momentic 2.17.5 → 2.17.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,39 +1,39 @@
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]="54b84a56-febc-5edb-b704-618fc9fa3bc2")}catch(e){}}();
4
- var i_=Object.defineProperty;var $e=(r,e)=>()=>(r&&(e=r(r=0)),e);var a_=(r,e)=>{for(var t in e)i_(r,t,{get:e[t],enumerable:!0})};var $v,Wv=$e(()=>{"use strict";$v=typeof globalThis=="object"?globalThis:global});var qv=$e(()=>{"use strict";Wv()});var Kv=$e(()=>{"use strict";qv()});var Cn,fg=$e(()=>{"use strict";Cn="1.9.0"});function L0(r){var e=new Set([r]),t=new Set,n=r.match(Yv);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===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(Yv);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[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 Yv,Xv,Jv=$e(()=>{"use strict";fg();Yv=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Xv=L0(Cn)});function la(r,e,t,n){var o;n===void 0&&(n=!1);var i=Is[_s]=(o=Is[_s])!==null&&o!==void 0?o:{version:Cn};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==Cn){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Cn);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Cn+"."),!0}function xn(r){var e,t,n=(e=Is[_s])===null||e===void 0?void 0:e.version;if(!(!n||!Xv(n)))return(t=Is[_s])===null||t===void 0?void 0:t[r]}function ca(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Cn+".");var t=Is[_s];t&&delete t[r]}var N0,_s,Is,Ps=$e(()=>{"use strict";Kv();fg();Jv();N0=Cn.split(".")[0],_s=Symbol.for("opentelemetry.js.api."+N0),Is=$v});function Ms(r,e,t){var n=xn("diag");if(n)return t.unshift(e),n[r].apply(n,k0([],D0(t),!1))}var D0,k0,Qv,Zv=$e(()=>{"use strict";Ps();D0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},k0=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},Qv=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ms("verbose",this._namespace,e)},r}()});var Ge,au=$e(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(Ge||(Ge={}))});function eR(r,e){r<Ge.NONE?r=Ge.NONE:r>Ge.ALL&&(r=Ge.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",Ge.ERROR),warn:t("warn",Ge.WARN),info:t("info",Ge.INFO),debug:t("debug",Ge.DEBUG),verbose:t("verbose",Ge.VERBOSE)}}var tR=$e(()=>{"use strict";au()});var F0,U0,B0,on,Os=$e(()=>{"use strict";Zv();tR();au();Ps();F0=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},U0=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},B0="diag",on=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=xn("diag");if(l)return l[o].apply(l,U0([],F0(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:Ge.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=xn("diag"),d=eR((l=i.logLevel)!==null&&l!==void 0?l:Ge.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 la("diag",d,t,!0)};t.setLogger=n,t.disable=function(){ca(B0,t)},t.createComponentLogger=function(o){return new Qv(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var rR,nR=$e(()=>{"use strict";rR=Symbol("BaggageEntryMetadata")});function Sg(r){return typeof r!="string"&&(z0.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:rR,toString:function(){return r}}}var z0,oR=$e(()=>{"use strict";Os();nR();z0=on.instance()});function yg(r){return Symbol.for(r)}var H0,Eg,Tg=$e(()=>{"use strict";H0=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),Eg=new H0});function Rg(){return vg}var ri,G0,su,V0,j0,$0,W0,bg,q0,K0,Y0,vg,X0,J0,Q0,Z0,eF,tF,rF,Ag=$e(()=>{"use strict";ri=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),G0=function(){function r(){}return r.prototype.createGauge=function(e,t){return J0},r.prototype.createHistogram=function(e,t){return Q0},r.prototype.createCounter=function(e,t){return X0},r.prototype.createUpDownCounter=function(e,t){return Z0},r.prototype.createObservableGauge=function(e,t){return tF},r.prototype.createObservableCounter=function(e,t){return eF},r.prototype.createObservableUpDownCounter=function(e,t){return rF},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),su=function(){function r(){}return r}(),V0=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(su),j0=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(su),$0=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(su),W0=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(su),bg=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),q0=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bg),K0=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bg),Y0=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bg),vg=new G0,X0=new V0,J0=new $0,Q0=new W0,Z0=new j0,eF=new q0,tF=new K0,rF=new Y0});var tr,iR=$e(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(tr||(tr={}))});var nF,oF,aR,sR=$e(()=>{"use strict";Tg();nF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},oF=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},aR=function(){function r(){}return r.prototype.active=function(){return Eg},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,oF([n],nF(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var iF,aF,wg,sF,lR,cR=$e(()=>{"use strict";sR();Ps();Os();iF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},aF=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},wg="context",sF=new aR,lR=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return la(wg,e,on.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,aF([e,t,n],iF(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return xn(wg)||sF},r.prototype.disable=function(){this._getContextManager().disable(),ca(wg,on.instance())},r}()});var ua,uR=$e(()=>{"use strict";cR();ua=lR.getInstance()});var G,dR=$e(()=>{"use strict";Os();G=on.instance()});var lF,pR,mR=$e(()=>{"use strict";Ag();lF=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return vg},r}(),pR=new lF});var Cg,gR,hR=$e(()=>{"use strict";mR();Ps();Os();Cg="metrics",gR=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return la(Cg,e,on.instance())},r.prototype.getMeterProvider=function(){return xn(Cg)||pR},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){ca(Cg,on.instance())},r}()});var lu,fR=$e(()=>{"use strict";hR();lu=gR.getInstance()});var Pe=$e(()=>{"use strict";oR();Tg();au();Ag();iR();uR();dR();fR()});var Ia=(r,e)=>{},Nd=!1;try{let r=await import("@sentry/node");Ia=r.captureException,r.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),Nd=!0}catch{}import{Command as aG,Option as Jt}from"@commander-js/extra-typings";import{execSync as sG}from"child_process";var Pa=!!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{existsSync as yO,statSync as EO}from"fs";import{z as sf}from"zod";var bG=sf.object({input:sf.string()});import{z as pt}from"zod";var AG=pt.object({srcs:pt.array(pt.string()),urls:pt.array(pt.string()),desiredSrc:pt.string().optional(),desiredUrl:pt.string().optional()}),lf=pt.object({srcRegex:pt.string().optional(),urlRegex:pt.string().optional()}),cf=pt.object({x:pt.number(),y:pt.number(),correlation:pt.number()}),wG=pt.object({searchImageBase64String:pt.string(),pageImageBase64String:pt.string(),id:pt.string().uuid(),timeoutMs:pt.number().max(1e4).min(0).optional()});import{z as k}from"zod";import*as F from"zod";import{extendZodWithOpenApi as s_}from"zod-openapi";s_(F);var Ln=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(Ln||{}),l_=F.object({mPathSelectorTokens:F.string().array(),frameSrcRegex:F.string().optional(),frameUrlRegex:F.string().optional(),indices:F.number().array()}),Dd=F.object({result:F.number(),traceId:F.string()}).array(),Ei=F.object({type:F.literal("GCS_TRACES"),traces:Dd}),uf=F.object({text:F.string().optional(),attributes:F.record(F.string(),F.string()).optional(),boundingBox:F.object({x:F.number(),y:F.number(),width:F.number(),height:F.number()}).optional()}),c_=F.object({selectors:F.string().array(),requirements:uf.optional()}),Nn=F.object({id:F.number().int(),dataMomenticId:F.number().int().optional(),selector:F.string().optional(),hybridSelector:F.object({textContent:F.string().nullish(),attributes:F.record(F.string(),F.string()),tagName:F.string(),expandShadowRoot:F.boolean().optional(),classNames:F.string().array(),nthChild:F.number()}).array().optional(),generatedSelectors:F.string().array().optional(),requirements:uf.optional(),additionalElements:c_.array().optional(),role:F.string().optional(),name:F.string().optional(),numChildren:F.number().optional(),content:F.string().optional(),pathFromRoot:F.string().optional(),serializedHtml:F.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:F.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:F.string().url().optional(),boundingBox:F.object({x:F.number().optional(),y:F.number().optional(),width:F.number(),height:F.number()}).describe("css pixel bounding box").optional(),frameCache:l_.optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(Ln).optional(),targetUpdateTime:F.string().optional(),targetUpdateLoggerTags:F.record(F.string(),F.string()).optional(),cacheResolutionUpdateSource:F.string().optional(),cacheResolutionUpdateTime:F.string().optional(),cacheResolutionUpdateLoggerTags:F.record(F.string(),F.string()).optional(),memory:Ei.optional()}).openapi({ref:"ElementTargetCache"});function df(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var u_=F.object({type:F.literal("description"),elementDescriptor:F.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),d_=F.object({x:F.number(),y:F.number()}),p_=F.object({type:F.literal("coordinates"),pixels:d_}).openapi({ref:"CoordinatesTarget"});function Dn(r){return r.type==="description"}function Hr(r){return r.type==="coordinates"}var _t=F.discriminatedUnion("type",[u_,p_]).openapi({ref:"ElementTarget"});function kd(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function It(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.pixels.x}, y: ${r.pixels.y}`}}function cl(r){return Ei.safeParse(r).success}import{v4 as Se}from"uuid";import*as v from"zod";import{extendZodWithOpenApi as T_}from"zod-openapi";import{z as ne}from"zod";import{extendZodWithOpenApi as m_}from"zod-openapi";import{z as Ti}from"zod";var Fd=Ti.object({result:Ti.boolean(),traceId:Ti.string()}).array(),Ud=Ti.object({type:Ti.literal("GCS_TRACES"),traces:Fd}),Bd=Ti.object({memory:Ud.optional()});m_(ne);var pf=ne.object({plan:ne.string().optional(),evidence:ne.string().optional(),thoughts:ne.string(),result:ne.boolean(),relevantElements:ne.array(ne.number()).optional(),updatedMemory:Fd.optional()}),kn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(kn||{});var g_=ne.object({type:ne.literal("ELEMENT_NAME"),negated:ne.boolean().optional(),operation:ne.nativeEnum(kn),value:ne.string()}).openapi({ref:"ElementNameAssertion"}),h_=ne.object({type:ne.literal("ELEMENT_STYLE"),negated:ne.boolean().optional(),operation:ne.nativeEnum(kn),property:ne.string(),value:ne.string()}).openapi({ref:"ElementStyleAssertion"}),f_=ne.object({type:ne.literal("ELEMENT_CONTENT"),negated:ne.boolean().optional(),operation:ne.nativeEnum(kn),value:ne.string()}).openapi({ref:"ElementContentAssertion"}),S_=ne.object({type:ne.literal("ELEMENT_ATTRIBUTE"),negated:ne.boolean().optional(),operation:ne.nativeEnum(kn),attr:ne.string(),value:ne.string()}).openapi({ref:"ElementAttributeValueAssertion"}),bi=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(bi||{}),y_=ne.object({type:ne.literal("ELEMENT_EXISTENCE"),negated:ne.boolean().optional(),condition:ne.nativeEnum(bi).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),mf=ne.discriminatedUnion("type",[f_,S_,y_,g_,h_]).openapi({ref:"ManualElementAssertion"});var E_=ne.object({type:ne.literal("CONTENT"),negated:ne.boolean().optional(),value:ne.string()}).openapi({ref:"PageContentAssertion"}),gf=ne.discriminatedUnion("type",[E_]).openapi({ref:"ManualPageAssertion"});import Bt from"zod";var zd=Bt.discriminatedUnion("type",[Bt.object({type:Bt.literal("SUBSTRING"),url:Bt.string()}),Bt.object({type:Bt.literal("GLOB"),glob:Bt.string()}),Bt.object({type:Bt.literal("REGEX"),regex:Bt.string()}),Bt.object({type:Bt.literal("DOMAIN"),domain:Bt.string()})]),Ma=Bt.object({urlMatcher:zd,method:Bt.string().optional()});import{z as fe}from"zod";var ul=fe.object({url:fe.string(),method:fe.union([fe.literal("GET"),fe.literal("POST"),fe.literal("PUT"),fe.literal("DELETE"),fe.literal("PATCH")]),headers:fe.record(fe.string(),fe.string()).optional(),params:fe.record(fe.string(),fe.string()).optional(),body:fe.string().optional(),timeout:fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),hf=fe.object({url:fe.string(),headers:fe.record(fe.string(),fe.string()).optional(),query:fe.string(),variables:fe.string().optional(),timeout:fe.number().int().optional().describe("Max seconds to wait for the request to complete")}),dl=fe.object({code:fe.string(),fragment:fe.boolean().optional(),environment:fe.union([fe.literal("NODE"),fe.literal("BROWSER")]).optional().describe("default NODE"),timeout:fe.number().int().max(60).optional().describe("Max seconds for the code to complete")});var We=(V=>(V.AI_EXTRACT="AI_EXTRACT",V.AI_ASSERTION="AI_ASSERTION",V.AUTH_LOAD="AUTH_LOAD",V.AUTH_SAVE="AUTH_SAVE",V.BLUR="BLUR",V.CAPTCHA="CAPTCHA",V.CLICK="CLICK",V.COOKIE="COOKIE",V.COPY="COPY",V.DIALOG="DIALOG",V.DRAG="DRAG",V.ELEMENT_CHECK="ELEMENT_CHECK",V.FILE_UPLOAD="FILE_UPLOAD",V.FOCUS="FOCUS",V.GO_BACK="GO_BACK",V.GO_FORWARD="GO_FORWARD",V.HOVER="HOVER",V.JAVASCRIPT="JAVASCRIPT",V.LOCAL_STORAGE="LOCAL_STORAGE",V.MOUSE_DRAG="MOUSE_DRAG",V.NAVIGATE="NAVIGATE",V.NEW_TAB="NEW_TAB",V.PAGE_CHECK="PAGE_CHECK",V.PASTE="PASTE",V.PRESS="PRESS",V.KEY_DOWN="KEY_DOWN",V.KEY_UP="KEY_UP",V.REFRESH="REFRESH",V.REQUEST="REQUEST",V.GRAPHQL_REQUEST="GRAPHQL_REQUEST",V.SCROLL_DOWN="SCROLL_DOWN",V.SCROLL_UP="SCROLL_UP",V.SCROLL_LEFT="SCROLL_LEFT",V.SCROLL_RIGHT="SCROLL_RIGHT",V.SELECT_OPTION="SELECT_OPTION",V.SWITCH_TAB="TAB",V.TYPE="TYPE",V.VISUAL_DIFF="VISUAL_DIFF",V.WAIT="WAIT",V.WAIT_FOR_URL="WAIT_FOR_URL",V.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",V.AWAIT_LISTENER="AWAIT_LISTENER",V.RECORD_REQUESTS="RECORD_REQUESTS",V.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",V.SET_HEADER="SET_HEADER",V.MOCK_ROUTE="MOCK_ROUTE",V.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",V.OFFLINE_MODE="OFFLINE_MODE",V.SUCCESS="SUCCESS",V))(We||{});T_(v);var K=v.object({thoughts:v.string().optional(),id:v.string().uuid().describe("unique identifier to this step, used for step cache")}),ar=v.object({useSelector:v.boolean().optional(),force:v.boolean().optional(),disableCache:v.boolean().optional().describe("disable element caching for this step"),iframeUrl:v.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Qt=v.object({target:Nn}).optional().openapi({ref:"SingleTargetCache"});function ff(r){return Qt.safeParse(r).success}var ml=v.object({loadTimeout:v.number().int().max(60).optional().describe("Max seconds for the page to load")}),Gd=K.merge(ml).merge(v.object({type:v.literal("NAVIGATE"),url:v.string()})).openapi({ref:"NavigateCommand"}),gl=ar.merge(v.object({cache:Qt})),Fn=K.merge(gl.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_UP"),deltaY:v.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Un=K.merge(gl.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_DOWN"),deltaY:v.number().optional()}))).openapi({ref:"ScrollDownCommand"}),vi=K.merge(gl.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_LEFT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ri=K.merge(gl.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_RIGHT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollRightCommand"}),XG=v.discriminatedUnion("type",[Fn,Un,vi,Ri]).openapi({ref:"AllScrollCommands"}),b_=K.merge(v.object({type:v.literal("DIALOG"),action:v.union([v.literal("ACCEPT"),v.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),v_=K.merge(v.object({type:v.literal("WAIT"),delay:v.number()})).openapi({ref:"WaitCommand"}),R_=v.object({caseInsensitive:v.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:v.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:v.number().int().optional().describe("Max seconds to wait for the URL to match")}),Vd=K.extend({type:v.literal("WAIT_FOR_URL"),matcher:zd}).merge(R_).openapi({ref:"WaitUrlCommand"}),A_=K.merge(ml).merge(v.object({type:v.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),w_=K.merge(v.object({type:v.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),C_=K.merge(v.object({type:v.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),x_=K.extend({type:v.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),__=K.extend({type:v.literal("AUTH_LOAD"),storageState:v.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),jd=K.merge(ar).extend({type:v.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),I_=K.extend({type:v.literal("COPY"),value:v.string()}).openapi({ref:"CopyCommand"}),P_=K.extend({type:v.literal("PASTE")}).openapi({ref:"PasteCommand"}),$d=K.merge(dl).extend({type:v.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ao=K.merge(ar).extend({type:v.literal("CLICK"),target:_t,doubleClick:v.boolean().optional(),rightClick:v.boolean().optional(),waitForDownload:v.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:v.number().optional(),downloadTimeoutMs:v.number().optional(),cache:Qt,relativePosition:v.object({x:v.number(),y:v.number()}).optional()}).openapi({ref:"ClickCommand"}),Wd=v.object({fromTarget:Nn.optional(),toTarget:Nn.optional()}),Oa=K.merge(ar).merge(v.object({type:v.literal("DRAG"),fromTarget:_t,toTarget:_t,steps:v.number().optional(),hoverSeconds:v.number().optional().describe("Seconds to hover the object before dropping"),cache:Wd.optional()})).openapi({ref:"DragCommand"}),La=K.merge(ar).merge(v.object({type:v.literal("MOUSE_DRAG"),target:_t.optional(),deltaX:v.string().describe("pixels to move horizontally, can be template"),deltaY:v.string().describe("pixels to move vertically, can be template"),steps:v.number().optional(),cache:Qt})).openapi({ref:"MouseDragCommand"}),wo=K.merge(ar).merge(v.object({type:v.literal("HOVER"),target:_t,cache:Qt})).openapi({ref:"HoverCommand"}),Na=K.merge(ar).merge(v.object({type:v.literal("FOCUS"),target:_t,cache:Qt})).openapi({ref:"FocusCommand"}),Da=K.merge(ar).extend({type:v.literal("BLUR"),target:_t.optional(),cache:Qt}).openapi({ref:"BlurCommand"}),M_=v.object({type:v.literal("URL"),url:v.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),O_=v.object({type:v.literal("USER_FILE"),name:v.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),L_=K.extend({type:v.literal("FILE_UPLOAD"),fileSource:v.discriminatedUnion("type",[M_,O_]),filename:v.string().optional()}).openapi({ref:"FileUploadCommand"}),N_=v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.coerce.string()})]),Co=K.merge(ar).extend({type:v.literal("SELECT_OPTION"),target:_t,cache:Qt,choice:N_.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),qd=v.union([v.literal("MULTIMODAL"),v.literal("VISION_ONLY")]),Ai=K.merge(v.object({type:v.literal("AI_ASSERTION"),assertion:v.string(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional(),contextChoice:qd.optional(),timeout:v.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Bd.optional()})).openapi({ref:"AIAssertionCommand"}),Gr=5,Kd=600,xo=K.merge(ar).extend({type:v.literal("ELEMENT_CHECK"),target:_t,assertion:mf,cache:Qt.or(Bd).optional(),timeout:v.number().int().min(0).max(Kd).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Yd=K.extend({type:v.literal("PAGE_CHECK"),assertion:gf,iframeUrl:v.string().optional().describe("url or url regex for the iframe"),timeout:v.number().int().min(0).max(Kd).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),D_=K.merge(v.object({type:v.literal("AI_EXTRACT"),goal:v.string(),schema:v.string().optional(),envKey:v.string().optional(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional()})).openapi({ref:"AIExtractCommand"}),k_=v.object({clearContent:v.boolean().optional(),forceClearContent:v.boolean().optional(),delay:v.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:v.boolean().optional(),pressEnter:v.boolean().optional()}),Sf=25,_o=K.merge(ar).merge(k_).extend({type:v.literal("TYPE"),target:_t.optional(),value:v.string(),cache:Qt}).openapi({ref:"TypeCommand"}),Xd=K.merge(v.object({type:v.literal("PRESS"),value:v.string(),repeat:v.number().optional(),convertMeta:v.boolean().optional(),delayMs:v.number().optional()})).openapi({ref:"PressCommand"}),F_=K.merge(v.object({type:v.literal("KEY_DOWN"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyDownCommand"}),U_=K.merge(v.object({type:v.literal("KEY_UP"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyUpCommand"}),B_=v.object({type:v.literal("SUBSTRING"),substring:v.string()}),z_=v.object({type:v.literal("REGEX"),pattern:v.string()}),H_=v.object({type:v.literal("INDEX"),index:v.coerce.string()}),G_=v.discriminatedUnion("type",[B_,z_,H_]),V_=K.merge(ml).merge(v.object({type:v.literal("TAB"),action:G_})).openapi({ref:"TabCommand"}),Jd=K.merge(ml).merge(v.object({type:v.literal("NEW_TAB"),url:v.string()})).openapi({ref:"NewTabCommand"}),j_=K.merge(v.object({type:v.literal("COOKIE"),value:v.string()})).openapi({ref:"CookieCommand"}),$_=K.merge(v.object({type:v.literal("LOCAL_STORAGE"),key:v.string(),value:v.string()})).openapi({ref:"LocalStorageCommand"}),W_=K.extend({type:v.literal("REQUEST")}).merge(ul).openapi({ref:"RequestCommand"}),q_=K.extend({type:v.literal("GRAPHQL_REQUEST")}).merge(hf).openapi({ref:"GraphQLRequestCommand"}),K_=K.merge(v.object({type:v.literal("SUCCESS"),condition:Ai.optional()})).openapi({ref:"SuccessCommand"}),Y_=K.merge(v.object({type:v.literal("FAILURE")})).openapi({ref:"FailureCommand"}),X_=v.object({data:v.string().describe("location at which to find a jpg"),width:v.number(),height:v.number()}),ka=K.merge(ar).merge(v.object({type:v.literal("VISUAL_DIFF"),threshold:v.number().optional().describe("default 0.1"),target:_t.optional(),screenshot:X_.optional(),cache:Qt})).openapi({ref:"VisualDiffCommand"}),J_=K.merge(v.object({type:v.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Ma,key:v.string()})).openapi({ref:"RegisterRequestListenerCommand"}),Q_=K.merge(v.object({type:v.literal("AWAIT_LISTENER"),key:v.string(),timeout:v.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Z_=K.merge(v.object({type:v.literal("RECORD_REQUESTS"),requestMatcher:Ma,key:v.string()})).openapi({ref:"RecordRequestsCommand"}),eI=K.merge(v.object({type:v.literal("GET_RECORDED_REQUESTS"),key:v.string()})).openapi({ref:"GetRecordedRequestsCommand"}),tI=K.merge(v.object({type:v.literal("SET_HEADER"),name:v.string(),value:v.string(),requestMatcher:Ma.optional()})).openapi({ref:"SetHeaderCommand"}),rI=K.merge(v.object({type:v.literal("MOCK_ROUTE"),requestMatcher:Ma,responseGenerator:v.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:v.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:v.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"})),nI=K.merge(v.object({type:v.literal("REMOVE_ROUTE_MOCK"),key:v.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),oI=K.merge(v.object({type:v.literal("OFFLINE_MODE"),enable:v.boolean()})).openapi({ref:"OfflineModeCommand"}),yf=v.discriminatedUnion("type",[Ao,_o,Xd,F_,U_,Co,Gd,Un,Fn,Ai,wo,v_,K_]),iI=v.discriminatedUnion("type",[D_,__,x_,jd,j_,I_,b_,Oa,xo,L_,w_,C_,$d,$_,La,Jd,Yd,P_,A_,W_,q_,vi,Ri,V_,ka,Na,Da,Vd,J_,Q_,Z_,eI,tI,rI,nI,oI]),wi=v.discriminatedUnion("type",[...yf.options,...iI.options]).openapi({ref:"Command"}),hl=v.discriminatedUnion("type",[...yf.options,Y_]);function pn(r){let e;switch(r){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:Se(),type:r};break;case"AUTH_LOAD":{e={id:Se(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:Se(),type:r,goal:""};break;case"DIALOG":e={id:Se(),type:r,action:"DISMISS"};break;case"DRAG":e={id:Se(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Se(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Se(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:Se(),type:r,delay:1};break;case"BLUR":e={id:Se(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Se(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Se(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:Se(),type:r,value:""};break;case"SELECT_OPTION":e={id:Se(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:Se(),type:r,url:""};case"TAB":e={id:Se(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:Se(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Se(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Se(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:Se(),type:r,code:""};break;case"AI_ASSERTION":e={id:Se(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:Se(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Se(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Se(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:Se(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:Se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:Se(),type:r,key:""};break}case"SET_HEADER":{e={id:Se(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:Se(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:Se(),type:r};break}case"OFFLINE_MODE":{e={id:Se(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function Ef(r){switch(r.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(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as aI}from"zod";var tV=aI.discriminatedUnion("type",[Da,jd,Ao,Oa,Na,wo,La,Fn,Un,vi,Ri,Co,_o,ka,xo]);function Tf(r){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(r)}import{z as sI}from"zod";import{z as Bn}from"zod";function Fa(r){return Bn.object({key:Bn.string(),testId:Bn.string().optional(),moduleId:Bn.string().optional(),organizationId:Bn.string(),value:r})}function Ua(r){return Fa(r).extend({uniqueKey:Bn.string()})}function fl(r){return Bn.record(Bn.string(),Ua(r))}var zt={type:!0,cache:!0},mn=sI.discriminatedUnion("type",[Ai.pick(zt),Da.pick(zt),Ao.pick(zt),Oa.pick(zt),xo.pick(zt),Na.pick(zt),wo.pick(zt),La.pick(zt),Fn.pick(zt),Un.pick(zt),vi.pick(zt),Ri.pick(zt),Co.pick(zt),_o.pick(zt),ka.pick(zt)]),Sl=Object.values(We).filter(r=>mn.options.some(e=>e.shape.type.safeParse(r).success));wi.options.forEach(r=>{if("target"in r.shape&&!Sl.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function bf(r){return Sl.includes(r.type)}var vf=Fa(mn),Rf=Ua(mn),cV=fl(mn);import{z as Qd}from"zod";import{extendZodWithOpenApi as uI}from"zod-openapi";import{z as Af}from"zod";import{extendZodWithOpenApi as lI}from"zod-openapi";import{z as Io}from"zod";var sr=Io.object({index:Io.number().optional().describe("global index within a test (in-order traversal)"),id:Io.string(),skipped:Io.boolean().optional(),envKey:Io.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Io.boolean().optional(),retries:Io.number().optional()});lI(Af);var cI=sr.extend({type:Af.literal("PRESET_ACTION")}),Zt=cI.extend({command:wi}).openapi({ref:"PresetAction"});uI(Qd);var Po=sr.extend({type:Qd.literal("AI_ACTION"),text:Qd.string(),steps:Zt.array().optional()}).openapi({ref:"AIAction"});import{z as Ht}from"zod";import{z as yl}from"zod";import{extendZodWithOpenApi as dI}from"zod-openapi";dI(yl);var Ci=sr.extend({type:yl.literal("AI_ACTION_DYNAMIC"),text:yl.string(),retries:yl.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as wf}from"zod";var Zd=sr.extend({type:wf.literal("CONDITIONAL"),skipped:wf.boolean().optional()});import{z as de}from"zod";var pI=de.object({cacheKey:de.string(),cacheExpiryMs:de.number()}),ep=sr.extend({id:de.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:de.record(de.string()).optional(),cacheConfig:pI.optional()}),xr=ep.extend({type:de.literal("MODULE"),moduleId:de.string().uuid()}),mI=de.union([xr.pick({type:!0,moduleId:!0}),de.record(de.unknown())]),gI=de.object({type:de.literal("URL_REGEX"),regex:de.string()}),hI=de.object({type:de.literal("PAGE_CHECK"),substring:de.string()}),tp=de.object({cacheInvalidation:de.discriminatedUnion("type",[hI,gI]).optional()}),Wt=de.object({moduleId:de.string().uuid(),name:de.string(),description:de.string().nullish(),enabled:de.boolean().nullish(),parameters:de.string().array().nullish(),defaultParameters:de.record(de.string(),de.string()).nullish(),parameterEnums:de.record(de.string(),de.string().array()).nullish(),defaultCacheKey:de.string().nullish(),defaultCacheTtl:de.number().nullish(),defaultCacheAllInvocations:de.boolean().nullish(),autoAuth:de.boolean().nullish(),advanced:tp.nullish()});var rp=r=>r.type==="AI_ACTION"||r.type==="AI_ACTION_DYNAMIC"||r.type==="PRESET_ACTION";import{z as lr}from"zod";var np=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(np||{});var fI=lr.discriminatedUnion("type",[lr.object({type:lr.literal("NAVIGATE_URL"),url:lr.string().url()}),lr.object({type:lr.literal("GO_TO_SECTION_START")})]),SI=lr.object({trigger:lr.nativeEnum(np).optional(),attempts:lr.number().int().optional(),restartBehavior:fI}),Ba=sr.extend({type:lr.literal("SECTION"),description:lr.string().describe("user provided goal of what the section should accomplish"),plan:lr.string().array().optional(),autohealingConfig:SI.optional()});var Cf=Wt.merge(ep).extend({type:Ht.literal("RESOLVED_MODULE"),steps:Ht.lazy(()=>Ze.array())}),za=Wt.extend({steps:Ht.lazy(()=>Ze.array())}),op=Ba.extend({steps:Ht.lazy(()=>Oe.array())}),yI=Ba.extend({steps:Ht.lazy(()=>Ze.array())}),Mo=Zd.extend({blocks:Ht.object({assertion:Ht.lazy(()=>Zt),steps:Ht.lazy(()=>Oe.array())}).array(),elseSteps:Ht.lazy(()=>Oe.array().optional())}),EI=Zd.extend({blocks:Ht.object({assertion:Ht.lazy(()=>Zt),steps:Ht.lazy(()=>Ze.array())}).array(),elseSteps:Ht.lazy(()=>Ze.array().optional())}),Oe=Ht.discriminatedUnion("type",[Zt,Po,Ci,xr,Mo,op]),Ze=Ht.discriminatedUnion("type",[Zt,Po,Ci,Cf,EI,yI]);import{z as cr}from"zod";var TI=cr.object({steps:Oe.array(),beforeSteps:Oe.array().nullish(),afterSteps:Oe.array().nullish()}),xi=cr.object({steps:Ze.array(),beforeSteps:Ze.array().nullish(),afterSteps:Ze.array().nullish()}),Oo=cr.object({steps:cr.record(cr.string(),cr.unknown()).array(),beforeSteps:cr.record(cr.string(),cr.unknown()).array().nullish(),afterSteps:cr.record(cr.string(),cr.unknown()).array().nullish()});var oe="1.0.21";var xf=k.object({phrase:k.string()}),ip=k.object({thoughts:k.string().optional(),result:k.union([k.literal("NOT_FOUND"),k.string(),k.number(),k.array(k.unknown()),k.record(k.unknown(),k.unknown()),k.unknown()])}),qj=k.object({text:k.string()}),_f=k.object({attributes:k.array(k.string()).optional(),text:k.boolean().optional(),boundingBox:k.boolean().optional()}),bI=k.object({id:k.number().int(),requirements:_f}),vI=bI.array(),If=k.object({thoughts:k.string(),review:k.string().optional(),id:k.number().int(),updatedMemory:Dd.optional(),requirements:_f.optional(),additionalElements:vI.optional()});var El=(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))(El||{});var Pf=k.object({thoughts:k.string(),category:k.nativeEnum(El)}),RI=k.discriminatedUnion("op",[k.object({op:k.literal("replace"),path:k.string(),value:k.string()}),k.object({op:k.literal("add"),path:k.string(),value:k.string()}),k.object({op:k.literal("remove"),path:k.string()})]),Kj=k.object({thoughts:k.string(),patches:RI.array()}),AI=[k.literal("add"),k.literal("replace"),k.literal("remove")],wI=k.object({op:k.union(AI),path:k.string(),value:Ze.optional()}),Mf=k.object({patches:wI.array(),thoughts:k.string()}),ap=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(ap||{}),Of=k.object({thoughts:k.string(),scenario:k.nativeEnum(ap),instructions:k.string().nullish()}),Lf=k.object({reasoning:k.string(),scenario:k.string(),patch:k.null().optional()}),Yj=k.object({thoughts:k.string(),evaluation:k.number().min(0).max(10)}),Xj=k.object({observations:k.string(),reasoning:k.string(),command:hl});var sp=k.object({summary:k.string(),reasoning:k.string(),evaluation:k.discriminatedUnion("type",[k.object({type:k.literal("DONE")}),k.object({type:k.literal("RIGHT_TRACK")}),k.object({type:k.literal("WRONG_TRACK"),feedback:k.string()}),k.object({type:k.literal("IMPOSSIBLE")})])}),Nf=k.object({categoryThoughts:k.string(),category:k.string(),relevantIds:k.number().array()});import{z as O}from"zod";import*as ie from"zod";var r$=ie.object({thoughts:ie.string().optional().describe("only provided if a description was provided"),target:Nn.optional().describe("only provided if a description was provided"),pageState:ie.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ie.object({label:ie.string(),value:ie.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ie.object({data:ie.string(),height:ie.number().int(),width:ie.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Tl=ie.union([ie.literal("ELEMENT_CHECK"),ie.literal("NEGATED_CHECK"),ie.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ie.literal("SELECT_OPTION"),ie.literal("TYPE")]);function Lo(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Ha=(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))(Ha||{}),_i=ie.object({matched:ie.boolean(),reason:ie.string().optional().describe("Human understandable description"),logs:ie.string().array().optional().describe("Logs for debugging")}),CI=_i.extend({type:ie.literal("USER_SELECTOR")}),xI=_i.extend({type:ie.literal("CSS_SELECTOR"),selectors:ie.string().array()}),_I=_i.extend({type:ie.literal("HYBRID_SELECTOR")}),II=_i.extend({type:ie.literal("HTML_DISTANCE"),distance:ie.number().optional(),closestElement:ie.string().optional(),savedElement:ie.string().optional()}),PI=_i.extend({type:ie.literal("TEMPLATE_MATCHING"),elementImageUrl:ie.string().url()}),MI=_i.extend({type:ie.literal("AUTO_FRAME"),logs:ie.string().array().optional()}),Df=ie.discriminatedUnion("type",[CI,xI,_I,II,PI,MI]);import{z as $a}from"zod";import{z as jI}from"zod";import*as j from"zod";import{extendZodWithOpenApi as kI}from"zod-openapi";import{cloneDeep as Ga}from"lodash-es";import Hf from"truncate-json";import*as ko from"zod";import{extendZodWithOpenApi as OI}from"zod-openapi";import{z as Pt}from"zod";import{z as Le}from"zod";var lp=Le.object({autoFollowNewTabs:Le.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Le.union([Le.boolean(),Le.literal("inputs-only")]).optional(),ignoreHrefForCaching:Le.boolean().optional(),disableSecondaryCacheResolution:Le.boolean().optional(),hybridSelectorMode:Le.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Le.boolean().optional(),visualActions:Le.boolean().optional(),autoExpandIframes:Le.boolean().optional(),disableHtmlSnapshots:Le.boolean().optional(),importantAttributes:Le.string().array().optional(),importantClasses:Le.string().array().optional(),importantStyles:Le.string().array().optional()});var kf=1e4,Ff=6e4,No=lp.extend({pageLoadTimeoutMs:Le.number().optional().refine(r=>r===void 0||r<=Ff&&r>=-1,{message:`Page load timeout must be between 0 and ${Ff/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Le.number().optional().refine(r=>r===void 0||r<=kf&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${kf/1e3} seconds`}),localChromeExtensionPaths:Le.string().array().optional(),extraHeaders:Le.record(Le.string(),Le.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Le.string().optional(),disableGpu:Le.boolean().optional(),bustCacheOnBoundingBoxChange:Le.boolean().optional().describe("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:Le.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Le.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.")});var ft="BASE_URL",bl="CURRENT_URL",Do="ENV_NAME",Ii="TEST_NAME",l$={[ft]:"https://www.google.com"},Uf=Pt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Bf=Pt.object({name:Pt.string(),variables:Pt.record(Pt.string().describe("variable name"),Pt.string().describe("variable value"))}),zf=Pt.object({name:Pt.string(),variables:Pt.record(Pt.string().describe("variable name"),Pt.unknown().describe("variable value")),browser:No.optional()});var c$=Pt.object({name:Pt.string(),variables:Pt.record(Pt.string().describe("variable name"),Pt.unknown().describe("variable value"))});OI(ko);var cp=ko.object({env:ko.record(ko.unknown())}).openapi({ref:"TestContextSnapshot"}),LI="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",NI=[ft,Do,Ii],Gf=[bl,ft,Do,Ii],qt=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[ft]??"about:blank",o=e.env[bl]??"about:blank",i=e.env[Do],a=e.env[Ii],l={};for(let[s,u]of Object.entries(e.env))Gf.includes(s)||(t??{})[s]===void 0&&(l[s]=u);return new r({baseUrl:n,currentUrl:o,dynamicVariables:l,envName:i,testName:a,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=Ga(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){NI.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Do]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Ga(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Gf.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,LI]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Hf(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Hf(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[bl]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Ga(e.variablesFromEnvironment),this.setMomenticSystemVariable(ft,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Do,e.envName),e.testName&&this.setMomenticSystemVariable(Ii,e.testName)}getDynamicVariablesCopy(){return Ga(this.env)}getVariablesFromEnvironmentCopy(){return Ga(this.varsFromMomenticEnvironment)}};var ve=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(ve||{}),vl=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(vl||{});import{z as Vr}from"zod";import{extendZodWithOpenApi as DI}from"zod-openapi";DI(Vr);var pe=(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))(pe||{});var Vf=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Rl={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"},Pi={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."},up=Vr.object({reason:Vr.nativeEnum(pe),previousStepsDescription:Vr.array(Vr.string()).optional(),summary:Vr.string(),rootCause:Vr.string().optional()}).openapi({ref:"TestResultClassification"}),Al=Vr.object({errorMessage:Vr.string(),errorStack:Vr.string().optional(),classification:up.optional()}).openapi({ref:"TestFailureDetails"});kI(j);var dp=j.object({beforeUrl:j.string().optional(),afterUrl:j.string().optional(),message:j.string().optional(),beforeSnapshot:j.string().optional(),afterSnapshot:j.string().optional(),startedAt:j.coerce.date(),finishedAt:j.coerce.date()}),FI=dp.extend({viewport:j.object({height:j.number(),width:j.number()}).nullish(),status:j.nativeEnum(vl),message:j.string().optional(),elementInteracted:j.string().optional()}),Fo=dp.extend({status:j.nativeEnum(ve),message:j.string().optional(),data:j.unknown().optional(),beforeTestContext:cp.optional(),afterTestContext:cp.optional(),failureReason:j.nativeEnum(pe).optional(),details:j.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"}),pp=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(pp||{}),wl=Fo.merge(Zt).extend({results:FI.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:j.lazy(()=>mt.array()).optional(),failureRecoveryStatus:j.object({type:j.nativeEnum(pp),message:j.string()}).optional()}),UI=Fo.merge(Po).extend({results:j.lazy(()=>wl.array()),previousAttempts:j.lazy(()=>mt.array()).optional()}),BI=Fo.merge(Ci).extend({results:j.lazy(()=>wl.array()),previousAttempts:j.lazy(()=>mt.array()).optional()}),zI=Fo.merge(xr).extend({moduleName:j.string().optional(),results:j.lazy(()=>mt.array()),previousAttempts:j.lazy(()=>mt.array()).optional()}),HI=Fo.merge(Mo).extend({assertion:wl.optional(),results:j.lazy(()=>mt.array()).describe("results for the block actually executed"),previousAttempts:j.lazy(()=>mt.array()).optional()}),GI=Fo.merge(Ba).extend({results:j.lazy(()=>mt.array()),healingAttempts:j.lazy(()=>mt.array().array()).optional(),previousAttempts:j.lazy(()=>mt.array()).optional()}),mt=j.discriminatedUnion("type",[UI,BI,wl,zI,HI,GI]),Cl=Fo.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),VI=dp.extend({index:j.number().optional(),description:j.string(),pageState:j.string().optional(),elementInteracted:j.string().optional(),startedAt:j.coerce.date().or(j.string()).optional().catch(void 0),finishedAt:j.coerce.date().or(j.string()).optional().catch(void 0)}),xl=VI.extend({beforeScreenshot:j.string().optional(),afterScreenshot:j.string().optional()});var mp=jI.object({results:mt.array().describe("main results"),beforeResults:mt.array().optional(),afterResults:mt.array().optional()}),Va=mp.partial();import{z as B}from"zod";import{extendZodWithOpenApi as XI}from"zod-openapi";var Mi=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Mi||{});import{isValidCron as $I}from"cron-validator";import{z as le}from"zod";import{z as gp}from"zod";var gn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(gn||{});var _l=gp.object({width:gp.number().min(200).max(1e4),height:gp.number().min(200).max(1e4)}),jf={"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}},F$=Object.keys(jf);var Mt=jf["Desktop Large"],zn="en-us",Hn="America/Los_Angeles";var Gn={latitude:37.7749,longitude:-122.4194};var $f=["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 Wf=2e3,Il=No.extend({browserType:le.nativeEnum(gn).optional(),slowMoMs:le.number().optional().refine(r=>r===void 0||r<=Wf&&r>=-1,{message:`Slow motion must be between 0 and ${Wf} milliseconds`}),basicAuthorization:le.object({username:le.string().optional(),password:le.string().optional()}).optional(),geolocation:le.object({latitude:le.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:le.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:le.boolean().optional(),locale:le.string().optional(),timezone:le.enum($f).optional(),colorScheme:le.enum(["light","dark"]).optional()}),qf=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],hp=le.object({useMemory:le.boolean().optional(),failureRecovery:le.boolean().optional().describe("undefined means inherit org settings")}),WI=hp.extend({disableAICaching:le.boolean().optional(),failureRecoveryInstructions:le.string().optional()}),qI=le.object({viewport:_l.optional()}),Uo=qI.merge(WI).merge(Il),Oi=le.object({cron:le.string().refine(r=>$I(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:le.boolean().default(!1),env:le.string().optional(),timeZone:le.string().default("America/Los_Angeles"),jobKey:le.string().optional()}),Li=le.object({onSuccess:le.boolean().default(!1),failureMessage:le.string().optional(),onFailure:le.boolean().default(!0),successMessage:le.string().optional()}),KI=le.object({name:le.string(),required:le.boolean().optional(),defaultValue:le.string().describe("this is not optional because we need a value when the editor is first loaded")}),Pl=KI.array(),YI=le.object({name:le.string(),value:le.string()}),Kf=YI.array(),Ml=le.object({name:le.string(),default:le.boolean().optional(),fixtures:Uf.array().optional()});XI(B);var ur={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},me=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(me||{}),Ol=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Ol||{});var at=B.string().pipe(B.coerce.date()).or(B.date()),ja=B.object({id:B.string(),runKey:B.string(),organizationId:B.string(),executionType:B.nativeEnum(Mi).optional().default("WEB"),createdAt:at,createdBy:B.string(),flake:B.boolean().nullish(),scheduledAt:at.or(B.null()),startedAt:at.or(B.null()),updatedAt:at.nullish(),finishedAt:at.or(B.null()),resolvedBaseUrl:B.string().nullish(),environmentName:B.string().nullish(),gitBranchName:B.string().nullish(),githubRepository:B.string().nullish(),gitlabProjectPath:B.string().nullish(),labels:B.array(B.string()).optional(),gitOriginUrl:B.string().nullish(),gitCommitSha:B.string().nullish(),gitCommitShaShort:B.string().nullish(),gitCommitAuthorName:B.string().nullish(),cliVersion:B.string().nullish(),section:B.nativeEnum(Ol).nullish(),status:B.nativeEnum(me),trigger:B.nativeEnum(ur),attempts:B.number(),runAttempts:B.array(B.object({id:B.string(),status:B.nativeEnum(me),startedAt:at.or(B.null()),finishedAt:at.or(B.null())})).optional(),videos:B.array(B.string()).optional(),failureReason:B.nativeEnum(pe).nullish(),failureDetails:Al.nullish(),failureRecoveryDetails:B.record(B.string(),B.unknown()).nullish(),pipelineId:B.string().nullish(),resolvedInputs:B.record(B.string(),B.string()).nullish(),quarantined:B.boolean().nullish().default(!1),quarantinedReason:B.string().nullish(),localTestId:B.string().nullish(),testId:B.string().nullish(),testName:B.string().nullish(),description:B.string().nullish(),test:B.object({name:B.string(),id:B.string()}).nullish().default(null),suiteId:B.string().nullish()}).openapi({ref:"RunMetadata"}),JI={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Ll=ja.pick({...JI,test:!0}),Yf=ja.omit({failureReason:!0,failureDetails:!0,test:!0}),fp=ja.extend({stepsSnapshot:B.array(B.record(B.unknown())).nullish(),resolvedInputs:B.record(B.string(),B.string()).nullish(),test:B.object({name:B.string(),id:B.string(),description:B.string().nullish(),baseUrl:B.string().nullish(),advanced:Uo.nullish()}).nullish()}).merge(mp),Xf=r=>r.includes("PASSED")&&r.includes("FAILED");var QI=$a.object({id:$a.string().uuid(),startedAt:at.or($a.null()),finishedAt:at.or($a.null()),status:$a.nativeEnum(me)}).merge(Va),iW=QI.array();var Nl=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(Nl||{});import{z as st}from"zod";var ZI=st.object({id:st.string(),status:st.nativeEnum(me),trigger:st.nativeEnum(ur),createdAt:at,startedAt:at.nullish(),finishedAt:at.nullish(),gitCommitSha:st.string().nullish(),gitCommitShaShort:st.string().nullish(),gitCommitTimestamp:at.nullish(),gitBranchName:st.string().nullish(),gitOriginUrl:st.string().nullish(),gitCommitMessage:st.string().nullish(),gitCommitAuthorName:st.string().nullish(),githubRepository:st.string().nullish(),gitlabProjectPath:st.string().nullish(),pipelineId:st.string().nullish(),cliVersion:st.string().nullish(),labels:st.string().array().optional(),suite:st.object({id:st.string(),name:st.string()}).nullish(),runs:st.object({status:st.nativeEnum(me)}).array()}).openapi({ref:"RunGroup"}),Jf=ZI.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Ll.array()});import{z as St}from"zod";var eP=St.object({type:St.literal("TARGETING"),name:St.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Df.array(),pageState:St.string().optional(),targetSource:St.nativeEnum(Ln).optional(),targetUpdateTime:St.string().optional()}),tP=St.object({type:St.literal("AI_LOCATION"),matched:St.boolean(),pageState:St.string().optional(),ragUsed:St.boolean().optional(),thoughts:St.string().optional()}),rP=St.object({type:St.literal("ASSERTION"),relevantElementsSerialized:St.string().array().optional(),pageState:St.string().optional(),ragUsed:St.boolean().optional()}),Qf=St.discriminatedUnion("type",[eP,tP,rP]);function Dl(){return{details:[]}}import{z as rt}from"zod";var nP=rt.object({id:rt.string(),name:rt.string()}),EW=nP.merge(rt.object({createdAt:at,createdBy:rt.string(),schedule:Oi,notification:Li,environment:rt.object({name:rt.string()}).nullish(),beforeTests:rt.object({id:rt.string()}).array().nullish(),afterTests:rt.object({id:rt.string()}).array().nullish()})),Zf=rt.object({id:rt.string().uuid(),orgId:rt.string(),createdAt:at,startedAt:at.or(rt.null()),finishedAt:at.or(rt.null()),status:rt.nativeEnum(me),trigger:rt.nativeEnum(ur),suite:rt.object({id:rt.string(),name:rt.string()}).nullish(),runs:ja.array()}),TW=Zf.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),eS=Zf.extend({runs:Ll.array()});import{z as dr}from"zod";import{cloneDeep as RW}from"lodash-es";import{z as ye}from"zod";var IW=ye.object({thoughts:ye.string(),subGoals:ye.object({instruction:ye.string()}).array()}),PW=ye.object({thoughts:ye.string(),newPlanMarkdown:ye.string()}),MW=ye.object({thoughts:ye.string(),correct:ye.boolean(),failedActionIndex:ye.number().optional()}),oP=ye.object({type:ye.literal("PLANNING"),beforePlan:ye.string(),goalDecision:ye.string(),thoughts:ye.string()}),iP=ye.object({type:ye.literal("RUNNING"),stepDisplayName:ye.string(),status:ye.nativeEnum(ve),results:mt.array()}),aP=ye.object({type:ye.literal("REVISING"),beforePlan:ye.string(),afterPlan:ye.string(),errString:ye.string(),diffs:ye.string(),thoughts:ye.string()}),sP=ye.object({type:ye.literal("SYSTEM"),message:ye.string()}),lP=ye.discriminatedUnion("type",[oP,iP,aP,sP]),tS=lP.array();var kW=dr.object({id:dr.string(),scheduledAt:dr.coerce.date().nullable(),startedAt:dr.coerce.date().nullable(),finishedAt:dr.coerce.date().nullable(),status:dr.nativeEnum(me),history:tS.nullable(),testPlan:dr.object({id:dr.string(),name:dr.string()}).nullable(),test:dr.object({id:dr.string(),name:dr.string()}).nullable()});import{z as Gt}from"zod";var Sp=Gt.object({content:Gt.string(),ids:Gt.string().array(),tokenLength:Gt.number()}),cP=Gt.object({chunks:Sp.array()}),ZW=Gt.object({ids:Gt.string().array(),score:Gt.number(),tokenLength:Gt.number()}),eq=cP.extend({description:Gt.string().describe("Input to pass to RAG engine"),tokenLimit:Gt.number()}),rS=Gt.object({ids:Gt.number().array()}),nS=Gt.object({indices:Gt.number().array()});var Vt=O.object({disableCache:O.boolean().optional(),useMemory:O.boolean().optional(),loggerTags:O.record(O.string(),O.string()).optional(),langfuseSessionId:O.string().optional(),agentConfigVersion:O.string().optional()}),lq=Vt.extend({chunks:Sp.array(),description:O.string().describe("Input to pass to AI"),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),softTokenLimit:O.number(),hardTokenLimit:O.number()}),uP=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),oS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:Tl.optional().catch(void 0),memory:O.discriminatedUnion("type",[Ei,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),iS=O.object({target:O.string().or(O.number()),browserState:O.string().optional(),screenshot:O.string().optional(),boundingBox:O.object({x:O.number(),y:O.number(),height:O.number(),width:O.number()}).optional()}),aS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),dP=O.literal("NEGATED_CHECK"),sS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:qd.optional(),memory:O.discriminatedUnion("type",[Ud,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional(),source:dP.optional()}),lS=O.object({command:wi}),yp=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:uP.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),cS=O.object({results:xl.array(),errorMessage:O.string(),errorStack:O.string().optional()}),uS=O.object({results:xl.array(),goal:O.string(),errorMessage:O.string()}),dS=O.object({failedResults:xl.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),cq=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()}),pS=O.object({type:O.string(),browserContext:O.string(),currentStep:O.string(),screenshot:O.string()});import{z as Wa}from"zod";var pq=Wa.object({goal:Wa.string()}),mS=Wa.object({keywords:Wa.array(Wa.string())});import{z as Ep}from"zod";var kl=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(kl||{}),hq=Ep.nativeEnum(kl),pP=Ep.enum(["v1","v2"]),fq=pP.or(Ep.string().describe("for people with special configurations"));import{z as qe}from"zod";var gS=qe.object({attributesRequired:qe.array(qe.string()).optional(),textRequired:qe.boolean().optional(),boundsRequired:qe.boolean().optional()}),mP=qe.object({id:qe.number(),thoughts:qe.string(),requirements:gS.optional(),additionalElements:qe.object({id:qe.number(),requirements:gS}).array().optional()}),hS=qe.object({description:qe.string(),screenXml:qe.string(),screenshot:qe.string()}),fS=qe.object({assertion:qe.string(),screenXml:qe.string(),screenshot:qe.string()}),gP=qe.object({thoughts:qe.string(),result:qe.boolean(),relevantElements:qe.array(qe.number()).optional()});var SS=r=>!(!r.org_id||!r.user_id||!r.platform);import{z as Bo}from"zod";var yS=Bo.object({id:Bo.string().uuid(),skipped:Bo.boolean().optional(),envKey:Bo.string().optional().describe("key in the environment to save the result of this step to")}),Tp=yS.merge(ul).extend({type:Bo.literal("REQUEST")}),bp=yS.merge(dl).extend({type:Bo.literal("JAVASCRIPT")}),vp=Bo.discriminatedUnion("type",[bp,Tp]);import{z as pr}from"zod";import{z as zo}from"zod";var hP=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,xe=r=>{let e=r.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 Ni=zo.string().min(1).max(255).superRefine((r,e)=>{try{Vn(r)}catch(t){return e.addIssue({code:zo.ZodIssueCode.custom,message:t.message,fatal:!0}),zo.NEVER}});function Vn(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(hP))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Fl=zo.preprocess(r=>r===null?"":r,zo.union([zo.string().url(),zo.literal("")])).optional();var ES=pr.object({id:pr.string(),name:Ni,description:pr.string().optional().nullish(),baseUrl:Fl.nullish(),schemaVersion:pr.string(),advanced:pr.unknown().optional(),retries:pr.number(),envs:pr.array(Ml).nullish(),parameters:Pl.nullish()}),fP=pr.object({createdAt:pr.coerce.date(),updatedAt:pr.coerce.date(),schedule:Oi.nullish(),notification:Li.nullish(),createdBy:pr.string(),organizationId:pr.string()}),SP=ES.merge(fP),Gq=SP.extend({steps:vp.array()}),Vq=ES.extend({steps:vp.array()});import{z as Kt}from"zod";var TS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date(),status:Kt.nativeEnum(ve),message:Kt.string().optional(),data:Kt.unknown().optional()}),yP=TS.merge(bp).extend({type:Kt.literal("JAVASCRIPT")}),EP=TS.merge(Tp).extend({type:Kt.literal("REQUEST")}),TP=Kt.discriminatedUnion("type",[yP,EP]),bS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date().nullish(),status:Kt.nativeEnum(me),results:TP.array(),failureReason:Kt.string().nullish(),failureDetails:Al.nullish()});import{z as Yt}from"zod";var bP=Yt.object({id:Yt.string(),organizationId:Yt.string(),createdAt:Yt.coerce.date(),updatedAt:Yt.coerce.date(),createdBy:Yt.string(),scheduledAt:Yt.coerce.date().nullish(),startedAt:Yt.coerce.date().nullish(),finishedAt:Yt.coerce.date().nullish(),status:Yt.nativeEnum(me),trigger:Yt.nativeEnum(ur),results:bS.array().nullish(),apiTestName:Yt.string().nullish(),apiTestPath:Yt.string().nullish(),apiTestId:Yt.string().nullish()}),Zq=bP.pick({status:!0,startedAt:!0,finishedAt:!0});var qa=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(qa||{}),vS=3;function vP(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Rp(r){if(!vP(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Ap(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return vS;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 r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.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:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Di=class{trackStepExecution(){}async flush(){}};import{parseString as RP,splitCookiesString as AP}from"set-cookie-parser";import{z as Re}from"zod";var wp=Re.object({name:Re.string(),value:Re.string(),url:Re.string().optional(),domain:Re.string().optional(),path:Re.string().optional(),expires:Re.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Re.boolean().optional(),secure:Re.boolean().default(!0),sameSite:Re.union([Re.literal("Strict"),Re.literal("Lax"),Re.literal("None")]).default("None")});function Ul(r,e){let t=[],n=AP(r);for(let o of n){let i=RP(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 l=wp.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var wP=Re.object({origin:Re.string(),localStorage:Re.array(Re.object({name:Re.string(),value:Re.string()}))}),CP=Re.object({entries:Re.record(Re.string(),Re.array(Re.tuple([Re.unknown(),Re.unknown()]))),version:Re.number().optional()}),Bl=Re.object({cookies:wp.array().optional(),origins:wP.array().optional(),idb:Re.record(Re.string(),CP).optional().describe("key is db name")});function RS(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=wp.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import FP from"zod";import{v4 as v2}from"uuid";import{z as Ee}from"zod";import*as Ne from"zod";var AS=Ne.object({requiredText:Ne.string().optional(),requiredAttributes:Ne.record(Ne.string(),Ne.string()).optional(),requiredBounds:Ne.boolean().optional()}),xP=Ne.object({xPath:Ne.string(),requirements:AS.optional()}),_P=Ne.object({type:Ne.literal("NATIVE"),bounds:Ne.number().array(),resolvedDescription:Ne.string(),xPath:Ne.string(),elementOnlySerializedXml:Ne.string(),requirements:AS.optional(),requiredRelatedElements:xP.array().optional()}),IP=Ne.object({type:Ne.literal("WEBVIEW"),resolvedDescription:Ne.string(),xPath:Ne.string(),browserCache:Nn.optional()}),wS=Ne.discriminatedUnion("type",[_P,IP]);var ki=(s=>(s.AI_CHECK="AI_CHECK",s.TAP="TAP",s.TYPE="TYPE",s.PRESS="PRESS",s.OPEN_APP="OPEN_APP",s.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",s.JAVASCRIPT="JAVASCRIPT",s.ADB="ADB",s.STATE="STATE",s))(ki||{}),CS=(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))(CS||{}),xS=Ee.discriminatedUnion("type",[Ee.object({type:Ee.literal("description"),description:Ee.string()}),Ee.object({type:Ee.literal("coordinates"),xPercent:Ee.number(),yPercent:Ee.number()})]),hn=Ee.object({id:Ee.string().uuid(),disableCache:Ee.boolean().optional()}),PP=hn.extend({type:Ee.literal("STATE")}),_S=Ee.object({target:wS}),Cp=hn.extend({type:Ee.literal("TAP"),target:xS,cache:_S.optional()}),xp=hn.extend({type:Ee.literal("TYPE"),target:xS.optional(),cache:_S.optional(),text:Ee.string()}),MP=hn.extend({type:Ee.literal("OPEN_NOTIFICATION_DRAWER")}),OP=hn.extend({type:Ee.literal("PRESS"),key:Ee.nativeEnum(CS)}),LP=hn.extend({type:Ee.literal("OPEN_APP"),packageName:Ee.string(),activityName:Ee.string().optional()}),NP=hn.extend({type:Ee.literal("AI_CHECK"),assertion:Ee.string(),timeoutSecs:Ee.number().optional()}),DP=hn.extend({type:Ee.literal("JAVASCRIPT"),code:Ee.string(),timeout:Ee.number().int().max(60).optional().describe("Max seconds for the code to complete")}),kP=hn.extend({type:Ee.literal("ADB"),command:Ee.string()}),IS=Ee.discriminatedUnion("type",[Cp,xp,OP,LP,MP,NP,DP,kP,PP]);var PS={type:!0,cache:!0},Fi=FP.discriminatedUnion("type",[Cp.pick(PS),xp.pick(PS)]),P2=Object.values(ki).filter(r=>Fi.options.some(e=>e.shape.type.safeParse(r).success));var MS=Fa(Fi),OS=Ua(Fi),M2=fl(Fi);import{cloneDeep as N2}from"lodash-es";import k2 from"truncate-json";import jn from"zod";import Ka from"zod";var UP=Ka.object({id:Ka.string().uuid(),envKey:Ka.string().optional()}),fn=UP.extend({type:Ka.literal("MOBILE_PRESET_STEP"),command:IS}),H2=Ka.discriminatedUnion("type",[fn]);import Ke from"zod";var Ui=Ke.object({startTime:Ke.number(),endTime:Ke.number().optional(),error:Ke.string().optional()});var _p=Ui.extend({type:Ke.literal("SECTION"),name:Ke.string(),subSpans:Ke.lazy(()=>jP.array())}),BP=Ui.extend({type:Ke.literal("AI_LOCATOR_CALL"),result:Ke.object({serializedElement:Ke.string(),id:Ke.number(),thoughts:Ke.string()}).optional()}),zP=Ui.extend({type:Ke.literal("AI_ASSERTION_CALL"),result:Ke.object({thoughts:Ke.string(),result:Ke.boolean()}).optional()}),HP=Ui.extend({type:Ke.literal("WAIT_FOR_STABILITY"),reason:Ke.string().optional()}),GP=Ui.extend({type:Ke.literal("RESOLVE_TARGET_CACHE"),result:Ke.object({serializedElement:Ke.string()}).optional()}),VP=Ui.extend({type:Ke.literal("GET_EMULATOR_STATE")}),jP=Ke.discriminatedUnion("type",[_p,BP,zP,HP,GP,VP]);var $P=jn.object({message:jn.string().optional(),startTime:jn.number(),endTime:jn.number(),status:jn.nativeEnum(ve),trace:_p.optional().catch(void 0),beforeSnapshot:jn.string().optional(),afterSnapshot:jn.string().optional()}),WP=fn.merge($P).extend({data:jn.unknown().optional().describe("output data from the step")}),zl=WP;import lt from"zod";import{z as _r}from"zod";import{z as Ve}from"zod";var Ot=Ve.object({id:Ve.string(),name:Ni,baseUrl:Fl,description:Ve.string().optional().nullish(),schemaVersion:Ve.string(),advanced:Uo,retries:Ve.number(),envs:Ve.array(Ml).nullish(),parameters:Pl.nullish(),disabled:Ve.boolean().optional(),labels:Ve.array(Ve.string()).optional().catch([])}),eK=Ve.enum(["INHERIT","ENABLED","DISABLED"]);var qP=Uo.extend({failureRecovery:Ve.boolean().or(Ve.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Ve.boolean().or(Ve.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var tK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:qP}),rK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),KP=Ve.object({labels:Ve.array(Ve.string()).optional(),outputs:Kf.nullish()}),mr=Ot.merge(KP),YP=Ve.object({createdAt:Ve.coerce.date(),updatedAt:Ve.coerce.date(),updatedBy:Ve.string().nullable(),schedule:Oi,notification:Li,createdBy:Ve.string(),organizationId:Ve.string(),folderId:Ve.string().nullable().optional()}),XP=Ot.merge(YP),nK=XP.merge(xi),Hl=Ot.merge(xi),oK=Ot.merge(Oo);var LS="test",NS="module",JP="mobile-test",yt=(t=>(t.TEST=`${LS}.yaml`,t.MODULE=`${NS}.yaml`,t))(yt||{}),he=(n=>(n.TEST=`momentic/${LS}`,n.MODULE=`momentic/${NS}`,n.MOBILE_TEST=`momentic/${JP}`,n))(he||{}),dK=Ot.merge(Oo),Ip=Wt.extend({steps:_r.array(_r.record(_r.string(),_r.unknown())),schemaVersion:_r.string()}),pK=Ip.extend({fileType:_r.literal(he.MODULE)}),mK=_r.object({test:_r.string().describe("YAML for the test, including metadata and steps"),modules:_r.record(_r.string(),_r.string()).describe("Map of module name to YAML for the module")});var Ya=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Ya||{});var QP=lt.object({disableDefaultWebviewAccessibilityTree:lt.boolean().optional(),autoGrantPermissions:lt.boolean().optional()}),Pp=QP.extend({region:lt.nativeEnum(Ya).optional()}),Xa=lt.object({retries:lt.number().optional().describe("number of retries to run"),defaultChannel:lt.string().optional().describe("default channel to use"),defaultTag:lt.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:lt.string().optional(),emulator:Pp.optional()}),Mp=lt.object({id:lt.string().uuid(),description:lt.string(),schemaVersion:lt.string(),settings:Xa.optional()}),ZP=Mp.merge(lt.object({steps:lt.array(fn)})),DS=lt.object({fileType:lt.literal(he.MOBILE_TEST)}).merge(ZP),TK=lt.object({name:lt.string(),steps:lt.array(fn).optional(),settings:Xa.optional()});var UK=new Set(Object.values(We));var eM={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",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"},BK={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],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:[]},zK={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.",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."},HK={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},GK={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import tM from"semver";import{z as rM}from"zod";var WK=rM.string().refine(r=>tM.valid(r),{message:"must be a valid semver string"});import{Faker as YK,en as XK}from"@faker-js/faker";import{z as D}from"zod";var Bi=55555,QK=D.object({body:D.string(),to:D.string(),from:D.string()}),ZK=D.object({from:D.string().optional(),to:D.string(),timeout:D.number().optional(),beforeDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional()}),eY=D.object({to:D.string().email(),from:D.string(),subject:D.string(),body:D.string(),html:D.string().optional()}),tY=D.object({inbox:D.string().transform(r=>r.toLowerCase()),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),timeout:D.number().optional(),trimWhitespace:D.boolean().optional()}),rY=D.object({inbox:D.string(),limit:D.number().optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),trimWhitespace:D.boolean().optional()});var Gl=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Gl||{}),kS=D.object({body:D.string().nullish(),status:D.number().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}),nM=D.object({url:D.string(),options:D.object({method:D.string(),body:D.string().nullish(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),oM=D.object({body:D.string().nullish(),options:D.object({status:D.number(),statusText:D.string().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),FS=D.object({result:D.unknown(),variableUpdates:D.record(D.string(),D.unknown()).optional(),persistentVariableUpdates:D.record(D.string(),D.unknown()).optional(),error:D.string().optional(),success:D.boolean()}),nY=D.object({id:D.string().optional(),orgId:D.string(),momenticLambdaAuthHash:D.string(),code:D.string(),fragment:D.boolean(),state:D.object({env:D.record(D.string(),D.unknown()),request:nM,response:oM,additionalBindings:D.record(D.string(),D.unknown()).optional()}),timeoutMs:D.number().optional(),disallowVariableUpdates:D.boolean().optional(),responseSerialization:D.nativeEnum(Gl).optional()}),$n=15e3;import*as Lt from"zod";import{extendZodWithOpenApi as iM}from"zod-openapi";iM(Lt);var aM=Lt.object({url:Lt.string(),lineNumber:Lt.number(),columnNumber:Lt.number()}).openapi({ref:"CodeLocation"}),Vl=Lt.object({timestamp:Lt.number(),text:Lt.string(),type:Lt.string(),tabIndex:Lt.number(),args:Lt.unknown().array().optional(),url:Lt.string().optional(),location:aM.optional()}).openapi({ref:"ConsoleLog"}),US=Vl.array(),sM=US.array();import*as Lp from"zod";import{extendZodWithOpenApi as xM}from"zod-openapi";import{z as I}from"zod";var lM=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),cM=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),uM=I.object({onContentLoad:I.number().optional(),onLoad:I.number().optional(),comment:I.string().optional()}),zS=I.object({startedDateTime:I.string(),id:I.string(),title:I.string().optional(),pageTimings:uM,comment:I.string().optional()}),dM=I.array(zS),pM=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()}),HS=I.array(pM),mM=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),GS=I.array(mM),gM=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),hM=I.array(gM),fM=I.object({name:I.string(),value:I.string().optional(),fileName:I.string().optional(),contentType:I.string().optional(),comment:I.string().optional()}),SM=I.array(fM),yM=I.object({mimeType:I.string(),params:SM,text:I.string(),comment:I.string().optional()}),EM=I.object({method:I.string(),url:I.string(),httpVersion:I.string().optional(),cookies:HS,headers:GS,queryString:hM,postData:yM.optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),TM=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()}),bM=I.object({status:I.number(),statusText:I.string(),httpVersion:I.string().optional(),cookies:HS,headers:GS,content:TM,redirectURL:I.string().optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional(),_mocked:I.boolean().optional()}),BS=I.object({expires:I.string().optional(),lastAccess:I.string(),eTag:I.string(),hitCount:I.number(),comment:I.string().optional()}),vM=I.object({beforeRequest:BS.optional(),afterRequest:BS.optional(),comment:I.string().optional()}),RM=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()}),VS=I.object({pageref:I.string().optional(),startedDateTime:I.string(),time:I.number().optional(),request:EM,response:bM.optional(),cache:vM.optional(),timings:RM,serverIPAddress:I.string().optional(),connection:I.string().optional(),comment:I.string().optional(),_resourceType:I.string().optional()}),AM=I.array(VS),wM=I.object({version:I.string().default("1.1"),creator:lM.optional(),browser:cM.optional(),pages:dM.optional(),entries:AM,comment:I.string().optional()}),CM=I.object({log:wM}),jS=I.record(I.string(),zS),$S=I.record(I.string(),VS);function Op(r,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(r).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}xM(Lp);var _M=Lp.object({logsPerPage:Vl.array().array(),harPages:jS.optional(),harEntries:$S.optional()}).openapi({ref:"DebugData"});var Ja=class{async getConsoleLogsForRunAttempt(e,t,n){}async getNetworkLogsForRunAttempt(e,t,n){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}async storeConsoleLogsForRunAttempt(e,t,n,o){}async storeNetworkLogsForRunAttempt(e,t,n,o){}async storeScreenshot(e,t,n){}async storeHtmlSnapshot(e,t,n){}};var _e=class extends Error{constructor(e,t={}){super(e,t),this.name="ValidationError"}};var jl=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function WS(r){for(let e of Object.values(pe))if(r.includes(e))return e}var C=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(pe))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;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}}},zi=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},jr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
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]="5c578492-ad0b-5b1b-a1ed-310b5ae0f7d0")}catch(e){}}();
4
+ var E_=Object.defineProperty;var We=(r,e)=>()=>(r&&(e=r(r=0)),e);var T_=(r,e)=>{for(var t in e)E_(r,t,{get:e[t],enumerable:!0})};var Xv,Jv=We(()=>{"use strict";Xv=typeof globalThis=="object"?globalThis:global});var Qv=We(()=>{"use strict";Jv()});var Zv=We(()=>{"use strict";Qv()});var wn,yg=We(()=>{"use strict";wn="1.9.0"});function Q0(r){var e=new Set([r]),t=new Set,n=r.match(eR);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===r};function i(l){return t.add(l),!1}function a(l){return e.add(l),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var s=c.match(eR);if(!s)return i(c);var u={major:+s[1],minor:+s[2],patch:+s[3],prerelease:s[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 eR,tR,rR=We(()=>{"use strict";yg();eR=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;tR=Q0(wn)});function ca(r,e,t,n){var o;n===void 0&&(n=!1);var i=Os[Ms]=(o=Os[Ms])!==null&&o!==void 0?o:{version:wn};if(!n&&i[r]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(a.stack||a.message),!1}if(i.version!==wn){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+wn);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+wn+"."),!0}function Cn(r){var e,t,n=(e=Os[Ms])===null||e===void 0?void 0:e.version;if(!(!n||!tR(n)))return(t=Os[Ms])===null||t===void 0?void 0:t[r]}function ua(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+wn+".");var t=Os[Ms];t&&delete t[r]}var Z0,Ms,Os,Ls=We(()=>{"use strict";Zv();yg();rR();Z0=wn.split(".")[0],Ms=Symbol.for("opentelemetry.js.api."+Z0),Os=Xv});function Ns(r,e,t){var n=Cn("diag");if(n)return t.unshift(e),n[r].apply(n,tF([],eF(t),!1))}var eF,tF,nR,oR=We(()=>{"use strict";Ls();eF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tF=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},nR=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ns("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ns("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ns("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ns("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ns("verbose",this._namespace,e)},r}()});var Ve,lu=We(()=>{"use strict";(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(Ve||(Ve={}))});function iR(r,e){r<Ve.NONE?r=Ve.NONE:r>Ve.ALL&&(r=Ve.ALL),e=e||{};function t(n,o){var i=e[n];return typeof i=="function"&&r>=o?i.bind(e):function(){}}return{error:t("error",Ve.ERROR),warn:t("warn",Ve.WARN),info:t("info",Ve.INFO),debug:t("debug",Ve.DEBUG),verbose:t("verbose",Ve.VERBOSE)}}var aR=We(()=>{"use strict";lu()});var rF,nF,oF,on,Ds=We(()=>{"use strict";oR();aR();lu();Ls();rF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nF=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},oF="diag",on=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var l=Cn("diag");if(l)return l[o].apply(l,nF([],rF(i),!1))}}var t=this,n=function(o,i){var a,l,c;if(i===void 0&&(i={logLevel:Ve.INFO}),o===t){var s=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=s.stack)!==null&&a!==void 0?a:s.message),!1}typeof i=="number"&&(i={logLevel:i});var u=Cn("diag"),d=iR((l=i.logLevel)!==null&&l!==void 0?l:Ve.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 ca("diag",d,t,!0)};t.setLogger=n,t.disable=function(){ua(oF,t)},t.createComponentLogger=function(o){return new nR(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}()});var sR,lR=We(()=>{"use strict";sR=Symbol("BaggageEntryMetadata")});function Eg(r){return typeof r!="string"&&(iF.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:sR,toString:function(){return r}}}var iF,cR=We(()=>{"use strict";Ds();lR();iF=on.instance()});function Tg(r){return Symbol.for(r)}var aF,bg,vg=We(()=>{"use strict";aF=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var i=new r(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=function(n){var o=new r(t._currentContext);return o._currentContext.delete(n),o}}return r}(),bg=new aF});function wg(){return Ag}var ri,sF,cu,lF,cF,uF,dF,Rg,pF,mF,gF,Ag,hF,fF,SF,yF,EF,TF,bF,Cg=We(()=>{"use strict";ri=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),sF=function(){function r(){}return r.prototype.createGauge=function(e,t){return fF},r.prototype.createHistogram=function(e,t){return SF},r.prototype.createCounter=function(e,t){return hF},r.prototype.createUpDownCounter=function(e,t){return yF},r.prototype.createObservableGauge=function(e,t){return TF},r.prototype.createObservableCounter=function(e,t){return EF},r.prototype.createObservableUpDownCounter=function(e,t){return bF},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),cu=function(){function r(){}return r}(),lF=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(cu),cF=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(cu),uF=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(cu),dF=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(cu),Rg=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),pF=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Rg),mF=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Rg),gF=function(r){ri(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Rg),Ag=new sF,hF=new lF,fF=new uF,SF=new dF,yF=new cF,EF=new pF,TF=new mF,bF=new gF});var tr,uR=We(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(tr||(tr={}))});var vF,RF,dR,pR=We(()=>{"use strict";vg();vF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},RF=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},dR=function(){function r(){}return r.prototype.active=function(){return bg},r.prototype.with=function(e,t,n){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return t.call.apply(t,RF([n],vF(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var AF,wF,xg,CF,mR,gR=We(()=>{"use strict";pR();Ls();Ds();AF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},wF=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},xg="context",CF=new dR,mR=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return ca(xg,e,on.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,wF([e,t,n],AF(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Cn(xg)||CF},r.prototype.disable=function(){this._getContextManager().disable(),ua(xg,on.instance())},r}()});var da,hR=We(()=>{"use strict";gR();da=mR.getInstance()});var H,fR=We(()=>{"use strict";Ds();H=on.instance()});var xF,SR,yR=We(()=>{"use strict";Cg();xF=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return Ag},r}(),SR=new xF});var _g,ER,TR=We(()=>{"use strict";yR();Ls();Ds();_g="metrics",ER=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return ca(_g,e,on.instance())},r.prototype.getMeterProvider=function(){return Cn(_g)||SR},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){ua(_g,on.instance())},r}()});var uu,bR=We(()=>{"use strict";TR();uu=ER.getInstance()});var Me=We(()=>{"use strict";cR();vg();lu();Cg();uR();hR();fR();bR()});var Oa=(r,e)=>{},Fd=!1;try{let r=await import("@sentry/node");Oa=r.captureException,r.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),Fd=!0}catch{}import{Command as bG,Option as Jt}from"@commander-js/extra-typings";import{execSync as vG}from"child_process";var La=!!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{existsSync as LO,statSync as NO}from"fs";import{z as uf}from"zod";var kG=uf.object({input:uf.string()});import{z as mt}from"zod";var BG=mt.object({srcs:mt.array(mt.string()),urls:mt.array(mt.string()),desiredSrc:mt.string().optional(),desiredUrl:mt.string().optional()}),df=mt.object({srcRegex:mt.string().optional(),urlRegex:mt.string().optional()}),pf=mt.object({x:mt.number(),y:mt.number(),correlation:mt.number()}),zG=mt.object({searchImageBase64String:mt.string(),pageImageBase64String:mt.string(),id:mt.string().uuid(),timeoutMs:mt.number().max(1e4).min(0).optional()});import{z as N}from"zod";import*as F from"zod";import{extendZodWithOpenApi as b_}from"zod-openapi";b_(F);var Mn=(l=>(l.AI="AI",l.AI_HEALED="AI_HEALED",l.CLICK_TO_FIND="CLICK_TO_FIND",l.XY_PERCENT="XY_PERCENT",l.RECORDING="RECORDING",l.USER_CSS_SELECTOR="USER_CSS_SELECTOR",l.HEURISTIC_HEALED="HEURISTIC_HEALED",l))(Mn||{}),v_=F.object({mPathSelectorTokens:F.string().array(),frameSrcRegex:F.string().optional(),frameUrlRegex:F.string().optional(),indices:F.number().array()}),Ud=F.object({result:F.number(),traceId:F.string()}).array(),pl=F.object({type:F.literal("GCS_TRACES"),traces:Ud}),mf=F.object({text:F.string().optional(),attributes:F.record(F.string(),F.string()).optional(),boundingBox:F.object({x:F.number(),y:F.number(),width:F.number(),height:F.number()}).optional()}),R_=F.object({selectors:F.string().array(),requirements:mf.optional()}),On=F.object({id:F.number().int(),dataMomenticId:F.number().int().optional(),selector:F.string().optional(),hybridSelector:F.object({textContent:F.string().nullish(),attributes:F.record(F.string(),F.string()),tagName:F.string(),expandShadowRoot:F.boolean().optional(),classNames:F.string().array(),nthChild:F.number()}).array().optional(),generatedSelectors:F.string().array().optional(),requirements:mf.optional(),additionalElements:R_.array().optional(),role:F.string().optional(),name:F.string().optional(),numChildren:F.number().optional(),content:F.string().optional(),pathFromRoot:F.string().optional(),serializedHtml:F.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:F.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:F.string().url().optional(),boundingBox:F.object({x:F.number().optional(),y:F.number().optional(),width:F.number(),height:F.number()}).describe("css pixel bounding box").optional(),frameCache:v_.optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(Mn).optional(),targetUpdateTime:F.string().optional(),targetUpdateLoggerTags:F.record(F.string(),F.string()).optional(),cacheResolutionUpdateSource:F.string().optional(),cacheResolutionUpdateTime:F.string().optional(),cacheResolutionUpdateLoggerTags:F.record(F.string(),F.string()).optional(),memory:pl.optional()}).openapi({ref:"ElementTargetCache"});function ml(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}function gf(r){r.serializedHtml=void 0,r.nodeOnlySerializedHtml=void 0,r.screenshotUrl=void 0,r.boundingBox=void 0,r.hybridSelector=void 0,r.generatedSelectors=void 0,r.id=-1}var A_=F.object({type:F.literal("description"),elementDescriptor:F.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),w_=F.object({x:F.number(),y:F.number()}),C_=F.object({type:F.literal("coordinates"),pixels:w_}).openapi({ref:"CoordinatesTarget"});function Ln(r){return r.type==="description"}function Hr(r){return r.type==="coordinates"}var _t=F.discriminatedUnion("type",[A_,C_]).openapi({ref:"ElementTarget"});function Bd(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function It(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.pixels.x}, y: ${r.pixels.y}`}}function gl(r){return pl.safeParse(r).success}import{v4 as Ee}from"uuid";import*as v from"zod";import{extendZodWithOpenApi as N_}from"zod-openapi";import{z as oe}from"zod";import{extendZodWithOpenApi as x_}from"zod-openapi";import{z as Ei}from"zod";var zd=Ei.object({result:Ei.boolean(),traceId:Ei.string()}).array(),Hd=Ei.object({type:Ei.literal("GCS_TRACES"),traces:zd}),Gd=Ei.object({memory:Hd.optional()});x_(oe);var hf=oe.object({plan:oe.string().optional(),evidence:oe.string().optional(),thoughts:oe.string(),result:oe.boolean(),relevantElements:oe.array(oe.number()).optional(),updatedMemory:zd.optional()}),Nn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Nn||{});var __=oe.object({type:oe.literal("ELEMENT_NAME"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Nn),value:oe.string()}).openapi({ref:"ElementNameAssertion"}),I_=oe.object({type:oe.literal("ELEMENT_STYLE"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Nn),property:oe.string(),value:oe.string()}).openapi({ref:"ElementStyleAssertion"}),P_=oe.object({type:oe.literal("ELEMENT_CONTENT"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Nn),value:oe.string()}).openapi({ref:"ElementContentAssertion"}),M_=oe.object({type:oe.literal("ELEMENT_ATTRIBUTE"),negated:oe.boolean().optional(),operation:oe.nativeEnum(Nn),attr:oe.string(),value:oe.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Ti=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Ti||{}),O_=oe.object({type:oe.literal("ELEMENT_EXISTENCE"),negated:oe.boolean().optional(),condition:oe.nativeEnum(Ti).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),ff=oe.discriminatedUnion("type",[P_,M_,O_,__,I_]).openapi({ref:"ManualElementAssertion"});var L_=oe.object({type:oe.literal("CONTENT"),negated:oe.boolean().optional(),value:oe.string()}).openapi({ref:"PageContentAssertion"}),Sf=oe.discriminatedUnion("type",[L_]).openapi({ref:"ManualPageAssertion"});import Bt from"zod";var Vd=Bt.discriminatedUnion("type",[Bt.object({type:Bt.literal("SUBSTRING"),url:Bt.string()}),Bt.object({type:Bt.literal("GLOB"),glob:Bt.string()}),Bt.object({type:Bt.literal("REGEX"),regex:Bt.string()}),Bt.object({type:Bt.literal("DOMAIN"),domain:Bt.string()})]),Na=Bt.object({urlMatcher:Vd,method:Bt.string().optional()});import{z as ye}from"zod";var hl=ye.object({url:ye.string(),method:ye.union([ye.literal("GET"),ye.literal("POST"),ye.literal("PUT"),ye.literal("DELETE"),ye.literal("PATCH")]),headers:ye.record(ye.string(),ye.string()).optional(),params:ye.record(ye.string(),ye.string()).optional(),body:ye.string().optional(),timeout:ye.number().int().optional().describe("Max seconds to wait for the request to complete")}),yf=ye.object({url:ye.string(),headers:ye.record(ye.string(),ye.string()).optional(),query:ye.string(),variables:ye.string().optional(),timeout:ye.number().int().optional().describe("Max seconds to wait for the request to complete")}),fl=ye.object({code:ye.string(),fragment:ye.boolean().optional(),environment:ye.union([ye.literal("NODE"),ye.literal("BROWSER")]).optional().describe("default NODE"),timeout:ye.number().int().max(60).optional().describe("Max seconds for the code to complete")});var qe=(G=>(G.AI_EXTRACT="AI_EXTRACT",G.AI_ASSERTION="AI_ASSERTION",G.AUTH_LOAD="AUTH_LOAD",G.AUTH_SAVE="AUTH_SAVE",G.BLUR="BLUR",G.CAPTCHA="CAPTCHA",G.CLICK="CLICK",G.COOKIE="COOKIE",G.COPY="COPY",G.DIALOG="DIALOG",G.DRAG="DRAG",G.ELEMENT_CHECK="ELEMENT_CHECK",G.FILE_UPLOAD="FILE_UPLOAD",G.FOCUS="FOCUS",G.GO_BACK="GO_BACK",G.GO_FORWARD="GO_FORWARD",G.HOVER="HOVER",G.JAVASCRIPT="JAVASCRIPT",G.LOCAL_STORAGE="LOCAL_STORAGE",G.MOUSE_DRAG="MOUSE_DRAG",G.NAVIGATE="NAVIGATE",G.NEW_TAB="NEW_TAB",G.PAGE_CHECK="PAGE_CHECK",G.PASTE="PASTE",G.PRESS="PRESS",G.KEY_DOWN="KEY_DOWN",G.KEY_UP="KEY_UP",G.REFRESH="REFRESH",G.REQUEST="REQUEST",G.GRAPHQL_REQUEST="GRAPHQL_REQUEST",G.SCROLL_DOWN="SCROLL_DOWN",G.SCROLL_UP="SCROLL_UP",G.SCROLL_LEFT="SCROLL_LEFT",G.SCROLL_RIGHT="SCROLL_RIGHT",G.SELECT_OPTION="SELECT_OPTION",G.SWITCH_TAB="TAB",G.TYPE="TYPE",G.VISUAL_DIFF="VISUAL_DIFF",G.WAIT="WAIT",G.WAIT_FOR_URL="WAIT_FOR_URL",G.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",G.AWAIT_LISTENER="AWAIT_LISTENER",G.RECORD_REQUESTS="RECORD_REQUESTS",G.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",G.SET_HEADER="SET_HEADER",G.MOCK_ROUTE="MOCK_ROUTE",G.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",G.OFFLINE_MODE="OFFLINE_MODE",G.SUCCESS="SUCCESS",G))(qe||{});N_(v);var q=v.object({thoughts:v.string().optional(),id:v.string().uuid().describe("unique identifier to this step, used for step cache")}),ir=v.object({useSelector:v.boolean().optional(),force:v.boolean().optional(),disableCache:v.boolean().optional().describe("disable element caching for this step"),iframeUrl:v.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Qt=v.object({target:On}).optional().openapi({ref:"SingleTargetCache"});function Ef(r){return Qt.safeParse(r).success}var yl=v.object({loadTimeout:v.number().int().max(60).optional().describe("Max seconds for the page to load")}),$d=q.merge(yl).merge(v.object({type:v.literal("NAVIGATE"),url:v.string()})).openapi({ref:"NavigateCommand"}),El=ir.merge(v.object({cache:Qt})),Dn=q.merge(El.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_UP"),deltaY:v.number().optional()}))).openapi({ref:"ScrollUpCommand"}),kn=q.merge(El.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_DOWN"),deltaY:v.number().optional()}))).openapi({ref:"ScrollDownCommand"}),bi=q.merge(El.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_LEFT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),vi=q.merge(El.merge(v.object({target:_t.optional(),type:v.literal("SCROLL_RIGHT"),deltaX:v.number().optional()}))).openapi({ref:"ScrollRightCommand"}),dV=v.discriminatedUnion("type",[Dn,kn,bi,vi]).openapi({ref:"AllScrollCommands"}),D_=q.merge(v.object({type:v.literal("DIALOG"),action:v.union([v.literal("ACCEPT"),v.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),k_=q.merge(v.object({type:v.literal("WAIT"),delay:v.number()})).openapi({ref:"WaitCommand"}),F_=v.object({caseInsensitive:v.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:v.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:v.number().int().optional().describe("Max seconds to wait for the URL to match")}),Wd=q.extend({type:v.literal("WAIT_FOR_URL"),matcher:Vd}).merge(F_).openapi({ref:"WaitUrlCommand"}),U_=q.merge(yl).merge(v.object({type:v.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),B_=q.merge(v.object({type:v.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),z_=q.merge(v.object({type:v.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),H_=q.extend({type:v.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),G_=q.extend({type:v.literal("AUTH_LOAD"),storageState:v.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),qd=q.merge(ir).extend({type:v.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),V_=q.extend({type:v.literal("COPY"),value:v.string()}).openapi({ref:"CopyCommand"}),j_=q.extend({type:v.literal("PASTE")}).openapi({ref:"PasteCommand"}),Kd=q.merge(fl).extend({type:v.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Ro=q.merge(ir).extend({type:v.literal("CLICK"),target:_t,doubleClick:v.boolean().optional(),rightClick:v.boolean().optional(),waitForDownload:v.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:v.number().optional(),downloadTimeoutMs:v.number().optional(),cache:Qt,relativePosition:v.object({x:v.number(),y:v.number()}).optional()}).openapi({ref:"ClickCommand"}),Yd=v.object({fromTarget:On.optional(),toTarget:On.optional()}),Da=q.merge(ir).merge(v.object({type:v.literal("DRAG"),fromTarget:_t,toTarget:_t,steps:v.number().optional(),hoverSeconds:v.number().optional().describe("Seconds to hover the object before dropping"),cache:Yd.optional()})).openapi({ref:"DragCommand"}),ka=q.merge(ir).merge(v.object({type:v.literal("MOUSE_DRAG"),target:_t.optional(),deltaX:v.string().describe("pixels to move horizontally, can be template"),deltaY:v.string().describe("pixels to move vertically, can be template"),steps:v.number().optional(),cache:Qt})).openapi({ref:"MouseDragCommand"}),Ao=q.merge(ir).merge(v.object({type:v.literal("HOVER"),target:_t,cache:Qt})).openapi({ref:"HoverCommand"}),Fa=q.merge(ir).merge(v.object({type:v.literal("FOCUS"),target:_t,cache:Qt})).openapi({ref:"FocusCommand"}),Ua=q.merge(ir).extend({type:v.literal("BLUR"),target:_t.optional(),cache:Qt}).openapi({ref:"BlurCommand"}),$_=v.object({type:v.literal("URL"),url:v.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),W_=v.object({type:v.literal("USER_FILE"),name:v.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),q_=q.extend({type:v.literal("FILE_UPLOAD"),fileSource:v.discriminatedUnion("type",[$_,W_]),filename:v.string().optional()}).openapi({ref:"FileUploadCommand"}),K_=v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.coerce.string()})]),wo=q.merge(ir).extend({type:v.literal("SELECT_OPTION"),target:_t,cache:Qt,choice:K_.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Xd=v.union([v.literal("MULTIMODAL"),v.literal("VISION_ONLY")]),Ri=q.merge(v.object({type:v.literal("AI_ASSERTION"),assertion:v.string(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional(),contextChoice:Xd.optional(),timeout:v.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Gd.optional()})).openapi({ref:"AIAssertionCommand"}),Gr=5,Jd=600,Co=q.merge(ir).extend({type:v.literal("ELEMENT_CHECK"),target:_t,assertion:ff,cache:Qt.or(Gd).optional(),timeout:v.number().int().min(0).max(Jd).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Qd=q.extend({type:v.literal("PAGE_CHECK"),assertion:Sf,iframeUrl:v.string().optional().describe("url or url regex for the iframe"),timeout:v.number().int().min(0).max(Jd).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Y_=q.merge(v.object({type:v.literal("AI_EXTRACT"),goal:v.string(),schema:v.string().optional(),envKey:v.string().optional(),disableCache:v.boolean().optional(),iframeUrl:v.string().optional()})).openapi({ref:"AIExtractCommand"}),X_=v.object({clearContent:v.boolean().optional(),forceClearContent:v.boolean().optional(),delay:v.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:v.boolean().optional(),pressEnter:v.boolean().optional()}),Tf=25,xo=q.merge(ir).merge(X_).extend({type:v.literal("TYPE"),target:_t.optional(),value:v.string(),cache:Qt}).openapi({ref:"TypeCommand"}),Zd=q.merge(v.object({type:v.literal("PRESS"),value:v.string(),repeat:v.number().optional(),convertMeta:v.boolean().optional(),delayMs:v.number().optional()})).openapi({ref:"PressCommand"}),J_=q.merge(v.object({type:v.literal("KEY_DOWN"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyDownCommand"}),Q_=q.merge(v.object({type:v.literal("KEY_UP"),value:v.string(),convertMeta:v.boolean().optional()})).openapi({ref:"KeyUpCommand"}),Z_=v.object({type:v.literal("SUBSTRING"),substring:v.string()}),eI=v.object({type:v.literal("REGEX"),pattern:v.string()}),tI=v.object({type:v.literal("INDEX"),index:v.coerce.string()}),rI=v.discriminatedUnion("type",[Z_,eI,tI]),nI=q.merge(yl).merge(v.object({type:v.literal("TAB"),action:rI})).openapi({ref:"TabCommand"}),ep=q.merge(yl).merge(v.object({type:v.literal("NEW_TAB"),url:v.string()})).openapi({ref:"NewTabCommand"}),oI=q.merge(v.object({type:v.literal("COOKIE"),value:v.string()})).openapi({ref:"CookieCommand"}),iI=q.merge(v.object({type:v.literal("LOCAL_STORAGE"),key:v.string(),value:v.string()})).openapi({ref:"LocalStorageCommand"}),aI=q.extend({type:v.literal("REQUEST")}).merge(hl).openapi({ref:"RequestCommand"}),sI=q.extend({type:v.literal("GRAPHQL_REQUEST")}).merge(yf).openapi({ref:"GraphQLRequestCommand"}),lI=q.merge(v.object({type:v.literal("SUCCESS"),condition:Ri.optional()})).openapi({ref:"SuccessCommand"}),cI=q.merge(v.object({type:v.literal("FAILURE")})).openapi({ref:"FailureCommand"}),uI=v.object({data:v.string().describe("location at which to find a jpg"),width:v.number(),height:v.number()}),Ba=q.merge(ir).merge(v.object({type:v.literal("VISUAL_DIFF"),threshold:v.number().optional().describe("default 0.1"),target:_t.optional(),screenshot:uI.optional(),cache:Qt})).openapi({ref:"VisualDiffCommand"}),dI=q.merge(v.object({type:v.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Na,key:v.string()})).openapi({ref:"RegisterRequestListenerCommand"}),pI=q.merge(v.object({type:v.literal("AWAIT_LISTENER"),key:v.string(),timeout:v.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),mI=q.merge(v.object({type:v.literal("RECORD_REQUESTS"),requestMatcher:Na,key:v.string()})).openapi({ref:"RecordRequestsCommand"}),gI=q.merge(v.object({type:v.literal("GET_RECORDED_REQUESTS"),key:v.string()})).openapi({ref:"GetRecordedRequestsCommand"}),hI=q.merge(v.object({type:v.literal("SET_HEADER"),name:v.string(),value:v.string(),requestMatcher:Na.optional()})).openapi({ref:"SetHeaderCommand"}),fI=q.merge(v.object({type:v.literal("MOCK_ROUTE"),requestMatcher:Na,responseGenerator:v.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:v.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:v.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"})),SI=q.merge(v.object({type:v.literal("REMOVE_ROUTE_MOCK"),key:v.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),yI=q.merge(v.object({type:v.literal("OFFLINE_MODE"),enable:v.boolean()})).openapi({ref:"OfflineModeCommand"}),bf=v.discriminatedUnion("type",[Ro,xo,Zd,J_,Q_,wo,$d,kn,Dn,Ri,Ao,k_,lI]),EI=v.discriminatedUnion("type",[Y_,G_,H_,qd,oI,V_,D_,Da,Co,q_,B_,z_,Kd,iI,ka,ep,Qd,j_,U_,aI,sI,bi,vi,nI,Ba,Fa,Ua,Wd,dI,pI,mI,gI,hI,fI,SI,yI]),Ai=v.discriminatedUnion("type",[...bf.options,...EI.options]).openapi({ref:"Command"}),Tl=v.discriminatedUnion("type",[...bf.options,cI]);function pn(r){let e;switch(r){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:Ee(),type:r};break;case"AUTH_LOAD":{e={id:Ee(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:Ee(),type:r,goal:""};break;case"DIALOG":e={id:Ee(),type:r,action:"DISMISS"};break;case"DRAG":e={id:Ee(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Ee(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Ee(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:Ee(),type:r,delay:1};break;case"BLUR":e={id:Ee(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Ee(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Ee(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:Ee(),type:r,value:""};break;case"SELECT_OPTION":e={id:Ee(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:Ee(),type:r,url:""};case"TAB":e={id:Ee(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:Ee(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Ee(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Ee(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:Ee(),type:r,code:""};break;case"AI_ASSERTION":e={id:Ee(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:Ee(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Ee(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Ee(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Ee(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:Ee(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:Ee(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:Ee(),type:r,key:""};break}case"SET_HEADER":{e={id:Ee(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:Ee(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:Ee(),type:r};break}case"OFFLINE_MODE":{e={id:Ee(),type:r,enable:!0};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}function vf(r){switch(r.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(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{z as TI}from"zod";var fV=TI.discriminatedUnion("type",[Ua,qd,Ro,Da,Fa,Ao,ka,Dn,kn,bi,vi,wo,xo,Ba,Co]);function Rf(r){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(r)}import{z as bI}from"zod";import{z as Fn}from"zod";function za(r){return Fn.object({key:Fn.string(),testId:Fn.string().optional(),moduleId:Fn.string().optional(),organizationId:Fn.string(),value:r})}function Ha(r){return za(r).extend({uniqueKey:Fn.string()})}function bl(r){return Fn.record(Fn.string(),Ha(r))}var zt={type:!0,cache:!0},mn=bI.discriminatedUnion("type",[Ri.pick(zt),Ua.pick(zt),Ro.pick(zt),Da.pick(zt),Co.pick(zt),Fa.pick(zt),Ao.pick(zt),ka.pick(zt),Dn.pick(zt),kn.pick(zt),bi.pick(zt),vi.pick(zt),wo.pick(zt),xo.pick(zt),Ba.pick(zt)]),vl=Object.values(qe).filter(r=>mn.options.some(e=>e.shape.type.safeParse(r).success));Ai.options.forEach(r=>{if("target"in r.shape&&!vl.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Af(r){return vl.includes(r.type)}var wf=za(mn),Cf=Ha(mn),AV=bl(mn);import{z as tp}from"zod";import{extendZodWithOpenApi as AI}from"zod-openapi";import{z as xf}from"zod";import{extendZodWithOpenApi as vI}from"zod-openapi";import{z as _o}from"zod";var ar=_o.object({index:_o.number().optional().describe("global index within a test (in-order traversal)"),id:_o.string(),skipped:_o.boolean().optional(),envKey:_o.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:_o.boolean().optional(),retries:_o.number().optional()});vI(xf);var RI=ar.extend({type:xf.literal("PRESET_ACTION")}),Zt=RI.extend({command:Ai}).openapi({ref:"PresetAction"});AI(tp);var Io=ar.extend({type:tp.literal("AI_ACTION"),text:tp.string(),steps:Zt.array().optional()}).openapi({ref:"AIAction"});import{z as Ht}from"zod";import{z as Rl}from"zod";import{extendZodWithOpenApi as wI}from"zod-openapi";wI(Rl);var wi=ar.extend({type:Rl.literal("AI_ACTION_DYNAMIC"),text:Rl.string(),retries:Rl.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as _f}from"zod";var rp=ar.extend({type:_f.literal("CONDITIONAL"),skipped:_f.boolean().optional()});import{z as pe}from"zod";var CI=pe.object({cacheKey:pe.string(),cacheExpiryMs:pe.number()}),np=ar.extend({id:pe.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:pe.record(pe.string()).optional(),cacheConfig:CI.optional()}),_r=np.extend({type:pe.literal("MODULE"),moduleId:pe.string().uuid()}),xI=pe.union([_r.pick({type:!0,moduleId:!0}),pe.record(pe.unknown())]),_I=pe.object({type:pe.literal("URL_REGEX"),regex:pe.string()}),II=pe.object({type:pe.literal("PAGE_CHECK"),substring:pe.string()}),op=pe.object({cacheInvalidation:pe.discriminatedUnion("type",[II,_I]).optional()}),Wt=pe.object({moduleId:pe.string().uuid(),name:pe.string(),description:pe.string().nullish(),enabled:pe.boolean().nullish(),parameters:pe.string().array().nullish(),defaultParameters:pe.record(pe.string(),pe.string()).nullish(),parameterEnums:pe.record(pe.string(),pe.string().array()).nullish(),defaultCacheKey:pe.string().nullish(),defaultCacheTtl:pe.number().nullish(),defaultCacheAllInvocations:pe.boolean().nullish(),autoAuth:pe.boolean().nullish(),advanced:op.nullish()});var ip=r=>r.type==="AI_ACTION"||r.type==="AI_ACTION_DYNAMIC"||r.type==="PRESET_ACTION";import{z as sr}from"zod";var ap=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(ap||{});var PI=sr.discriminatedUnion("type",[sr.object({type:sr.literal("NAVIGATE_URL"),url:sr.string().url()}),sr.object({type:sr.literal("GO_TO_SECTION_START")})]),MI=sr.object({trigger:sr.nativeEnum(ap).optional(),attempts:sr.number().int().optional(),restartBehavior:PI}),Ga=ar.extend({type:sr.literal("SECTION"),description:sr.string().describe("user provided goal of what the section should accomplish"),plan:sr.string().array().optional(),autohealingConfig:MI.optional()});var If=Wt.merge(np).extend({type:Ht.literal("RESOLVED_MODULE"),steps:Ht.lazy(()=>et.array())}),Va=Wt.extend({steps:Ht.lazy(()=>et.array())}),sp=Ga.extend({steps:Ht.lazy(()=>Le.array())}),OI=Ga.extend({steps:Ht.lazy(()=>et.array())}),Po=rp.extend({blocks:Ht.object({assertion:Ht.lazy(()=>Zt),steps:Ht.lazy(()=>Le.array())}).array(),elseSteps:Ht.lazy(()=>Le.array().optional())}),LI=rp.extend({blocks:Ht.object({assertion:Ht.lazy(()=>Zt),steps:Ht.lazy(()=>et.array())}).array(),elseSteps:Ht.lazy(()=>et.array().optional())}),Le=Ht.discriminatedUnion("type",[Zt,Io,wi,_r,Po,sp]),et=Ht.discriminatedUnion("type",[Zt,Io,wi,If,LI,OI]);import{z as lr}from"zod";var NI=lr.object({steps:Le.array(),beforeSteps:Le.array().nullish(),afterSteps:Le.array().nullish()}),Ci=lr.object({steps:et.array(),beforeSteps:et.array().nullish(),afterSteps:et.array().nullish()}),Mo=lr.object({steps:lr.record(lr.string(),lr.unknown()).array(),beforeSteps:lr.record(lr.string(),lr.unknown()).array().nullish(),afterSteps:lr.record(lr.string(),lr.unknown()).array().nullish()});var ie="1.0.21";var Pf=N.object({phrase:N.string()}),lp=N.object({thoughts:N.string().optional(),result:N.union([N.literal("NOT_FOUND"),N.string(),N.number(),N.array(N.unknown()),N.record(N.unknown(),N.unknown()),N.unknown()])}),l$=N.object({text:N.string()}),Mf=N.object({attributes:N.array(N.string()).optional(),text:N.boolean().optional(),boundingBox:N.boolean().optional()}),DI=N.object({id:N.number().int(),requirements:Mf}),kI=DI.array(),Of=N.object({thoughts:N.string(),review:N.string().optional(),id:N.number().int(),updatedMemory:Ud.optional(),requirements:Mf.optional(),additionalElements:kI.optional()});var Al=(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))(Al||{});var Lf=N.object({thoughts:N.string(),category:N.nativeEnum(Al)}),FI=N.discriminatedUnion("op",[N.object({op:N.literal("replace"),path:N.string(),value:N.string()}),N.object({op:N.literal("add"),path:N.string(),value:N.string()}),N.object({op:N.literal("remove"),path:N.string()})]),c$=N.object({thoughts:N.string(),patches:FI.array()}),UI=[N.literal("add"),N.literal("replace"),N.literal("remove")],BI=N.object({op:N.union(UI),path:N.string(),value:et.optional()}),Nf=N.object({patches:BI.array(),thoughts:N.string()}),cp=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(cp||{}),Df=N.object({thoughts:N.string(),scenario:N.nativeEnum(cp),instructions:N.string().nullish()}),kf=N.object({reasoning:N.string(),scenario:N.string(),patch:N.null().optional()}),u$=N.object({thoughts:N.string(),evaluation:N.number().min(0).max(10)}),d$=N.object({observations:N.string(),reasoning:N.string(),command:Tl});var up=N.object({summary:N.string(),reasoning:N.string(),evaluation:N.discriminatedUnion("type",[N.object({type:N.literal("DONE")}),N.object({type:N.literal("RIGHT_TRACK")}),N.object({type:N.literal("WRONG_TRACK"),feedback:N.string()}),N.object({type:N.literal("IMPOSSIBLE")})])}),zI=N.object({startId:N.number().int(),endId:N.number().int()}),Ff=N.object({categoryThoughts:N.string(),category:N.string(),relevantSections:zI.array()});import{z as O}from"zod";import*as ae from"zod";var S$=ae.object({thoughts:ae.string().optional().describe("only provided if a description was provided"),target:On.optional().describe("only provided if a description was provided"),pageState:ae.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ae.object({label:ae.string(),value:ae.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ae.object({data:ae.string(),height:ae.number().int(),width:ae.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Uf=ae.union([ae.literal("ELEMENT_CHECK"),ae.literal("NEGATED_CHECK"),ae.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ae.literal("SELECT_OPTION"),ae.literal("TYPE")]);function Oo(r){if(!("useSelector"in r&&r.useSelector)){if(r.type==="SELECT_OPTION")return"SELECT_OPTION";if(r.type==="TYPE")return"TYPE";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="EXISTS"&&r.assertion.negated)return"NEGATED_CHECK";if(r.type==="ELEMENT_CHECK"&&r.assertion.type==="ELEMENT_EXISTENCE"&&r.assertion.condition==="VISIBLE"&&r.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(r.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var ja=(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))(ja||{}),xi=ae.object({matched:ae.boolean(),reason:ae.string().optional().describe("Human understandable description"),logs:ae.string().array().optional().describe("Logs for debugging")}),HI=xi.extend({type:ae.literal("USER_SELECTOR")}),GI=xi.extend({type:ae.literal("CSS_SELECTOR"),selectors:ae.string().array()}),VI=xi.extend({type:ae.literal("HYBRID_SELECTOR")}),jI=xi.extend({type:ae.literal("HTML_DISTANCE"),distance:ae.number().optional(),closestElement:ae.string().optional(),savedElement:ae.string().optional()}),$I=xi.extend({type:ae.literal("TEMPLATE_MATCHING"),elementImageUrl:ae.string().url()}),WI=xi.extend({type:ae.literal("AUTO_FRAME"),logs:ae.string().array().optional()}),Bf=ae.discriminatedUnion("type",[HI,GI,VI,jI,$I,WI]);import{z as Ka}from"zod";import{z as iP}from"zod";import*as V from"zod";import{extendZodWithOpenApi as JI}from"zod-openapi";import{cloneDeep as $a}from"lodash-es";import $f from"truncate-json";import*as Do from"zod";import{extendZodWithOpenApi as qI}from"zod-openapi";import{z as Pt}from"zod";import{z as Ne}from"zod";var dp=Ne.object({autoFollowNewTabs:Ne.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Ne.union([Ne.boolean(),Ne.literal("inputs-only")]).optional(),ignoreHrefForCaching:Ne.boolean().optional(),disableSecondaryCacheResolution:Ne.boolean().optional(),hybridSelectorMode:Ne.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Ne.boolean().optional(),visualActions:Ne.boolean().optional(),autoExpandIframes:Ne.boolean().optional(),disableHtmlSnapshots:Ne.boolean().optional(),importantAttributes:Ne.string().array().optional(),importantClasses:Ne.string().array().optional(),importantStyles:Ne.string().array().optional()});var zf=1e4,Hf=6e4,Lo=dp.extend({pageLoadTimeoutMs:Ne.number().optional().refine(r=>r===void 0||r<=Hf&&r>=-1,{message:`Page load timeout must be between 0 and ${Hf/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Ne.number().optional().refine(r=>r===void 0||r<=zf&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${zf/1e3} seconds`}),localChromeExtensionPaths:Ne.string().array().optional(),extraHeaders:Ne.record(Ne.string(),Ne.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Ne.string().optional(),disableGpu:Ne.boolean().optional(),bustCacheOnBoundingBoxChange:Ne.boolean().optional().describe("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:Ne.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Ne.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.")});var ht="BASE_URL",wl="CURRENT_URL",No="ENV_NAME",_i="TEST_NAME",R$={[ht]:"https://www.google.com"},Gf=Pt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Vf=Pt.object({name:Pt.string(),variables:Pt.record(Pt.string().describe("variable name"),Pt.string().describe("variable value"))}),jf=Pt.object({name:Pt.string(),variables:Pt.record(Pt.string().describe("variable name"),Pt.unknown().describe("variable value")),browser:Lo.optional()});var A$=Pt.object({name:Pt.string(),variables:Pt.record(Pt.string().describe("variable name"),Pt.unknown().describe("variable value"))});qI(Do);var pp=Do.object({env:Do.record(Do.unknown())}).openapi({ref:"TestContextSnapshot"}),KI="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",YI=[ht,No,_i],Wf=[wl,ht,No,_i],qt=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[ht]??"about:blank",o=e.env[wl]??"about:blank",i=e.env[No],a=e.env[_i],l={};for(let[s,u]of Object.entries(e.env))Wf.includes(s)||(t??{})[s]===void 0&&(l[s]=u);return new r({baseUrl:n,currentUrl:o,dynamicVariables:l,envName:i,testName:a,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=$a(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){YI.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[No]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return $a(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Wf.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,KI]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=$f(JSON.stringify(o),5e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=$f(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[wl]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=$a(e.variablesFromEnvironment),this.setMomenticSystemVariable(ht,e.baseUrl),e.envName&&this.setMomenticSystemVariable(No,e.envName),e.testName&&this.setMomenticSystemVariable(_i,e.testName)}getDynamicVariablesCopy(){return $a(this.env)}getVariablesFromEnvironmentCopy(){return $a(this.varsFromMomenticEnvironment)}};var Ae=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ae||{}),Cl=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Cl||{});import{z as Vr}from"zod";import{extendZodWithOpenApi as XI}from"zod-openapi";XI(Vr);var me=(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))(me||{});var qf=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],xl={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"},Ii={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."},mp=Vr.object({reason:Vr.nativeEnum(me),previousStepsDescription:Vr.array(Vr.string()).optional(),summary:Vr.string(),rootCause:Vr.string().optional()}).openapi({ref:"TestResultClassification"}),_l=Vr.object({errorMessage:Vr.string(),errorStack:Vr.string().optional(),classification:mp.optional()}).openapi({ref:"TestFailureDetails"});JI(V);var gp=V.object({beforeUrl:V.string().optional(),afterUrl:V.string().optional(),message:V.string().optional(),beforeSnapshot:V.string().optional(),afterSnapshot:V.string().optional(),startedAt:V.coerce.date(),finishedAt:V.coerce.date()}),QI=gp.extend({viewport:V.object({height:V.number(),width:V.number()}).nullish(),status:V.nativeEnum(Cl),message:V.string().optional(),elementInteracted:V.string().optional()}),ko=gp.extend({status:V.nativeEnum(Ae),message:V.string().optional(),data:V.unknown().optional(),beforeTestContext:pp.optional(),afterTestContext:pp.optional(),failureReason:V.nativeEnum(me).optional(),details:V.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"}),hp=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(hp||{}),Il=ko.merge(Zt).extend({results:QI.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:V.lazy(()=>gt.array()).optional(),failureRecoveryStatus:V.object({type:V.nativeEnum(hp),message:V.string()}).optional()}),ZI=ko.merge(Io).extend({results:V.lazy(()=>Il.array()),previousAttempts:V.lazy(()=>gt.array()).optional()}),eP=ko.merge(wi).extend({results:V.lazy(()=>Il.array()),previousAttempts:V.lazy(()=>gt.array()).optional()}),tP=ko.merge(_r).extend({moduleName:V.string().optional(),results:V.lazy(()=>gt.array()),previousAttempts:V.lazy(()=>gt.array()).optional()}),rP=ko.merge(Po).extend({assertion:Il.optional(),results:V.lazy(()=>gt.array()).describe("results for the block actually executed"),previousAttempts:V.lazy(()=>gt.array()).optional()}),nP=ko.merge(Ga).extend({results:V.lazy(()=>gt.array()),healingAttempts:V.lazy(()=>gt.array().array()).optional(),previousAttempts:V.lazy(()=>gt.array()).optional()}),gt=V.discriminatedUnion("type",[ZI,eP,Il,tP,rP,nP]),Pl=ko.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),oP=gp.extend({index:V.number().optional(),description:V.string(),pageState:V.string().optional(),elementInteracted:V.string().optional(),startedAt:V.coerce.date().or(V.string()).optional().catch(void 0),finishedAt:V.coerce.date().or(V.string()).optional().catch(void 0)}),Ml=oP.extend({beforeScreenshot:V.string().optional(),afterScreenshot:V.string().optional()});var fp=iP.object({results:gt.array().describe("main results"),beforeResults:gt.array().optional(),afterResults:gt.array().optional()}),Wa=fp.partial();import{z as U}from"zod";import{extendZodWithOpenApi as dP}from"zod-openapi";var Pi=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Pi||{});import{isValidCron as aP}from"cron-validator";import{z as le}from"zod";import{z as Sp}from"zod";var gn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(gn||{});var Ol=Sp.object({width:Sp.number().min(200).max(1e4),height:Sp.number().min(200).max(1e4)}),Kf={"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}},Q$=Object.keys(Kf);var Mt=Kf["Desktop Large"],Un="en-us",Bn="America/Los_Angeles";var zn={latitude:37.7749,longitude:-122.4194};var Yf=["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 Xf=2e3,Ll=Lo.extend({browserType:le.nativeEnum(gn).optional(),slowMoMs:le.number().optional().refine(r=>r===void 0||r<=Xf&&r>=-1,{message:`Slow motion must be between 0 and ${Xf} milliseconds`}),basicAuthorization:le.object({username:le.string().optional(),password:le.string().optional()}).optional(),geolocation:le.object({latitude:le.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:le.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:le.boolean().optional(),locale:le.string().optional(),timezone:le.enum(Yf).optional(),colorScheme:le.enum(["light","dark"]).optional()}),Jf=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],yp=le.object({useMemory:le.boolean().optional(),failureRecovery:le.boolean().optional().describe("undefined means inherit org settings")}),sP=yp.extend({disableAICaching:le.boolean().optional(),failureRecoveryInstructions:le.string().optional()}),lP=le.object({viewport:Ol.optional()}),Fo=lP.merge(sP).merge(Ll),Mi=le.object({cron:le.string().refine(r=>aP(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:le.boolean().default(!1),env:le.string().optional(),timeZone:le.string().default("America/Los_Angeles"),jobKey:le.string().optional()}),Oi=le.object({onSuccess:le.boolean().default(!1),failureMessage:le.string().optional(),onFailure:le.boolean().default(!0),successMessage:le.string().optional()}),cP=le.object({name:le.string(),required:le.boolean().optional(),defaultValue:le.string().describe("this is not optional because we need a value when the editor is first loaded")}),Nl=cP.array(),uP=le.object({name:le.string(),value:le.string()}),Qf=uP.array(),Dl=le.object({name:le.string(),default:le.boolean().optional(),fixtures:Gf.array().optional()});dP(U);var cr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},he=(l=>(l.PENDING="PENDING",l.RUNNING="RUNNING",l.PASSED="PASSED",l.FAILED="FAILED",l.CANCELLED="CANCELLED",l.RETRYING="RETRYING",l.WAITING_FOR_USER="WAITING_FOR_USER",l))(he||{}),kl=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(kl||{});var lt=U.string().pipe(U.coerce.date()).or(U.date()),qa=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(Pi).optional().default("WEB"),createdAt:lt,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:lt.or(U.null()),startedAt:lt.or(U.null()),updatedAt:lt.nullish(),finishedAt:lt.or(U.null()),resolvedBaseUrl:U.string().nullish(),environmentName:U.string().nullish(),gitBranchName:U.string().nullish(),githubRepository:U.string().nullish(),gitlabProjectPath:U.string().nullish(),labels:U.array(U.string()).optional(),gitOriginUrl:U.string().nullish(),gitCommitSha:U.string().nullish(),gitCommitShaShort:U.string().nullish(),gitCommitAuthorName:U.string().nullish(),cliVersion:U.string().nullish(),section:U.nativeEnum(kl).nullish(),status:U.nativeEnum(he),trigger:U.nativeEnum(cr),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(he),startedAt:lt.or(U.null()),finishedAt:lt.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(me).nullish(),failureDetails:_l.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),pP={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Fl=qa.pick({...pP,test:!0}),Zf=qa.omit({failureReason:!0,failureDetails:!0,test:!0}),Ep=qa.extend({stepsSnapshot:U.array(U.record(U.unknown())).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),test:U.object({name:U.string(),id:U.string(),description:U.string().nullish(),baseUrl:U.string().nullish(),advanced:Fo.nullish()}).nullish()}).merge(fp),eS=r=>r.includes("PASSED")&&r.includes("FAILED");var mP=Ka.object({id:Ka.string().uuid(),startedAt:lt.or(Ka.null()),finishedAt:lt.or(Ka.null()),status:Ka.nativeEnum(he)}).merge(Wa),TW=mP.array();var Ul=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(Ul||{});import{z as ct}from"zod";var gP=ct.object({id:ct.string(),status:ct.nativeEnum(he),trigger:ct.nativeEnum(cr),createdAt:lt,startedAt:lt.nullish(),finishedAt:lt.nullish(),gitCommitSha:ct.string().nullish(),gitCommitShaShort:ct.string().nullish(),gitCommitTimestamp:lt.nullish(),gitBranchName:ct.string().nullish(),gitOriginUrl:ct.string().nullish(),gitCommitMessage:ct.string().nullish(),gitCommitAuthorName:ct.string().nullish(),githubRepository:ct.string().nullish(),gitlabProjectPath:ct.string().nullish(),pipelineId:ct.string().nullish(),cliVersion:ct.string().nullish(),labels:ct.string().array().optional(),suite:ct.object({id:ct.string(),name:ct.string()}).nullish(),runs:ct.object({status:ct.nativeEnum(he)}).array()}).openapi({ref:"RunGroup"}),tS=gP.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Fl.array()});import{z as ft}from"zod";var hP=ft.object({type:ft.literal("TARGETING"),name:ft.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Bf.array(),pageState:ft.string().optional(),targetSource:ft.nativeEnum(Mn).optional(),targetUpdateTime:ft.string().optional()}),fP=ft.object({type:ft.literal("AI_LOCATION"),matched:ft.boolean(),pageState:ft.string().optional(),ragUsed:ft.boolean().optional(),thoughts:ft.string().optional()}),SP=ft.object({type:ft.literal("ASSERTION"),relevantElementsSerialized:ft.string().array().optional(),pageState:ft.string().optional(),ragUsed:ft.boolean().optional()}),rS=ft.discriminatedUnion("type",[hP,fP,SP]);function Bl(){return{details:[]}}import{z as ot}from"zod";var yP=ot.object({id:ot.string(),name:ot.string()}),NW=yP.merge(ot.object({createdAt:lt,createdBy:ot.string(),schedule:Mi,notification:Oi,environment:ot.object({name:ot.string()}).nullish(),beforeTests:ot.object({id:ot.string()}).array().nullish(),afterTests:ot.object({id:ot.string()}).array().nullish()})),nS=ot.object({id:ot.string().uuid(),orgId:ot.string(),createdAt:lt,startedAt:lt.or(ot.null()),finishedAt:lt.or(ot.null()),status:ot.nativeEnum(he),trigger:ot.nativeEnum(cr),suite:ot.object({id:ot.string(),name:ot.string()}).nullish(),runs:qa.array()}),DW=nS.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),oS=nS.extend({runs:Fl.array()});import{z as ur}from"zod";import{cloneDeep as UW}from"lodash-es";import{z as Te}from"zod";var jW=Te.object({thoughts:Te.string(),subGoals:Te.object({instruction:Te.string()}).array()}),$W=Te.object({thoughts:Te.string(),newPlanMarkdown:Te.string()}),WW=Te.object({thoughts:Te.string(),correct:Te.boolean(),failedActionIndex:Te.number().optional()}),EP=Te.object({type:Te.literal("PLANNING"),beforePlan:Te.string(),goalDecision:Te.string(),thoughts:Te.string()}),TP=Te.object({type:Te.literal("RUNNING"),stepDisplayName:Te.string(),status:Te.nativeEnum(Ae),results:gt.array()}),bP=Te.object({type:Te.literal("REVISING"),beforePlan:Te.string(),afterPlan:Te.string(),errString:Te.string(),diffs:Te.string(),thoughts:Te.string()}),vP=Te.object({type:Te.literal("SYSTEM"),message:Te.string()}),RP=Te.discriminatedUnion("type",[EP,TP,bP,vP]),iS=RP.array();var JW=ur.object({id:ur.string(),scheduledAt:ur.coerce.date().nullable(),startedAt:ur.coerce.date().nullable(),finishedAt:ur.coerce.date().nullable(),status:ur.nativeEnum(he),history:iS.nullable(),testPlan:ur.object({id:ur.string(),name:ur.string()}).nullable(),test:ur.object({id:ur.string(),name:ur.string()}).nullable()});import{z as Gt}from"zod";var Tp=Gt.object({content:Gt.string(),ids:Gt.string().array(),tokenLength:Gt.number()}),AP=Gt.object({chunks:Tp.array()}),gq=Gt.object({ids:Gt.string().array(),score:Gt.number(),tokenLength:Gt.number()}),hq=AP.extend({description:Gt.string().describe("Input to pass to RAG engine"),tokenLimit:Gt.number()}),aS=Gt.object({ids:Gt.number().array()}),sS=Gt.object({indices:Gt.number().array()});var Vt=O.object({disableCache:O.boolean().optional(),useMemory:O.boolean().optional(),loggerTags:O.record(O.string(),O.string()).optional(),langfuseSessionId:O.string().optional(),agentConfigVersion:O.string().optional()}),Rq=Vt.extend({chunks:Tp.array(),description:O.string().describe("Input to pass to AI"),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),softTokenLimit:O.number(),hardTokenLimit:O.number()}),wP=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),lS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:Uf.optional().catch(void 0),memory:O.discriminatedUnion("type",[pl,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),cS=O.object({target:O.string().or(O.number()),browserState:O.string().optional(),screenshot:O.string().optional(),boundingBox:O.object({x:O.number(),y:O.number(),height:O.number(),width:O.number()}).optional()}),uS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),CP=O.literal("NEGATED_CHECK"),dS=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:Xd.optional(),memory:O.discriminatedUnion("type",[Hd,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional(),source:CP.optional()}),pS=O.object({command:Ai}),bp=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:wP.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),mS=O.object({results:Ml.array(),errorMessage:O.string(),errorStack:O.string().optional()}),gS=O.object({results:Ml.array(),goal:O.string(),errorMessage:O.string()}),hS=O.object({failedResults:Ml.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),Aq=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()}),fS=O.object({type:O.string(),browserContext:O.string(),currentStep:O.string(),screenshot:O.string()});import{z as Ya}from"zod";var xq=Ya.object({goal:Ya.string()}),SS=Ya.object({keywords:Ya.array(Ya.string())});import{z as vp}from"zod";var zl=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(zl||{}),Pq=vp.nativeEnum(zl),xP=vp.enum(["v1","v2"]),Mq=xP.or(vp.string().describe("for people with special configurations"));import{z as Ke}from"zod";var yS=Ke.object({attributesRequired:Ke.array(Ke.string()).optional(),textRequired:Ke.boolean().optional(),boundsRequired:Ke.boolean().optional()}),_P=Ke.object({id:Ke.number(),thoughts:Ke.string(),requirements:yS.optional(),additionalElements:Ke.object({id:Ke.number(),requirements:yS}).array().optional()}),ES=Ke.object({description:Ke.string(),screenXml:Ke.string(),screenshot:Ke.string()}),TS=Ke.object({assertion:Ke.string(),screenXml:Ke.string(),screenshot:Ke.string()}),IP=Ke.object({thoughts:Ke.string(),result:Ke.boolean(),relevantElements:Ke.array(Ke.number()).optional()});var bS=r=>!(!r.org_id||!r.user_id||!r.platform);import{z as Uo}from"zod";var vS=Uo.object({id:Uo.string().uuid(),skipped:Uo.boolean().optional(),envKey:Uo.string().optional().describe("key in the environment to save the result of this step to")}),Rp=vS.merge(hl).extend({type:Uo.literal("REQUEST")}),Ap=vS.merge(fl).extend({type:Uo.literal("JAVASCRIPT")}),wp=Uo.discriminatedUnion("type",[Ap,Rp]);import{z as dr}from"zod";import{z as Bo}from"zod";var PP=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,_e=r=>{let e=r.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 Li=Bo.string().min(1).max(255).superRefine((r,e)=>{try{Hn(r)}catch(t){return e.addIssue({code:Bo.ZodIssueCode.custom,message:t.message,fatal:!0}),Bo.NEVER}});function Hn(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(PP))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Hl=Bo.preprocess(r=>r===null?"":r,Bo.union([Bo.string().url(),Bo.literal("")])).optional();var RS=dr.object({id:dr.string(),name:Li,description:dr.string().optional().nullish(),baseUrl:Hl.nullish(),schemaVersion:dr.string(),advanced:dr.unknown().optional(),retries:dr.number(),envs:dr.array(Dl).nullish(),parameters:Nl.nullish()}),MP=dr.object({createdAt:dr.coerce.date(),updatedAt:dr.coerce.date(),schedule:Mi.nullish(),notification:Oi.nullish(),createdBy:dr.string(),organizationId:dr.string()}),OP=RS.merge(MP),n2=OP.extend({steps:wp.array()}),o2=RS.extend({steps:wp.array()});import{z as Kt}from"zod";var AS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date(),status:Kt.nativeEnum(Ae),message:Kt.string().optional(),data:Kt.unknown().optional()}),LP=AS.merge(Ap).extend({type:Kt.literal("JAVASCRIPT")}),NP=AS.merge(Rp).extend({type:Kt.literal("REQUEST")}),DP=Kt.discriminatedUnion("type",[LP,NP]),wS=Kt.object({startedAt:Kt.coerce.date(),finishedAt:Kt.coerce.date().nullish(),status:Kt.nativeEnum(he),results:DP.array(),failureReason:Kt.string().nullish(),failureDetails:_l.nullish()});import{z as Yt}from"zod";var kP=Yt.object({id:Yt.string(),organizationId:Yt.string(),createdAt:Yt.coerce.date(),updatedAt:Yt.coerce.date(),createdBy:Yt.string(),scheduledAt:Yt.coerce.date().nullish(),startedAt:Yt.coerce.date().nullish(),finishedAt:Yt.coerce.date().nullish(),status:Yt.nativeEnum(he),trigger:Yt.nativeEnum(cr),results:wS.array().nullish(),apiTestName:Yt.string().nullish(),apiTestPath:Yt.string().nullish(),apiTestId:Yt.string().nullish()}),g2=kP.pick({status:!0,startedAt:!0,finishedAt:!0});var Xa=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(Xa||{}),CS=3;function FP(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Cp(r){if(!FP(r))switch(r){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function xp(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return CS;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 r.useSelector||!r.target||r.target.type!=="description"?0:1;case"DRAG":return r.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:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var Ni=class{trackStepExecution(){}async flush(){}};import{parseString as UP,splitCookiesString as BP}from"set-cookie-parser";import{z as we}from"zod";var _p=we.object({name:we.string(),value:we.string(),url:we.string().optional(),domain:we.string().optional(),path:we.string().optional(),expires:we.number().default(Date.now()/1e3+60*60*24*365),httpOnly:we.boolean().optional(),secure:we.boolean().default(!0),sameSite:we.union([we.literal("Strict"),we.literal("Lax"),we.literal("None")]).default("None")});function Gl(r,e){let t=[],n=BP(r);for(let o of n){let i=UP(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 l=_p.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(l);let c=[l.name,...Object.keys(l)].map(u=>u.toLowerCase()),s=o.match(/\b(\S+)=([^;]*)/g);if(s)for(let u of s){let[d,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...l,name:d,value:p})}}return t}var zP=we.object({origin:we.string(),localStorage:we.array(we.object({name:we.string(),value:we.string()}))}),HP=we.object({entries:we.record(we.string(),we.array(we.tuple([we.unknown(),we.unknown()]))),version:we.number().optional()}),Vl=we.object({cookies:_p.array().optional(),origins:zP.array().optional(),idb:we.record(we.string(),HP).optional().describe("key is db name")});function xS(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=_p.safeParse({name:n.key,...n});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}import QP from"zod";import{v4 as F2}from"uuid";import{z as be}from"zod";import*as De from"zod";var _S=De.object({requiredText:De.string().optional(),requiredAttributes:De.record(De.string(),De.string()).optional(),requiredBounds:De.boolean().optional()}),GP=De.object({xPath:De.string(),requirements:_S.optional()}),VP=De.object({type:De.literal("NATIVE"),bounds:De.number().array(),resolvedDescription:De.string(),xPath:De.string(),elementOnlySerializedXml:De.string(),requirements:_S.optional(),requiredRelatedElements:GP.array().optional()}),jP=De.object({type:De.literal("WEBVIEW"),resolvedDescription:De.string(),xPath:De.string(),browserCache:On.optional()}),IS=De.discriminatedUnion("type",[VP,jP]);var Di=(s=>(s.AI_CHECK="AI_CHECK",s.TAP="TAP",s.TYPE="TYPE",s.PRESS="PRESS",s.OPEN_APP="OPEN_APP",s.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",s.JAVASCRIPT="JAVASCRIPT",s.ADB="ADB",s.STATE="STATE",s))(Di||{}),PS=(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))(PS||{}),MS=be.discriminatedUnion("type",[be.object({type:be.literal("description"),description:be.string()}),be.object({type:be.literal("coordinates"),xPercent:be.number(),yPercent:be.number()})]),hn=be.object({id:be.string().uuid(),disableCache:be.boolean().optional()}),$P=hn.extend({type:be.literal("STATE")}),OS=be.object({target:IS}),Ip=hn.extend({type:be.literal("TAP"),target:MS,cache:OS.optional()}),Pp=hn.extend({type:be.literal("TYPE"),target:MS.optional(),cache:OS.optional(),text:be.string()}),WP=hn.extend({type:be.literal("OPEN_NOTIFICATION_DRAWER")}),qP=hn.extend({type:be.literal("PRESS"),key:be.nativeEnum(PS)}),KP=hn.extend({type:be.literal("OPEN_APP"),packageName:be.string(),activityName:be.string().optional()}),YP=hn.extend({type:be.literal("AI_CHECK"),assertion:be.string(),timeoutSecs:be.number().optional()}),XP=hn.extend({type:be.literal("JAVASCRIPT"),code:be.string(),timeout:be.number().int().max(60).optional().describe("Max seconds for the code to complete")}),JP=hn.extend({type:be.literal("ADB"),command:be.string()}),LS=be.discriminatedUnion("type",[Ip,Pp,qP,KP,WP,YP,XP,JP,$P]);var NS={type:!0,cache:!0},ki=QP.discriminatedUnion("type",[Ip.pick(NS),Pp.pick(NS)]),$2=Object.values(Di).filter(r=>ki.options.some(e=>e.shape.type.safeParse(r).success));var DS=za(ki),kS=Ha(ki),W2=bl(ki);import{cloneDeep as Y2}from"lodash-es";import J2 from"truncate-json";import Gn from"zod";import Ja from"zod";var ZP=Ja.object({id:Ja.string().uuid(),envKey:Ja.string().optional()}),fn=ZP.extend({type:Ja.literal("MOBILE_PRESET_STEP"),command:LS}),rK=Ja.discriminatedUnion("type",[fn]);import Ye from"zod";var Fi=Ye.object({startTime:Ye.number(),endTime:Ye.number().optional(),error:Ye.string().optional()});var Mp=Fi.extend({type:Ye.literal("SECTION"),name:Ye.string(),subSpans:Ye.lazy(()=>iM.array())}),eM=Fi.extend({type:Ye.literal("AI_LOCATOR_CALL"),result:Ye.object({serializedElement:Ye.string(),id:Ye.number(),thoughts:Ye.string()}).optional()}),tM=Fi.extend({type:Ye.literal("AI_ASSERTION_CALL"),result:Ye.object({thoughts:Ye.string(),result:Ye.boolean()}).optional()}),rM=Fi.extend({type:Ye.literal("WAIT_FOR_STABILITY"),reason:Ye.string().optional()}),nM=Fi.extend({type:Ye.literal("RESOLVE_TARGET_CACHE"),result:Ye.object({serializedElement:Ye.string()}).optional()}),oM=Fi.extend({type:Ye.literal("GET_EMULATOR_STATE")}),iM=Ye.discriminatedUnion("type",[Mp,eM,tM,rM,nM,oM]);var aM=Gn.object({message:Gn.string().optional(),startTime:Gn.number(),endTime:Gn.number(),status:Gn.nativeEnum(Ae),trace:Mp.optional().catch(void 0),beforeSnapshot:Gn.string().optional(),afterSnapshot:Gn.string().optional()}),sM=fn.merge(aM).extend({data:Gn.unknown().optional().describe("output data from the step")}),jl=sM;import ut from"zod";import{z as Ir}from"zod";import{z as je}from"zod";var Ot=je.object({id:je.string(),name:Li,baseUrl:Hl,description:je.string().optional().nullish(),schemaVersion:je.string(),advanced:Fo,retries:je.number(),envs:je.array(Dl).nullish(),parameters:Nl.nullish(),disabled:je.boolean().optional(),labels:je.array(je.string()).optional().catch([])}),hK=je.enum(["INHERIT","ENABLED","DISABLED"]);var lM=Fo.extend({failureRecovery:je.boolean().or(je.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:je.boolean().or(je.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var fK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:lM}),SK=Ot.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),cM=je.object({labels:je.array(je.string()).optional(),outputs:Qf.nullish()}),pr=Ot.merge(cM),uM=je.object({createdAt:je.coerce.date(),updatedAt:je.coerce.date(),updatedBy:je.string().nullable(),schedule:Mi,notification:Oi,createdBy:je.string(),organizationId:je.string(),folderId:je.string().nullable().optional()}),dM=Ot.merge(uM),yK=dM.merge(Ci),$l=Ot.merge(Ci),EK=Ot.merge(Mo);var FS="test",US="module",pM="mobile-test",St=(t=>(t.TEST=`${FS}.yaml`,t.MODULE=`${US}.yaml`,t))(St||{}),Se=(n=>(n.TEST=`momentic/${FS}`,n.MODULE=`momentic/${US}`,n.MOBILE_TEST=`momentic/${pM}`,n))(Se||{}),CK=Ot.merge(Mo),Op=Wt.extend({steps:Ir.array(Ir.record(Ir.string(),Ir.unknown())),schemaVersion:Ir.string()}),xK=Op.extend({fileType:Ir.literal(Se.MODULE)}),_K=Ir.object({test:Ir.string().describe("YAML for the test, including metadata and steps"),modules:Ir.record(Ir.string(),Ir.string()).describe("Map of module name to YAML for the module")});var Qa=(t=>(t.USWest1="us-west1",t.EUNorth1="eu-north1",t))(Qa||{});var mM=ut.object({disableDefaultWebviewAccessibilityTree:ut.boolean().optional(),autoGrantPermissions:ut.boolean().optional()}),Lp=mM.extend({region:ut.nativeEnum(Qa).optional()}),Za=ut.object({retries:ut.number().optional().describe("number of retries to run"),defaultChannel:ut.string().optional().describe("default channel to use"),defaultTag:ut.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:ut.string().optional(),emulator:Lp.optional()}),Np=ut.object({id:ut.string().uuid(),description:ut.string(),schemaVersion:ut.string(),settings:Za.optional()}),gM=Np.merge(ut.object({steps:ut.array(fn)})),BS=ut.object({fileType:ut.literal(Se.MOBILE_TEST)}).merge(gM),DK=ut.object({name:ut.string(),steps:ut.array(fn).optional(),settings:Za.optional()});var ZK=new Set(Object.values(qe));var hM={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",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"},eY={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],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:[]},tY={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.",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."},rY={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},nY={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import fM from"semver";import{z as SM}from"zod";var sY=SM.string().refine(r=>fM.valid(r),{message:"must be a valid semver string"});import{Faker as uY,en as dY}from"@faker-js/faker";import{z as D}from"zod";var Ui=55555,mY=D.object({body:D.string(),to:D.string(),from:D.string()}),gY=D.object({from:D.string().optional(),to:D.string(),timeout:D.number().optional(),beforeDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional()}),hY=D.object({to:D.string().email(),from:D.string(),subject:D.string(),body:D.string(),html:D.string().optional()}),fY=D.object({inbox:D.string().transform(r=>r.toLowerCase()),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),timeout:D.number().optional(),trimWhitespace:D.boolean().optional()}),SY=D.object({inbox:D.string(),limit:D.number().optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),trimWhitespace:D.boolean().optional()});var Wl=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(Wl||{}),zS=D.object({body:D.string().nullish(),status:D.number().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}),yM=D.object({url:D.string(),options:D.object({method:D.string(),body:D.string().nullish(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),EM=D.object({body:D.string().nullish(),options:D.object({status:D.number(),statusText:D.string().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}).optional()}).optional(),HS=D.object({result:D.unknown(),variableUpdates:D.record(D.string(),D.unknown()).optional(),persistentVariableUpdates:D.record(D.string(),D.unknown()).optional(),error:D.string().optional(),success:D.boolean()}),yY=D.object({id:D.string().optional(),orgId:D.string(),momenticLambdaAuthHash:D.string(),code:D.string(),fragment:D.boolean(),state:D.object({env:D.record(D.string(),D.unknown()),request:yM,response:EM,additionalBindings:D.record(D.string(),D.unknown()).optional()}),timeoutMs:D.number().optional(),disallowVariableUpdates:D.boolean().optional(),responseSerialization:D.nativeEnum(Wl).optional()}),Vn=15e3;import*as Lt from"zod";import{extendZodWithOpenApi as TM}from"zod-openapi";TM(Lt);var bM=Lt.object({url:Lt.string(),lineNumber:Lt.number(),columnNumber:Lt.number()}).openapi({ref:"CodeLocation"}),ql=Lt.object({timestamp:Lt.number(),text:Lt.string(),type:Lt.string(),tabIndex:Lt.number(),args:Lt.unknown().array().optional(),url:Lt.string().optional(),location:bM.optional()}).openapi({ref:"ConsoleLog"}),GS=ql.array(),vM=GS.array();import*as kp from"zod";import{extendZodWithOpenApi as GM}from"zod-openapi";import{z as P}from"zod";var RM=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),AM=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),wM=P.object({onContentLoad:P.number().optional(),onLoad:P.number().optional(),comment:P.string().optional()}),jS=P.object({startedDateTime:P.string(),id:P.string(),title:P.string().optional(),pageTimings:wM,comment:P.string().optional()}),CM=P.array(jS),xM=P.object({name:P.string(),value:P.string(),path:P.string().optional(),domain:P.string().optional(),expires:P.string().optional(),httpOnly:P.boolean().optional(),secure:P.boolean().optional(),comment:P.string().optional()}),$S=P.array(xM),_M=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),WS=P.array(_M),IM=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),PM=P.array(IM),MM=P.object({name:P.string(),value:P.string().optional(),fileName:P.string().optional(),contentType:P.string().optional(),comment:P.string().optional()}),OM=P.array(MM),LM=P.object({mimeType:P.string(),params:OM,text:P.string(),comment:P.string().optional()}),NM=P.object({method:P.string(),url:P.string(),httpVersion:P.string().optional(),cookies:$S,headers:WS,queryString:PM,postData:LM.optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional()}),DM=P.object({size:P.number().optional(),compression:P.number().optional(),mimeType:P.string().optional(),text:P.string().optional(),encoding:P.string().optional(),comment:P.string().optional()}),kM=P.object({status:P.number(),statusText:P.string(),httpVersion:P.string().optional(),cookies:$S,headers:WS,content:DM,redirectURL:P.string().optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional(),_mocked:P.boolean().optional()}),VS=P.object({expires:P.string().optional(),lastAccess:P.string(),eTag:P.string(),hitCount:P.number(),comment:P.string().optional()}),FM=P.object({beforeRequest:VS.optional(),afterRequest:VS.optional(),comment:P.string().optional()}),UM=P.object({blocked:P.number().optional(),dns:P.number().optional(),connect:P.number().optional(),send:P.number(),wait:P.number(),receive:P.number(),ssl:P.number().optional(),comment:P.string().optional()}),qS=P.object({pageref:P.string().optional(),startedDateTime:P.string(),time:P.number().optional(),request:NM,response:kM.optional(),cache:FM.optional(),timings:UM,serverIPAddress:P.string().optional(),connection:P.string().optional(),comment:P.string().optional(),_resourceType:P.string().optional()}),BM=P.array(qS),zM=P.object({version:P.string().default("1.1"),creator:RM.optional(),browser:AM.optional(),pages:CM.optional(),entries:BM,comment:P.string().optional()}),HM=P.object({log:zM}),KS=P.record(P.string(),jS),YS=P.record(P.string(),qS);function Dp(r,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(r).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime()),entries:Object.values(e).sort((t,n)=>new Date(t.startedDateTime).getTime()-new Date(n.startedDateTime).getTime())}}}GM(kp);var VM=kp.object({logsPerPage:ql.array().array(),harPages:KS.optional(),harEntries:YS.optional()}).openapi({ref:"DebugData"});var es=class{async getConsoleLogsForRunAttempt(e,t,n){}async getNetworkLogsForRunAttempt(e,t,n){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}async storeConsoleLogsForRunAttempt(e,t,n,o){}async storeNetworkLogsForRunAttempt(e,t,n,o){}async storeScreenshot(e,t,n){}async storeHtmlSnapshot(e,t,n){}};var Ie=class extends Error{constructor(e,t={}){super(e,t),this.name="ValidationError"}};var Kl=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function XS(r){for(let e of Object.values(me))if(r.includes(e))return e}var C=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(me))if(t.startsWith(i)){o=!0,e=i;break}if(n?.errOptions?.cause)super(o?t:`${e}: ${t}`,n?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;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}}},Bi=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},jr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
5
5
  Decisions:
6
6
  ${this.decisions.map(e=>e.toString()).join(`
7
- `)}`}};function qS(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Np(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var $r=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},$l=class extends $r{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Wl=class extends $r{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function KS(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function Za(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function Dp(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var Qa=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as IM}from"lodash-es";import{z as Wr}from"zod";var Sn=(g=>(g.DisableClickhouseCaches="disable_clickhouse_caches",g.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",g.IconKnowledgeBase="icon_knowledge_base",g.MiniModelInitialAssertion="mini_model_initial_assertion",g.MiniModelInitialLocator="mini_model_initial_locator",g.ShowTestPlans="show_test_plans",g.AiPageSummary="ai_page_summary",g.ShowZeroOpacityElements="show_zero_opacity_elements",g.VisualActions="visual_actions",g.RagV2="rag_v2",g.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",g.GlobalLocatorRedirect="global_locator_redirect",g.FakerConstantSeed="faker_constant_seed",g.AutoExpandIframes="auto_expand_iframes",g))(Sn||{});var YS=Wr.union([Wr.string(),Wr.number(),Wr.boolean(),Wr.null(),Wr.record(Wr.string(),Wr.lazy(()=>YS)),Wr.array(Wr.lazy(()=>YS))]),es=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}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=IM(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Sn).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},WY=new es({},{});var kp={".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"},XS=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],KY=Object.keys(kp);import*as JS from"zod";var XY=JS.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as Wn}from"zod";var ZY=Wn.object({id:Wn.string(),name:Wn.string(),createdAt:Wn.coerce.date(),createdBy:Wn.string(),updatedAt:Wn.coerce.date(),updatedBy:Wn.string().nullable(),organizationId:Wn.string()});import{z as N}from"zod";import qn from"zod";var Hi=qn.object({platformSep:qn.string(),fullPathSegments:qn.string().array(),relativePathSegments:qn.string().array(),relativePath:qn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:qn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:qn.coerce.date(),createdAt:qn.coerce.date()});var PM=N.array(Hi.extend({id:N.string(),name:N.string(),description:N.string().optional(),labels:N.string().array().optional()})),MM=N.array(Hi.extend({id:N.string(),name:N.string(),description:N.string().optional(),content:za})),p5=N.object({tests:PM,modules:MM,labels:N.string().array()}),m5=Hl.merge(mr),QS=N.object({schemaVersion:N.string(),stepLists:xi}),ZS=mr.partial().merge(Ot.pick({id:!0})),Fp={name:N.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:N.string().optional(),baseUrl:N.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:N.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:N.nativeEnum(gn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:_l.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:N.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},ey=N.object(Fp),g5=Hl.merge(N.object({relativeFilePath:N.string().describe("relative to project root")})),ty=N.object({name:N.string()}),h5=N.object({relativeFilePath:N.string()}),ry=N.object({name:N.string()}),f5=N.object({relativeFilePath:N.string()}),ny=N.object({name:N.string(),description:N.string(),enabled:N.boolean(),steps:N.lazy(()=>Ze.array()),testFilePath:N.string().describe("relative to the project root"),folderPath:N.string().optional().describe("user selected folder path")}),oy=N.object({name:N.string(),description:N.string(),enabled:N.boolean()}).partial();var S5=N.array(zf),iy=N.object({defaultEnv:N.string().optional().describe("name of the default env, or undefined to unset")}),ay=N.object({configFilePath:N.string().describe("full path on disk")}),y5=N.string().array(),E5=N.object({message:N.string(),newRelativeTestPath:N.string().optional()}),Up=N.object({name:N.string(),absolutePath:N.string(),relativePath:N.string(),pathSegments:N.array(N.string()),isDirectory:N.boolean(),size:N.number(),createdAt:N.coerce.date(),modifiedAt:N.coerce.date(),accessedAt:N.coerce.date()}),sy=N.object({pathSegments:N.array(N.string())}),T5=N.object({absolutePath:N.string(),pathSegments:N.array(N.string()),contents:N.array(Up)}),ly=N.object({pathSegments:N.array(N.string())}),cy=N.object({pathSegments:N.array(N.string()),newPathSegments:N.array(N.string())}),uy=N.object({pathSegments:N.array(N.string()),recursive:N.boolean().optional()}),b5=N.object({success:N.boolean(),message:N.string(),pathSegments:N.array(N.string()).optional()});var ql=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Kl=ql.map(r=>`**/${r}/**`),dy=!0,yn=!1;import qr from"chalk";import OM from"safe-stable-stringify";import LM from"truncate-json";import NM from"zod";var ts=OM.configure({deterministic:!1});function py(r){let e=ts(r),{jsonString:t}=LM(e,1e4);return t}var DM=["app","version","env","namespace","host"];function Ie(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!DM.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Bp=NM.enum(["debug","info","warn","error"]);var rs={debug:20,info:30,warn:40,error:50},Xl={20:"debug",30:"info",40:"warn",50:"error"},ns=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=rs[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...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(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=ts(c,void 0,2),s=s.split(`
7
+ `)}`}};function JS(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function Fp(r){return!(r instanceof Error)||r.message.includes("locator resolved to visible")?!1:!!(r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("body >")||r.message.includes("Element is not attached to the DOM"))}var $r=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Yl=class extends $r{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Xl=class extends $r{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function QS(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}function rs(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator")&&r.message.includes("data-momentic-id")&&!r.message.includes("locator resolved")&&!r.message.includes("waiting for element to be"):!1}function Up(r){return r instanceof Error?r.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||r.message.includes("Could not resolve backend node"):!1}var ts=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};import{cloneDeep as jM}from"lodash-es";import{z as Wr}from"zod";var jn=(g=>(g.DisableClickhouseCaches="disable_clickhouse_caches",g.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",g.IconKnowledgeBase="icon_knowledge_base",g.MiniModelInitialAssertion="mini_model_initial_assertion",g.MiniModelInitialLocator="mini_model_initial_locator",g.ShowTestPlans="show_test_plans",g.AiPageSummary="ai_page_summary",g.ShowZeroOpacityElements="show_zero_opacity_elements",g.VisualActions="visual_actions",g.RagV2="rag_v2",g.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",g.GlobalLocatorRedirect="global_locator_redirect",g.FakerConstantSeed="faker_constant_seed",g.AutoExpandIframes="auto_expand_iframes",g))(jn||{});var ZS=Wr.union([Wr.string(),Wr.number(),Wr.boolean(),Wr.null(),Wr.record(Wr.string(),Wr.lazy(()=>ZS)),Wr.array(Wr.lazy(()=>ZS))]),ns=class{flags;payloads;constructor(e,t){this.flags=e,this.payloads=t}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=jM(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(jn).includes(t)&&(e[t]=this.isBooleanFlagEnabled(t))}),e}getFlagPayload(e){let t=this.payloads[e];if(t!==void 0){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}}refresh(){throw new Error("Not implemented")}},s5=new ns({},{});var Bp={".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"},ey=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],c5=Object.keys(Bp);import*as ty from"zod";var d5=ty.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as $n}from"zod";var g5=$n.object({id:$n.string(),name:$n.string(),createdAt:$n.coerce.date(),createdBy:$n.string(),updatedAt:$n.coerce.date(),updatedBy:$n.string().nullable(),organizationId:$n.string()});import{z as L}from"zod";import Wn from"zod";var zi=Wn.object({platformSep:Wn.string(),fullPathSegments:Wn.string().array(),relativePathSegments:Wn.string().array(),relativePath:Wn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:Wn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:Wn.coerce.date(),createdAt:Wn.coerce.date()});var $M=L.array(zi.extend({id:L.string(),name:L.string(),description:L.string().optional(),labels:L.string().array().optional()})),WM=L.array(zi.extend({id:L.string(),name:L.string(),description:L.string().optional(),content:Va})),x5=L.object({tests:$M,modules:WM,labels:L.string().array()}),_5=$l.merge(pr),ry=L.object({schemaVersion:L.string(),stepLists:Ci}),ny=pr.partial().merge(Ot.pick({id:!0})),zp={name:L.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:L.string().optional(),baseUrl:L.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:L.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:L.nativeEnum(gn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ol.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:L.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},oy=L.object(zp),I5=$l.merge(L.object({relativeFilePath:L.string().describe("relative to project root")})),iy=L.object({name:L.string()}),P5=L.object({relativeFilePath:L.string()}),ay=L.object({name:L.string()}),M5=L.object({relativeFilePath:L.string()}),sy=L.object({name:L.string(),description:L.string(),enabled:L.boolean(),steps:L.lazy(()=>et.array()),testFilePath:L.string().describe("relative to the project root"),folderPath:L.string().optional().describe("user selected folder path")}),ly=L.object({name:L.string(),description:L.string(),enabled:L.boolean()}).partial();var O5=L.array(jf),cy=L.object({defaultEnv:L.string().optional().describe("name of the default env, or undefined to unset")}),uy=L.object({configFilePath:L.string().describe("full path on disk")}),L5=L.string().array(),N5=L.object({message:L.string(),newRelativeTestPath:L.string().optional()}),Hp=L.object({name:L.string(),absolutePath:L.string(),relativePath:L.string(),pathSegments:L.array(L.string()),isDirectory:L.boolean(),size:L.number(),createdAt:L.coerce.date(),modifiedAt:L.coerce.date(),accessedAt:L.coerce.date()}),dy=L.object({pathSegments:L.array(L.string())}),D5=L.object({absolutePath:L.string(),pathSegments:L.array(L.string()),contents:L.array(Hp)}),py=L.object({pathSegments:L.array(L.string())}),my=L.object({pathSegments:L.array(L.string()),newPathSegments:L.array(L.string())}),gy=L.object({pathSegments:L.array(L.string()),recursive:L.boolean().optional()}),k5=L.object({success:L.boolean(),message:L.string(),pathSegments:L.array(L.string()).optional()});var Jl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Ql=Jl.map(r=>`**/${r}/**`),hy=!0,Sn=!1;import qr from"chalk";import qM from"safe-stable-stringify";import KM from"truncate-json";import YM from"zod";var os=qM.configure({deterministic:!1});function fy(r){let e=os(r),{jsonString:t}=KM(e,1e4);return t}var XM=["app","version","env","namespace","host"];function Pe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!XM.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Gp=YM.enum(["debug","info","warn","error"]);var is={debug:20,info:30,warn:40,error:50},ec={20:"debug",30:"info",40:"warn",50:"error"},as=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=is[e]:this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){try{this.logWithLevelHelper(e,t,...n)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,t,...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(t(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[l,c]of a){let s=c;c instanceof Error?(s=c.message,console.log(t(` ${l}:`,s)),console.log(t(" stack:",c.stack))):typeof c=="object"&&(s=os(c,void 0,2),s=s.split(`
8
8
  `).map((u,d)=>d>0?` ${u}`:u).join(`
9
- `),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=ts(a,void 0,2),l=l.split(`
9
+ `),console.log(t(` ${l}:`,s)))}}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=os(a,void 0,2),l=l.split(`
10
10
  `).map((c,s)=>s>0?` ${c}`:c).join(`
11
- `)),console.log(" ",t(l))}}getLevel(){return Xl[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=rs[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,qr.reset,...e)}info(...e){this.logWithLevel(30,qr.white,...e)}debug(...e){this.logWithLevel(20,qr.dim,...e)}warn(...e){this.logWithLevel(40,qr.yellow,...e)}error(...e){this.logWithLevel(50,qr.red,...e)}success(...e){this.logWithLevel(1/0,qr.green,...e)}dimmed(...e){this.logWithLevel(30,qr.dim,...e)}underline(...e){this.logWithLevel(40,qr.underline,...e)}bold(...e){this.logWithLevel(40,qr.bold,...e)}grey(...e){this.logWithLevel(20,qr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},zp=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},I5=new zp,kM=typeof window>"u"&&typeof process<"u"&&Bp.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Bp.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,E=new ns(kM,{}),En={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>En,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Yl={},Jl=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=Yl[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},Yl[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=Yl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Yl[e]},n)};import{z as Ae}from"zod";var FM=Ae.array(Hi.extend({id:Ae.string(),name:Ae.string(),description:Ae.string().optional(),labels:Ae.string().array().optional()})),UM=Ae.array(Hi.extend({id:Ae.string(),name:Ae.string(),description:Ae.string().optional(),content:za})),D5=Ae.object({name:Ae.string(),description:Ae.string().optional(),steps:Ae.array(fn).optional(),settings:Xa.optional(),pathSegments:Ae.string().array()}),k5=Ae.object({id:Ae.string(),fileName:Ae.string(),fullPath:Ae.string(),relativeFilePath:Ae.string().describe("relative to project root")});var F5=Ae.object({steps:Ae.array(fn).optional(),settings:Xa.optional()}),U5=Ae.object({message:Ae.literal("ok")}),B5=Ae.object({tag:Ae.string(),channel:Ae.string(),filePath:Ae.string()}),z5=Ae.object({tests:FM,modules:UM,labels:Ae.string().array()});import{z as nt}from"zod";var my=nt.object({id:nt.string(),createdAt:nt.coerce.date(),createdBy:nt.string(),organizationId:nt.string(),name:nt.string(),description:nt.string().nullish(),enabled:nt.boolean(),schemaVersion:nt.string().describe("Schema version for steps"),parameters:nt.string().array().nullish().describe("Parameter list"),parameterEnums:nt.record(nt.string(),nt.string().array()).nullish(),defaultParameters:nt.record(nt.string(),nt.string()).nullish(),defaultCacheKey:nt.string().nullish(),defaultCacheTtl:nt.number().nullish(),defaultCacheAllInvocations:nt.boolean().nullish(),autoAuth:nt.boolean().nullish(),advanced:tp.nullish()}),Y5=my.extend({steps:nt.lazy(()=>Oe.array())}),gy=5*60*1e3,Hp=Wt.merge(my.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as Q5}from"date-fns-tz";import{z as De}from"zod";var Gp=hp.extend({aiAction:De.boolean().optional(),stepLintSuggestions:De.boolean().optional(),agentConfig:De.record(De.string(),De.string()).optional(),aiFailureAnalysis:De.boolean().optional(),aiPageFiltering:De.boolean().optional().describe("rag v2 feature flag")}),Vp=De.object({fakerConstantSeed:De.boolean().optional()}),hy=De.object({ai:Gp.optional(),githubAppInstallationId:De.number().nullish(),githubAppSummaryMessageEnabled:De.boolean().nullish(),githubReleaseAppInstallationId:De.number().nullish(),gitlabAppAccessToken:De.string().nullish(),gitlabAppBaseUrl:De.string().nullish(),qaseAccessToken:De.string().nullish(),testSuggestionsEnabled:De.boolean().nullish(),browser:lp.optional(),advanced:Vp.optional()}),o3=De.object({globalOverrides:De.record(De.string()).optional(),agentConfig:De.record(De.string(),De.string()).optional()}),i3=De.record(De.string(),De.string()).nullish();import*as b from"zod";import{z as et}from"zod";var jp=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(jp||{});var BM=et.object({type:et.literal("DESCRIPTION_UPDATE"),thoughts:et.string()}),Ql=et.discriminatedUnion("type",[BM]),zM=et.object({testId:et.string(),name:et.string(),orgId:et.string(),runId:et.string(),steps:Ze.array(),purpose:et.nativeEnum(jp),details:Ql.or(Ql.array()).optional()});var c3=zM.pick({name:!0,orgId:!0}),HM=et.object({id:et.string(),name:et.string().nullish(),createdAt:et.string().pipe(et.coerce.date()).or(et.date()),organizationId:et.string(),schemaVersion:et.string(),runId:et.string().nullish(),purpose:et.nativeEnum(jp),details:Ql.or(Ql.array()).optional(),applied:et.boolean().nullish(),appliedAt:et.coerce.date().nullish()}),fy=HM.extend({steps:Ze.array()});var Sy="x-momentic-cli-version",yy="x-momentic-cli-type",GM="x-momentic-main-branch-name",VM="x-momentic-branch-name",jM="x-momentic-commit-timestamp",$M="x-momentic-last-commit-on-main",WM="x-momentic-last-commit-on-main-timestamp",qM="x-momentic-merged-branch-name",w3=b.object({error:b.boolean(),reason:b.string(),message:b.string()}),C3=Vt.merge(yp),Ey=hl,x3=Vt.merge(yp);var _3=Vt.merge(sS).extend({useConsensus:b.boolean().optional(),attemptNumber:b.number().optional()}),$p=pf,I3=Vt.merge(lS),Ty=Pf,P3=Vt.merge(oS),by=If,M3=Vt.merge(iS),vy=xf,O3=Vt.merge(aS);var L3=Vt.merge(pS),N3=b.object({testPaths:b.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:b.string().optional(),all:b.boolean().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional(),testInputMatrix:b.record(b.string(),b.string()).array().optional()}),Ry=b.object({queuedTests:b.unknown().array(),runIds:b.string().uuid().array(),runGroupId:b.string().optional()});var D3=b.string().array(),k3=b.union([b.object({paths:b.string().array().describe("run specific test paths (e.g. todo-test)"),all:b.boolean().describe("run all tests").optional()}),b.object({path:b.string().describe("deprecated; present for backcompat")})]),Ay=b.object({tests:b.record(b.string().describe("Test name"),b.string().describe("Test YAML")),modules:b.record(b.string().describe("Module name"),b.string().describe("Module YAML"))}),KM=b.object({test:b.string().describe("test YAML"),modules:b.record(b.string().describe("moduleId"),b.string().describe("module YAML"))}),F3=KM.array(),U3=b.object({testId:b.string(),schemaVersion:b.string()}).merge(Oo);function Wp(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[GM]=encodeURIComponent(e)),t&&(a[VM]=encodeURIComponent(t)),n&&(a[jM]=n.toISOString()),o&&(a[$M]=encodeURIComponent(o)),i&&(a[WM]=i.toISOString()),r.mergedGitBranchName&&(a[qM]=encodeURIComponent(r.mergedGitBranchName)),a}var B3=b.object({entries:b.array(vf),testId:b.string()}),z3=b.object({entries:b.array(MS),testId:b.string()}),H3=b.object({testId:b.string()});function wy(r){return b.record(b.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var Cy=wy(Rf),xy=wy(OS),_y=b.object({trigger:b.nativeEnum(ur),status:b.nativeEnum(me),startedAt:b.coerce.date().optional(),gitCommitSha:b.string().optional(),gitCommitShaShort:b.string().optional(),gitCommitTimestamp:b.coerce.date().optional(),gitBranchName:b.string().optional(),gitOriginUrl:b.string().optional(),gitCommitMessage:b.string().optional(),gitCommitAuthorName:b.string().optional(),githubRepository:b.string().optional(),gitlabProjectPath:b.string().optional(),pipelineId:b.string().optional(),cliVersion:b.string().optional()}),G3=b.object({id:b.string()}),Iy=b.object({status:b.nativeEnum(me),updatedAt:b.coerce.date().optional(),finishedAt:b.coerce.date().optional()}),Py=b.object({stepsSnapshot:b.array(b.record(b.unknown())).optional(),runGroupId:b.string().optional(),testId:b.string(),testName:b.string(),resolvedBaseUrl:b.string().optional(),environmentName:b.string().optional(),labels:b.array(b.string()).optional(),cliVersion:b.string().optional(),trigger:b.nativeEnum(ur),schemaVersion:b.string().optional(),section:b.nativeEnum(Ol).optional(),resolvedInputs:b.record(b.string(),b.string()).optional(),quarantined:b.boolean().optional().default(!1),quarantinedReason:b.string().optional()}),V3=b.object({id:b.string()}),YM=fp.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),My=YM.array(),Oy=fp.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(),j3=b.object({id:b.string()}),Ly=b.object({status:b.nativeEnum(me),finishedAt:b.coerce.date().optional(),schemaVersion:b.string().optional().default("1.0.19"),results:b.record(b.string(),b.unknown()).array().optional(),beforeResults:b.record(b.string(),b.unknown()).array().optional(),afterResults:b.record(b.string(),b.unknown()).array().optional()}),$3=b.object({screenshot:b.string()}),Ny=b.object({key:b.string()}),Dy=b.object({orgId:b.string(),userId:b.string()}),ky=b.array(Bf),W3=b.record(b.string(),b.union([b.string(),b.boolean()])),q3=b.object({paths:b.string().array(),env:b.string().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional()}),Fy=b.object({suiteRunIds:b.string().array(),runGroupIds:b.string().array()}),K3=b.object({suiteRunIds:b.string().array()}),Y3=eS.array(),X3=b.object({runGroupIds:b.string().array()}),XM=b.object({uploadUrl:b.string()}),J3=Vt.merge(cS),Q3=Vt.merge(dS),Z3=Vt.merge(uS),JM=b.object({testId:b.string().optional().default(""),testName:b.string().optional().default(""),suiteId:b.string().optional().default(""),suiteName:b.string().optional().default(""),creditsUsed:b.number().optional()}),QM=b.object({transactionId:b.string(),timestamp:b.string(),event:b.nativeEnum(qa),properties:JM}),eX=QM.array(),Uy=fy.omit({steps:!0}).extend({steps:b.array(b.record(b.string(),b.unknown())).describe("unparsed ResolvedStep[]")}),tX=b.object({limit:b.number().max(10).optional(),afterTime:b.number().optional()}),By=Yf.array(),rX=b.object({applied:b.boolean().optional(),appliedAt:b.coerce.date().optional()}),zy=XM.extend({id:b.string()}),nX=b.object({runGroupId:b.string().uuid().optional()}),Hy=b.object({runGroupId:b.string().uuid()}),Gy=b.object({quarantined:b.object({testId:b.string().uuid(),quarantinedAt:b.coerce.date(),quarantinedBy:b.string().optional(),quarantinedReason:b.string()}).array()}),oX=b.object({testId:b.string().uuid(),testName:b.string().optional(),reason:b.string(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),iX=b.object({testName:b.string().optional(),reason:b.string().optional(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),aX=Vt.merge(hS),sX=Vt.merge(fS),lX=b.object({apkToInstall:b.object({channel:b.string(),tag:b.string().optional()}).optional(),hostname:b.string().optional(),region:b.nativeEnum(Ya).optional()}),Vy=b.object({name:b.string(),webRtcUrl:b.string(),adbUrl:b.string(),token:b.string(),apkDownloadUrl:b.string().optional(),region:b.string().optional()}),cX=b.object({channel:b.string(),tag:b.string(),md5:b.string()}),jy=b.object({id:b.string(),uploadUrl:b.string().optional(),downloadUrl:b.string(),md5:b.string().optional()}),$y=b.object({assets:b.array(b.object({channel:b.string(),tag:b.string(),md5:b.string(),createdAt:b.number().describe("Unix timestamp in milliseconds")}))});import{z as J}from"zod";var ZM=3,pX=J.object({localTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()}).or(J.object({cloudTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()})),Wy=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(Wy||{});var qp=J.object({name:J.string(),description:J.string().nullish(),effect:J.nativeEnum(Wy),labels:J.array(J.string()),githubRepository:J.string().nullish(),gitlabProjectPath:J.string().nullish(),gitBranchName:J.string().nullish()}),eO=J.object({type:J.literal("LAST_N_RUNS"),lastN:J.number().min(ZM).max(10)}),tO=J.object({type:J.literal("LAST_N_HOURS"),lastN:J.number().min(1).max(24)}),rO=J.object({type:J.literal("LAST_N_DAYS"),lastN:J.number().min(1).max(7)}),Kp=J.discriminatedUnion("type",[eO,tO,rO]),nO=J.object({flakeRateThreshold:J.number().min(1).max(100),evaluationWindow:Kp}),oO=qp.extend({type:J.literal("FLAKE_RATE"),config:nO}),iO=J.object({passRateThreshold:J.number().min(1).max(100),evaluationWindow:Kp}),aO=qp.extend({type:J.literal("PASS_RATE"),config:iO}),sO=J.object({failureCountThreshold:J.number().min(0),evaluationWindow:Kp}),lO=qp.extend({type:J.literal("FAILURE_COUNT"),config:sO}),mX=J.discriminatedUnion("type",[oO,aO,lO]);import{z as ot}from"zod";var fX=ot.object({repositoriesIndexed:ot.boolean(),indexingInProgress:ot.boolean(),indexesOutdated:ot.boolean()}),qy=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(qy||{}),Ky=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(Ky||{}),SX=ot.object({name:ot.string(),status:ot.nativeEnum(qy),conclusion:ot.nativeEnum(Ky).nullable()}),os=ot.object({sha:ot.string(),message:ot.string(),author:ot.object({name:ot.string().optional(),email:ot.string().optional(),date:ot.coerce.date().optional()}),committer:ot.object({name:ot.string().optional(),email:ot.string().optional(),date:ot.coerce.date().optional()})}),Yp=ot.object({mergedBranch:ot.string().optional()});import{z as je}from"zod";var Yy=je.object({orgId:je.string(),cacheKeys:je.string().array()}),TX=je.object({keyParams:Yy,clientMetadata:je.string(),lockAcquisitionTimeoutMs:je.number().optional()}),Xy=je.object({acquired:je.boolean(),acquiredByMetadata:je.string(),keyPrefix:je.string()}),bX=je.object({keyPrefix:je.string(),result:je.string(),ttlMs:je.number()}),vX=je.union([je.object({keyPrefix:je.string()}),Yy]),cO=je.object({remainingTtlMs:je.number(),value:je.string().nullish()}),RX=je.object({results:je.record(je.string(),cO),activeLocks:je.string().array()}),Jy=0,Qy=5*60*1e3;var xX=90*24*60*60*1e3,_X=7*24*60*60*1e3;import{z as Zy}from"zod";var MX=Zy.object({quarantineNotifications:Zy.string().nullish()});import{z as vt}from"zod";var uO=vt.object({version:vt.string(),json:vt.record(vt.unknown()),hash:vt.string()}),eE=vt.record(vt.unknown()),DX=vt.object({newSvgs:vt.array(uO),metadata:eE.optional()}),dO=vt.object({version:vt.string(),json:vt.record(vt.unknown()).nullish(),hash:vt.string(),description:vt.string().nullish(),metadata:eE.nullish()}),tE=vt.record(vt.string().describe("icon hash"),dO);import{z as Ye}from"zod";var Xp=Ye.object({assertion:Ye.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),pO=Ye.object({instruction:Ye.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:Xp.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.")}),rE=pO.extend({subSteps:Ye.lazy(()=>rE.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),nE=Ye.object({name:Ye.string().describe("Short name describing the test plan"),description:Ye.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),oE=nE.extend({id:Ye.string(),createdAt:Ye.coerce.date(),updatedAt:Ye.coerce.date(),updatedBy:Ye.string(),createdBy:Ye.string(),test:Ye.object({id:Ye.string(),name:Ye.string()}).nullish().transform(r=>r??void 0)}),BX=oE.extend({testGenRuns:Ye.tuple([]).or(Ye.tuple([Ye.object({id:Ye.string(),startedAt:Ye.coerce.date(),status:Ye.nativeEnum(me)})]))}),iE=Ye.object({preConditions:Xp.array().nullish().transform(r=>r??[]),postConditions:Xp.array().nullish().transform(r=>r??[]),steps:rE.array().nullish().transform(r=>r??[])}),zX=oE.extend({plan:iE.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),mO=nE.extend({plan:iE.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),HX=mO.array().nullish().transform(r=>r??[]);import{validator as gO}from"@exodus/schemasafe";function aE(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{gO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var sE=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as o4}from"zod";var Zl=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};var Jp=class{getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(){}async startSubSteps(){return new is}},is=class{getParentStepIdChain(){return[]}async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new Jp}};import{z as X}from"zod";var hO=X.object({step:Ze,status:X.nativeEnum(ve),startedAt:X.coerce.date(),finishedAt:X.coerce.date().optional(),healMetadata:X.object({healType:X.nativeEnum(Ha).or(X.literal("AI")),healedAt:X.coerce.date()}).optional(),beforeSnapshotId:X.string().uuid().optional(),afterSnapshotId:X.string().uuid().optional(),message:X.string().optional()}),v4=hO.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),lE="1.0.0",Qp=Ly.extend({id:X.string().uuid().optional(),startedAt:X.coerce.date(),runAttemptSchemaVersion:X.string().optional(),schemaVersion:X.string().optional().default("1.0.19"),results:X.record(X.string(),X.unknown()).array().optional(),beforeResults:X.record(X.string(),X.unknown()).array().optional(),afterResults:X.record(X.string(),X.unknown()).array().optional()}),cE=Qp.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),R4=Qp.merge(Va),A4=cE.merge(Va),uE=X.object({results:X.array(zl),beforeResults:X.array(zl).optional(),afterResults:X.array(zl).optional()}),w4=Qp.merge(uE),C4=cE.merge(uE),fO=Oy.merge(Py).extend({executionType:X.nativeEnum(Mi).optional().default("WEB"),testId:X.string().uuid(),testDescription:X.string().optional(),runGroupId:X.string().uuid(),status:X.nativeEnum(me),startedAt:X.coerce.date(),attempts:X.number(),failureRecoveryDetails:X.record(X.unknown()).optional()}),x4=fO.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),SO=_y.merge(Iy).extend({id:X.string().uuid().optional(),startedAt:X.coerce.date(),cliVersion:X.string(),labels:X.string().array().optional().default([])}),as=SO.extend({updatedAt:X.coerce.date().optional().transform(r=>r??new Date),finishedAt:X.coerce.date().optional().transform(r=>r??new Date)});function dE(r){try{return yO(r)&&EO(r).isDirectory()}catch(e){return E.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import{confirm as MO,input as OO}from"@inquirer/prompts";import{existsSync as LO,mkdirSync as NO,statSync as DO}from"fs";import{dirname as kO}from"path";import Kr,{supportsColor as IO}from"chalk";import{Console as pE}from"console";import{format as ss}from"util";var Zp=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},ec=class r extends pE{_buffer=[];_groupDepth=0;Console=pE;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new Zp(void 0,r.write).stack;if(!i)return e;let a=i.split(`
11
+ `)),console.log(" ",t(l))}}getLevel(){return ec[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=is[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,qr.reset,...e)}info(...e){this.logWithLevel(30,qr.white,...e)}debug(...e){this.logWithLevel(20,qr.dim,...e)}warn(...e){this.logWithLevel(40,qr.yellow,...e)}error(...e){this.logWithLevel(50,qr.red,...e)}success(...e){this.logWithLevel(1/0,qr.green,...e)}dimmed(...e){this.logWithLevel(30,qr.dim,...e)}underline(...e){this.logWithLevel(40,qr.underline,...e)}bold(...e){this.logWithLevel(40,qr.bold,...e)}grey(...e){this.logWithLevel(20,qr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},Vp=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},j5=new Vp,JM=typeof window>"u"&&typeof process<"u"&&Gp.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Gp.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,T=new as(JM,{}),yn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>yn,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Zl={},tc=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let l=Zl[e];l?clearTimeout(l.timer):(l={count:0,totalCount:0},Zl[e]=l),l.totalCount++,l.count<t&&(l.count++,r.debug(o,i,...a)),l.timer=setTimeout(()=>{let c=Zl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Zl[e]},n)};import{z as Ce}from"zod";var QM=Ce.array(zi.extend({id:Ce.string(),name:Ce.string(),description:Ce.string().optional(),labels:Ce.string().array().optional()})),ZM=Ce.array(zi.extend({id:Ce.string(),name:Ce.string(),description:Ce.string().optional(),content:Va})),X5=Ce.object({name:Ce.string(),description:Ce.string().optional(),steps:Ce.array(fn).optional(),settings:Za.optional(),pathSegments:Ce.string().array()}),J5=Ce.object({id:Ce.string(),fileName:Ce.string(),fullPath:Ce.string(),relativeFilePath:Ce.string().describe("relative to project root")});var Q5=Ce.object({steps:Ce.array(fn).optional(),settings:Za.optional()}),Z5=Ce.object({message:Ce.literal("ok")}),e3=Ce.object({tag:Ce.string(),channel:Ce.string(),filePath:Ce.string()}),t3=Ce.object({tests:QM,modules:ZM,labels:Ce.string().array()});import{z as it}from"zod";var Sy=it.object({id:it.string(),createdAt:it.coerce.date(),createdBy:it.string(),organizationId:it.string(),name:it.string(),description:it.string().nullish(),enabled:it.boolean(),schemaVersion:it.string().describe("Schema version for steps"),parameters:it.string().array().nullish().describe("Parameter list"),parameterEnums:it.record(it.string(),it.string().array()).nullish(),defaultParameters:it.record(it.string(),it.string()).nullish(),defaultCacheKey:it.string().nullish(),defaultCacheTtl:it.number().nullish(),defaultCacheAllInvocations:it.boolean().nullish(),autoAuth:it.boolean().nullish(),advanced:op.nullish()}),u3=Sy.extend({steps:it.lazy(()=>Le.array())}),yy=5*60*1e3,jp=Wt.merge(Sy.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as m3}from"date-fns-tz";import{z as ke}from"zod";var $p=yp.extend({aiAction:ke.boolean().optional(),stepLintSuggestions:ke.boolean().optional(),agentConfig:ke.record(ke.string(),ke.string()).optional(),aiFailureAnalysis:ke.boolean().optional(),aiPageFiltering:ke.boolean().optional().describe("rag v2 feature flag")}),Wp=ke.object({fakerConstantSeed:ke.boolean().optional()}),Ey=ke.object({ai:$p.optional(),githubAppInstallationId:ke.number().nullish(),githubAppSummaryMessageEnabled:ke.boolean().nullish(),githubReleaseAppInstallationId:ke.number().nullish(),gitlabAppAccessToken:ke.string().nullish(),gitlabAppBaseUrl:ke.string().nullish(),qaseAccessToken:ke.string().nullish(),testSuggestionsEnabled:ke.boolean().nullish(),browser:dp.optional(),advanced:Wp.optional()}),E3=ke.object({globalOverrides:ke.record(ke.string()).optional(),agentConfig:ke.record(ke.string(),ke.string()).optional()}),T3=ke.record(ke.string(),ke.string()).nullish();import*as b from"zod";import{z as tt}from"zod";var qp=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(qp||{});var eO=tt.object({type:tt.literal("DESCRIPTION_UPDATE"),thoughts:tt.string()}),rc=tt.discriminatedUnion("type",[eO]),tO=tt.object({testId:tt.string(),name:tt.string(),orgId:tt.string(),runId:tt.string(),steps:et.array(),purpose:tt.nativeEnum(qp),details:rc.or(rc.array()).optional()});var A3=tO.pick({name:!0,orgId:!0}),rO=tt.object({id:tt.string(),name:tt.string().nullish(),createdAt:tt.string().pipe(tt.coerce.date()).or(tt.date()),organizationId:tt.string(),schemaVersion:tt.string(),runId:tt.string().nullish(),purpose:tt.nativeEnum(qp),details:rc.or(rc.array()).optional(),applied:tt.boolean().nullish(),appliedAt:tt.coerce.date().nullish()}),Ty=rO.extend({steps:et.array()});var by="x-momentic-cli-version",vy="x-momentic-cli-type",nO="x-momentic-main-branch-name",oO="x-momentic-branch-name",iO="x-momentic-commit-timestamp",aO="x-momentic-last-commit-on-main",sO="x-momentic-last-commit-on-main-timestamp",lO="x-momentic-merged-branch-name",z3=b.object({error:b.boolean(),reason:b.string(),message:b.string()}),H3=Vt.merge(bp),Ry=Tl,G3=Vt.merge(bp);var V3=Vt.merge(dS).extend({useConsensus:b.boolean().optional(),attemptNumber:b.number().optional()}),Kp=hf,j3=Vt.merge(pS),Ay=Lf,$3=Vt.merge(lS),wy=Of,W3=Vt.merge(cS),Cy=Pf,q3=Vt.merge(uS);var K3=Vt.merge(fS),Y3=b.object({testPaths:b.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:b.string().optional(),all:b.boolean().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional(),testInputMatrix:b.record(b.string(),b.string()).array().optional()}),xy=b.object({queuedTests:b.unknown().array(),runIds:b.string().uuid().array(),runGroupId:b.string().optional()});var X3=b.string().array(),J3=b.union([b.object({paths:b.string().array().describe("run specific test paths (e.g. todo-test)"),all:b.boolean().describe("run all tests").optional()}),b.object({path:b.string().describe("deprecated; present for backcompat")})]),_y=b.object({tests:b.record(b.string().describe("Test name"),b.string().describe("Test YAML")),modules:b.record(b.string().describe("Module name"),b.string().describe("Module YAML"))}),cO=b.object({test:b.string().describe("test YAML"),modules:b.record(b.string().describe("moduleId"),b.string().describe("module YAML"))}),Q3=cO.array(),Z3=b.object({testId:b.string(),schemaVersion:b.string()}).merge(Mo);function Yp(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[nO]=encodeURIComponent(e)),t&&(a[oO]=encodeURIComponent(t)),n&&(a[iO]=n.toISOString()),o&&(a[aO]=encodeURIComponent(o)),i&&(a[sO]=i.toISOString()),r.mergedGitBranchName&&(a[lO]=encodeURIComponent(r.mergedGitBranchName)),a}var eX=b.object({entries:b.array(wf),testId:b.string()}),tX=b.object({entries:b.array(DS),testId:b.string()}),rX=b.object({testId:b.string()});function Iy(r){return b.record(b.unknown()).transform(e=>{let t={};for(let[n,o]of Object.entries(e)){let i=r.safeParse(o);i.success&&(t[n]=i.data)}return t})}var Py=Iy(Cf),My=Iy(kS),Oy=b.object({trigger:b.nativeEnum(cr),status:b.nativeEnum(he),startedAt:b.coerce.date().optional(),gitCommitSha:b.string().optional(),gitCommitShaShort:b.string().optional(),gitCommitTimestamp:b.coerce.date().optional(),gitBranchName:b.string().optional(),gitOriginUrl:b.string().optional(),gitCommitMessage:b.string().optional(),gitCommitAuthorName:b.string().optional(),githubRepository:b.string().optional(),gitlabProjectPath:b.string().optional(),pipelineId:b.string().optional(),cliVersion:b.string().optional()}),nX=b.object({id:b.string()}),Ly=b.object({status:b.nativeEnum(he),updatedAt:b.coerce.date().optional(),finishedAt:b.coerce.date().optional()}),Ny=b.object({stepsSnapshot:b.array(b.record(b.unknown())).optional(),runGroupId:b.string().optional(),testId:b.string(),testName:b.string(),resolvedBaseUrl:b.string().optional(),environmentName:b.string().optional(),labels:b.array(b.string()).optional(),cliVersion:b.string().optional(),trigger:b.nativeEnum(cr),schemaVersion:b.string().optional(),section:b.nativeEnum(kl).optional(),resolvedInputs:b.record(b.string(),b.string()).optional(),quarantined:b.boolean().optional().default(!1),quarantinedReason:b.string().optional()}),oX=b.object({id:b.string()}),uO=Ep.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Dy=uO.array(),ky=Ep.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(),iX=b.object({id:b.string()}),Fy=b.object({status:b.nativeEnum(he),finishedAt:b.coerce.date().optional(),schemaVersion:b.string().optional().default("1.0.19"),results:b.record(b.string(),b.unknown()).array().optional(),beforeResults:b.record(b.string(),b.unknown()).array().optional(),afterResults:b.record(b.string(),b.unknown()).array().optional()}),aX=b.object({screenshot:b.string()}),Uy=b.object({key:b.string()}),By=b.object({orgId:b.string(),userId:b.string()}),zy=b.array(Vf),sX=b.record(b.string(),b.union([b.string(),b.boolean()])),lX=b.object({paths:b.string().array(),env:b.string().optional(),urlOverride:b.string().optional(),customHeaders:b.record(b.string(),b.string()).optional()}),Hy=b.object({suiteRunIds:b.string().array(),runGroupIds:b.string().array()}),cX=b.object({suiteRunIds:b.string().array()}),uX=oS.array(),dX=b.object({runGroupIds:b.string().array()}),dO=b.object({uploadUrl:b.string()}),pX=Vt.merge(mS),mX=Vt.merge(hS),gX=Vt.merge(gS),pO=b.object({testId:b.string().optional().default(""),testName:b.string().optional().default(""),suiteId:b.string().optional().default(""),suiteName:b.string().optional().default(""),creditsUsed:b.number().optional()}),mO=b.object({transactionId:b.string(),timestamp:b.string(),event:b.nativeEnum(Xa),properties:pO}),hX=mO.array(),Gy=Ty.omit({steps:!0}).extend({steps:b.array(b.record(b.string(),b.unknown())).describe("unparsed ResolvedStep[]")}),fX=b.object({limit:b.number().max(10).optional(),afterTime:b.number().optional()}),Vy=Zf.array(),SX=b.object({applied:b.boolean().optional(),appliedAt:b.coerce.date().optional()}),jy=dO.extend({id:b.string()}),yX=b.object({runGroupId:b.string().uuid().optional()}),$y=b.object({runGroupId:b.string().uuid()}),Wy=b.object({quarantined:b.object({testId:b.string().uuid(),quarantinedAt:b.coerce.date(),quarantinedBy:b.string().optional(),quarantinedReason:b.string()}).array()}),EX=b.object({testId:b.string().uuid(),testName:b.string().optional(),reason:b.string(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),TX=b.object({testName:b.string().optional(),reason:b.string().optional(),gitLocalUsername:b.string().optional(),gitLocalEmail:b.string().optional(),gitLocalName:b.string().optional()}),bX=Vt.merge(ES),vX=Vt.merge(TS),RX=b.object({apkToInstall:b.object({channel:b.string(),tag:b.string().optional()}).optional(),hostname:b.string().optional(),region:b.nativeEnum(Qa).optional()}),qy=b.object({name:b.string(),webRtcUrl:b.string(),adbUrl:b.string(),token:b.string(),apkDownloadUrl:b.string().optional(),region:b.string().optional()}),AX=b.object({channel:b.string(),tag:b.string(),md5:b.string()}),Ky=b.object({id:b.string(),uploadUrl:b.string().optional(),downloadUrl:b.string(),md5:b.string().optional()}),Yy=b.object({assets:b.array(b.object({channel:b.string(),tag:b.string(),md5:b.string(),createdAt:b.number().describe("Unix timestamp in milliseconds")}))});import{z as J}from"zod";var gO=3,xX=J.object({localTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()}).or(J.object({cloudTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()})),Xy=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(Xy||{});var Xp=J.object({name:J.string(),description:J.string().nullish(),effect:J.nativeEnum(Xy),labels:J.array(J.string()),githubRepository:J.string().nullish(),gitlabProjectPath:J.string().nullish(),gitBranchName:J.string().nullish()}),hO=J.object({type:J.literal("LAST_N_RUNS"),lastN:J.number().min(gO).max(10)}),fO=J.object({type:J.literal("LAST_N_HOURS"),lastN:J.number().min(1).max(24)}),SO=J.object({type:J.literal("LAST_N_DAYS"),lastN:J.number().min(1).max(7)}),Jp=J.discriminatedUnion("type",[hO,fO,SO]),yO=J.object({flakeRateThreshold:J.number().min(1).max(100),evaluationWindow:Jp}),EO=Xp.extend({type:J.literal("FLAKE_RATE"),config:yO}),TO=J.object({passRateThreshold:J.number().min(1).max(100),evaluationWindow:Jp}),bO=Xp.extend({type:J.literal("PASS_RATE"),config:TO}),vO=J.object({failureCountThreshold:J.number().min(0),evaluationWindow:Jp}),RO=Xp.extend({type:J.literal("FAILURE_COUNT"),config:vO}),_X=J.discriminatedUnion("type",[EO,bO,RO]);import{z as at}from"zod";var MX=at.object({repositoriesIndexed:at.boolean(),indexingInProgress:at.boolean(),indexesOutdated:at.boolean()}),Jy=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(Jy||{}),Qy=(l=>(l.Success="success",l.Failure="failure",l.Neutral="neutral",l.Cancelled="cancelled",l.Skipped="skipped",l.TimedOut="timed_out",l.ActionRequired="action_required",l))(Qy||{}),OX=at.object({name:at.string(),status:at.nativeEnum(Jy),conclusion:at.nativeEnum(Qy).nullable()}),ss=at.object({sha:at.string(),message:at.string(),author:at.object({name:at.string().optional(),email:at.string().optional(),date:at.coerce.date().optional()}),committer:at.object({name:at.string().optional(),email:at.string().optional(),date:at.coerce.date().optional()})}),Qp=at.object({mergedBranch:at.string().optional()});import{z as $e}from"zod";var Zy=$e.object({orgId:$e.string(),cacheKeys:$e.string().array()}),DX=$e.object({keyParams:Zy,clientMetadata:$e.string(),lockAcquisitionTimeoutMs:$e.number().optional()}),eE=$e.object({acquired:$e.boolean(),acquiredByMetadata:$e.string(),keyPrefix:$e.string()}),kX=$e.object({keyPrefix:$e.string(),result:$e.string(),ttlMs:$e.number()}),FX=$e.union([$e.object({keyPrefix:$e.string()}),Zy]),AO=$e.object({remainingTtlMs:$e.number(),value:$e.string().nullish()}),UX=$e.object({results:$e.record($e.string(),AO),activeLocks:$e.string().array()}),tE=0,rE=5*60*1e3;var GX=90*24*60*60*1e3,VX=7*24*60*60*1e3;import{z as nE}from"zod";var WX=nE.object({quarantineNotifications:nE.string().nullish()});import{z as vt}from"zod";var wO=vt.object({version:vt.string(),json:vt.record(vt.unknown()),hash:vt.string()}),oE=vt.record(vt.unknown()),XX=vt.object({newSvgs:vt.array(wO),metadata:oE.optional()}),CO=vt.object({version:vt.string(),json:vt.record(vt.unknown()).nullish(),hash:vt.string(),description:vt.string().nullish(),metadata:oE.nullish()}),iE=vt.record(vt.string().describe("icon hash"),CO);import{z as Xe}from"zod";var Zp=Xe.object({assertion:Xe.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),xO=Xe.object({instruction:Xe.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:Zp.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.")}),aE=xO.extend({subSteps:Xe.lazy(()=>aE.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),sE=Xe.object({name:Xe.string().describe("Short name describing the test plan"),description:Xe.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),lE=sE.extend({id:Xe.string(),createdAt:Xe.coerce.date(),updatedAt:Xe.coerce.date(),updatedBy:Xe.string(),createdBy:Xe.string(),test:Xe.object({id:Xe.string(),name:Xe.string()}).nullish().transform(r=>r??void 0)}),e4=lE.extend({testGenRuns:Xe.tuple([]).or(Xe.tuple([Xe.object({id:Xe.string(),startedAt:Xe.coerce.date(),status:Xe.nativeEnum(he)})]))}),cE=Xe.object({preConditions:Zp.array().nullish().transform(r=>r??[]),postConditions:Zp.array().nullish().transform(r=>r??[]),steps:aE.array().nullish().transform(r=>r??[])}),t4=lE.extend({plan:cE.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),_O=sE.extend({plan:cE.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),r4=_O.array().nullish().transform(r=>r??[]);import{validator as IO}from"@exodus/schemasafe";function uE(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{IO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var dE=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as E4}from"zod";var nc=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};var em=class{getParentStepIdChain(){return[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(){}async startSubSteps(){return new ls}},ls=class{getParentStepIdChain(){return[]}async getScreenshot(){}async getHtmlSnapshot(){}async startStep(){return new em}};import{z as X}from"zod";var PO=X.object({step:et,status:X.nativeEnum(Ae),startedAt:X.coerce.date(),finishedAt:X.coerce.date().optional(),healMetadata:X.object({healType:X.nativeEnum(ja).or(X.literal("AI")),healedAt:X.coerce.date()}).optional(),beforeSnapshotId:X.string().uuid().optional(),afterSnapshotId:X.string().uuid().optional(),message:X.string().optional()}),F4=PO.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),pE="1.0.0",tm=Fy.extend({id:X.string().uuid().optional(),startedAt:X.coerce.date(),runAttemptSchemaVersion:X.string().optional(),schemaVersion:X.string().optional().default("1.0.19"),results:X.record(X.string(),X.unknown()).array().optional(),beforeResults:X.record(X.string(),X.unknown()).array().optional(),afterResults:X.record(X.string(),X.unknown()).array().optional()}),mE=tm.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),U4=tm.merge(Wa),B4=mE.merge(Wa),gE=X.object({results:X.array(jl),beforeResults:X.array(jl).optional(),afterResults:X.array(jl).optional()}),z4=tm.merge(gE),H4=mE.merge(gE),MO=ky.merge(Ny).extend({executionType:X.nativeEnum(Pi).optional().default("WEB"),testId:X.string().uuid(),testDescription:X.string().optional(),runGroupId:X.string().uuid(),status:X.nativeEnum(he),startedAt:X.coerce.date(),attempts:X.number(),failureRecoveryDetails:X.record(X.unknown()).optional()}),G4=MO.extend({finishedAt:X.coerce.date().optional().transform(r=>r??new Date)}),OO=Oy.merge(Ly).extend({id:X.string().uuid().optional(),startedAt:X.coerce.date(),cliVersion:X.string(),labels:X.string().array().optional().default([])}),cs=OO.extend({updatedAt:X.coerce.date().optional().transform(r=>r??new Date),finishedAt:X.coerce.date().optional().transform(r=>r??new Date)});function hE(r){try{return LO(r)&&NO(r).isDirectory()}catch(e){return T.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import{confirm as KO,input as YO}from"@inquirer/prompts";import{existsSync as XO,mkdirSync as JO,statSync as QO}from"fs";import{dirname as ZO}from"path";import Kr,{supportsColor as WO}from"chalk";import{Console as fE}from"console";import{format as us}from"util";var rm=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},oc=class r extends fE{_buffer=[];_groupDepth=0;Console=fE;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new rm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
12
12
  `).slice(o).filter(Boolean).join(`
13
- `);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",ss(e,...t))}error(e,...t){this._log("error",ss(e,...t))}info(e,...t){this._log("info",ss(e,...t))}log(e,...t){this._log("log",ss(e,...t))}warn(e,...t){this._log("warn",ss(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function mE(r){let e=globalThis.console,t=new ec;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
13
+ `);return e.push({message:n,origin:a,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",us(e,...t))}error(e,...t){this._log("error",us(e,...t))}info(e,...t){this._log("info",us(e,...t))}log(e,...t){this._log("log",us(e,...t))}warn(e,...t){this._log("warn",us(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function SE(r){let e=globalThis.console,t=new oc;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
14
14
  `);process.stderr.write(`${o}
15
- `),globalThis.console=e}}var it=" ".repeat(6);function gE(r,e="",t=!1){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-e.length,20),i=r.split(`
15
+ `),globalThis.console=e}}var st=" ".repeat(6);function yE(r,e="",t=!1){let n=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(n-e.length,20),i=r.split(`
16
16
  `),a=[];for(let l of i)if(t){let c=l;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=l.split(" "),s="";for(let u of c){if(!s.length){s=u;continue}let d=`${s} ${u}`;d.length<=o?s=d:(a.push(e+s),s=u)}a.push(e+s)}return a.join(`
17
- `)}import bO from"os";import hE,{multistream as vO}from"pino";import RO from"pino-pretty";import AO from"pino-std-serializers";var ls=new Map,wO=!0,fE="Log throttle exceeded",CO=100,xO=5e3,em=class r{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:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??bO.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=wO?hE(a):hE(a,vO([{stream:RO({colorize:!0})}]))}getLevel(){return Xl[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}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 t=await fetch(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:ts(e)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===fE)return!0;let t=Date.now();return t-this.lastWindowStart>xO&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,fE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<CO?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(rs[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=AO.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:py({message:n||"",...i})};this.buffer.push(l),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,ls.set("app",this),ls.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=Xl[e]):(this.minLevelValue=rs[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},tc=({app:r,hostname:e,disableConsoleLogs:t})=>(ls.has(r)||ls.set(r,new em({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ls.get(r));import{hostname as _O}from"os";var Q=tc({app:"cli",hostname:_O(),disableConsoleLogs:!0}).child({cliVersion:"2.17.5"});var PO=5;async function nc({getResults:r,checkDone:e,name:t,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>PO&&(E.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{a=await r(),i=0}catch(s){i++,Q.warn({err:s},"Failed to fetch run status, retrying..."),E.warn({err:s},"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(s=>setTimeout(s,c))}E.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function Gi({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return mE(()=>{if(c.forEach(u=>{E.log(""),o(u)}),c.length){E.log("");let u=c.length===1?"":"s";E.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{E.dimmed(n(d))})}if(s.length){E.log("");let u=s.length===1?"":"s";E.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{E.dimmed(n(d))})}if(a.length){E.log("");let u=a.length===1?"":"s";E.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{E.dimmed(n(d))})}if(l.length){E.log("");let u=l.length===1?"":"s";E.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{E.dimmed(n(d))})}if(i.length){E.log("");let u=i.length===1?"":"s";E.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{E.dimmed(n(d))})}E.log(""),E.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var oc=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=Rl[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Pi[r.failureReason],o=r.failureDetails.classification?.rootCause;if(E.error(e),o){E.log(`${it}- Error type: ${Kr.dim(t)}`);let i="- Root cause analysis:",a=gE(`${i} ${o}`,`${it} `,!1),l=a.indexOf(":");E.log(`${it}${i} ${Kr.dim(a.slice(l+1))}`)}else E.log(`${it}Reason: ${Kr.red(t)}`),E.log(`${it}Description: ${Kr.red(n)}`)},cs=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Kr.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Kr.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Kr.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Kr.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Kr.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Kr.bgMagenta.white("RUNNING"),a=0):(E.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),IO||(i=`${i}`),E.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var FO=!1,yE=(()=>{try{return DO("/.dockerenv"),!0}catch{return!1}})();async function Nt(r,e){return Pa||FO||yE?!0:(E.flush(),Q.flush(),await new Promise(n=>setTimeout(n,500)),await MO({message:r}))}async function tm(r){let e=kO(r);return dE(e)?LO(r)?Nt(`File '${SE(r)}' already exists. Overwrite existing content?`,!0):!0:await Nt(`Directory '${SE(e)}' doesn't exist. Create it now?`,!0)?(NO(e,{recursive:!0}),!0):!1}function SE(r){return r.replace(/(\s+)/g,"\\$1")}async function EE(r,e){return Pa||yE?e:(await OO({message:r,default:e})).trim()||e}import UO from"fs";import{tmpdir as BO}from"os";import zO from"path";import{registry as us}from"playwright-core/lib/server";import TE from"proper-lockfile";var bE=zO.join(BO(),"momenticBrowserInstallation");var rm=["chrome","chromium","chrome-for-testing"],HO={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},vE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function RE(r){let e=vE[HO[r]??""]??"",t=us.findExecutable(e);return!t||t.installType==="none"?!1:nm(t)}function nm(r){let e=r.executablePath();return UO.existsSync(e)}function GO(r,e){let t=vE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=us.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&nm(n)))return n}async function VO({browser:r,force:e}){let t=GO(r,e);if(!t){E.info(`Browser '${r}' is already installed, skipping...`);return}E.info(`Installing browser '${r}'...`);try{await us.installDeps([t],!1),await us.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){E.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=us.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!nm(o);)E.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function AE({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?rm:Array.from(new Set(r));try{await TE.lock(bE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){E.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 VO({browser:i,force:e})}catch(a){o=a,E.error(`Failed to install the ${i} browser: ${a}`)}}finally{await TE.unlock(bE,{realpath:!1})}if(o)throw o}import{randomUUID as lG}from"crypto";import jC from"body-parser";import QH from"cors";import ZH from"dedent";import{Router as ML}from"express";import jt from"fs";import{globSync as OL}from"glob";import Et from"path";import Em from"fs";import{z as am}from"zod";var z="v1",om="cli",ds="2.17.5";var Kn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var wE=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function H(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(wE(d));l=()=>s(wE(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new Kn(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}var ic=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,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 jO=9e4,$O=3,WO=1500,qO=15e3,Ir=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function KO(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var im=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ds&&(e[Sy]=ds),om&&(e[yy]=om),e}async sendRequest(e,t){let{retries:n=$O,requestTimeoutMs:o=jO,initialRetryDelayMs:i=WO,maxRetryDelayMs:a=qO}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof Ir&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new Kn),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(g=>setTimeout(g,m))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await KO(s);throw new Ir(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},Rt=class extends im{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends Rt{constructor(e){super(e)}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});return Dy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${z}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return My.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${z}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Ay.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${z}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${z}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Cy.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${z}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${z}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return xy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${z}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ry.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${z}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ny.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${z}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ky.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${z}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Xy.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(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${z}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Fy.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${z}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return Jf.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${z}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${z}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Uy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${z}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return By.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${z}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return zy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${z}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Hy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return tE.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${z}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return os.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${z}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return os.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${z}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Yp.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),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 os.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${z}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return os.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${z}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Yp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${z}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return am.record(am.string(),am.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${z}/quarantine`,{method:"GET"});return Gy.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${z}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${z}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${z}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Vy.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${z}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${z}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return jy.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 $y.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${z}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function sm(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(E.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),E.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return E.debug("Got auth info from API"),n}var ac=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Vi=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}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,t){return this.client.saveNewIcons(e,t)}};import{Faker as YO,en as XO}from"@faker-js/faker";var ji="v1",Yr=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 YO({locale:XO}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${ji}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Ir?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${ji}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${ji}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${ji}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${ji}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${ji}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ir?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as JO}from"zod";var Yn=class extends Rt{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return nS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${z}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ds,...e},signal:t.abortSignal});return rS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${z}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return JO.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${z}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return by.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${z}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return $p.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ty.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${z}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return $p.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${z}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Ey.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${z}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${z}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return sp.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${z}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return vy.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${z}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return ip.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${z}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Nf.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${z}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return up.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${z}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return mS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${z}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Mf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Lf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${z}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Of.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${z}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return lf.parse(n)}};var Xn=class extends Rt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${z}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return cf.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function CE(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var sc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await CE(n,"application/zip",t);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}};import{diff as ME}from"deep-object-diff";function ps(r){let e={parentChain:[]};return lc(r,e),e}function lc(r,e){let{onPresetAction:t,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=r;for(let a of r.steps)switch(a.type){case"PRESET_ACTION":if(t(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(t(c.assertion,e)&&i||lc({...r,steps:c.steps},e)&&i)return!0;if(lc({...r,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),lc({...r,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 xE(r,e,t,n){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!QO([r],t,i).result}function QO(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return ps({steps:r,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function _E(r,e){e(r);for(let t in r){let n=r[t];n&&(Array.isArray(n)?uc(n,e):typeof n=="object"&&_E(n,e))}}function uc(r,e){for(let t of r)t&&(Array.isArray(t)?uc(t,e):typeof t=="object"&&_E(t,e))}function lm(r,e){if(r.length>e.length)return lm(e,r);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function cc(r){for(let e of r.results)switch(e.type){case"PRESET_ACTION":r.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":r.onSimpleStepContainer?.(e),cc({...r,results:e.results});break;case"CONDITIONAL":r.onConditional?.(e),e.assertionResult&&r.onPresetAction(e.assertionResult),cc({...r,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}import{cloneDeep as IE}from"lodash-es";import{v4 as cm}from"uuid";async function ke(r){let e=new Map,t=new Set,n=IE(r.stepLists.steps),o=await Ho({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let a of["beforeSteps","afterSteps"]){let l=IE(r.stepLists[a]);if(!l)continue;let c=await Ho({...r,steps:l,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...c.cachesToSave),i.moduleUpdates.push(...c.moduleUpdates),i.stepsToSave[a]=c.stepsToSave}return i}async function Ho({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(delete u.index,delete u.aiSuggested,u.id=c?cm():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?cm():p.id,"cache"in p&&p.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(um({id:p.id,orgId:n.orgId,testId:n.testId,value:mn.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,s.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?cm():u.id,m=u.moduleId;a.has(m)?m=a.get(m):l!==void 0&&(m=await l(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await Ho({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(f),s.cachesToSave=s.cachesToSave.concat(g),t.has(m)||(t.add(m),s.moduleUpdates.push({...Wt.parse(u),steps:Oe.array().parse(h),moduleId:m}));let y=xr.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});s.stepsToSave.push(y);break}case"AI_ACTION":{if(!u.steps){s.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await Ho({...e,steps:u.steps});try{u.steps=Zt.array().parse(p)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}s.stepsToSave.push(u),s.cachesToSave=s.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{s.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let g of u.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:y}=await Ho({...e,steps:g.steps});p.push({...g,steps:h}),s.cachesToSave=s.cachesToSave.concat(f),s.moduleUpdates=s.moduleUpdates.concat(y)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await Ho({...e,steps:u.elseSteps});m.elseSteps=g,s.cachesToSave=s.cachesToSave.concat(h),s.moduleUpdates=s.moduleUpdates.concat(f)}s.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:g}=await Ho({...e,steps:u.steps}),h={...u,steps:p};s.moduleUpdates=s.moduleUpdates.concat(g),s.stepsToSave.push(h),s.cachesToSave=s.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 s}function $i({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let g=mn.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){l.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=ZO(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_ASSERTION")return;l.push(g[0])}};for(let p of r)switch(p.type){case"RESOLVED_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=$i({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(s+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=$i({...t,steps:p.steps,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!Sl.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;s++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){s++,d(m.assertion.command,i),s+=m.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=$i({...t,steps:m.steps,topLevel:!1});a.push(...g),l.push(...h),c.push(...f)}if(p.elseSteps){s+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=$i({...t,steps:p.elseSteps,topLevel:!1});a.push(...m),l.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&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function OE(r,e){return e?`${e}:${r}`:r}function ZO(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function um(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
18
- ${JSON.stringify(t)}`);let n=[];return n.push({key:OE(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function LE(r){let e=new Set;return uc(r,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let n=t.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function dc({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&bf(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function pc(r,e){r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}}}async function mc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=ME(o,i);if(Object.keys(a).length!==0){r.debug("Updating step caches post-success");try{let{cachesToSave:l}=await ke({stepLists:i,cacheCreationParams:{testId:n,orgId:t}});await e.saveStepCacheEntries({logger:r,testId:n,entries:l})}catch(l){r.error({err:l},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function gc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=ME(o,i);if(Object.keys(a).length===0)return;r.debug({changes:a},"Updating memory post-run failure");let l={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=eL({steps:d});for(let[m,g]of Object.entries(p))l[m]=g}let{cachesToSave:c}=await ke({stepLists:i,cacheCreationParams:{testId:n,orgId:t}}),s=tL({newEntries:c,originalCachesMap:l,logger:r});if(s.length){r.debug({prunedCaches:s},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:r,testId:n,entries:c})}catch(u){r.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}function eL({steps:r}){let e={};return ps({steps:r,onPresetAction:(t,n)=>{let o=t.command;if(!("cache"in o)||!o.cache)return;let i=n.parentChain.filter(c=>c.type==="RESOLVED_MODULE").map(c=>c.id).join(":"),a=OE(t.id,i),l=mn.parse(o);e[a]=l},onSimpleStepContainer:(t,n)=>{},onConditional:(t,n)=>{}}),e}function tL({newEntries:r,originalCachesMap:e,logger:t}){let n=[];for(let o of r){let i=e[o.key];if(!i||!i.cache||o.value.type!==i.type)continue;let a=o.value.cache;if(o.value={...i},!a){n.push(o);continue}if("memory"in a&&a.memory)t.debug({cacheKey:o.key,newCacheMemory:a.memory,originalCache:i},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:a.memory};else if("target"in a&&a.target.memory){let l=Qt.parse(o.value.cache);if(!l)continue;t.debug({cacheKey:o.key,newCacheMemory:a.target.memory,originalCache:i},"Overwriting target cache memory"),l.target.memory=a.target.memory,o.value.cache=l}else if("fromTarget"in a||"toTarget"in a){let l=Wd.optional().parse(o.value.cache);if(!l)continue;l.fromTarget&&a.fromTarget&&(l.fromTarget.memory=a.fromTarget.memory),l.toTarget&&a.toTarget&&(l.toTarget.memory=a.toTarget.memory),t.debug({cacheKey:o.key,fromTargetMemory:a.fromTarget?.memory,toTargetMemory:a.toTarget?.memory,originalCache:i},"Overwriting drag cache memory"),o.value.cache=l}n.push(o)}return n}function Je(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var gr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},hr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},dm={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},pm={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function rL(r){switch(r.type){case"ELEMENT_CONTENT":return`content ${r.negated?hr[r.operation]:gr[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?hr[r.operation]:gr[r.operation];return r.operation==="EXISTS"?`attribute '${r.attr}' ${t}`:`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_NAME":{let t=r.negated?hr[r.operation]:gr[r.operation];return r.operation==="EXISTS"?`tag name ${t}`:`tag name ${t} '${r.value}'`}case"ELEMENT_STYLE":{let t=r.negated?hr[r.operation]:gr[r.operation];return r.operation==="EXISTS"?`style property '${r.property}' ${t}`:`style property '${r.property}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?pm[r.condition]:dm[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var j9={CONTENT:"The page"};function nL(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function fc(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function hc(r){let e="";return r.method&&(e=` with method ${r.method}`),`${fc(r.urlMatcher)}${e}`}function oL(r){switch(r.type){case"CONTENT":return`${r.negated?hr.CONTAINS:gr.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function Tn(r,e=!0){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${e?Je(r.url,30):r.url}`;case"DIALOG":return`Automatically ${r.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 ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${It(r.target)}`;let n="";return r.target?.elementDescriptor.length?n=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${It(r.target)}`;case"BLUR":return`Focus ${It(r.target)}`;case"DRAG":return`Drag ${It(r.fromTarget)} onto ${It(r.toTarget)}`;case"MOUSE_DRAG":return r.target?.type==="description"&&r.target.elementDescriptor?`Click and drag ${It(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let n="";return r.target?.type==="coordinates"?n=` in element at coordinates: ${It(r.target)}`:r.target?.elementDescriptor.length?n=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${n||""}`}case"HOVER":{let n="";return r.target.type==="coordinates"?n=` over coordinates: ${It(r.target)}`:r.target.elementDescriptor.length>0?n=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${r.value}`;case"KEY_DOWN":return`Hold down ${r.value} on the keyboard`;case"KEY_UP":return`Release ${r.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=nL(r.choice);return r.target.type==="coordinates"?n=` from element at coordinates: ${It(r.target)}`:r.target.elementDescriptor.length>0?n=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?Je(r.code,30):r.code}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${It(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return r.fileSource.type==="URL"?`Upload file: ${r.fileSource.url}`:`Upload file: ${r.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${It(r.target)} ${rL(r.assertion)}`;case"PAGE_CHECK":return`Check the page ${oL(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${fc(r.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return r.requestMatcher?`Register a listener for network requests that ${hc(r.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return r.key?`Wait for the listener ${r.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return r.requestMatcher?`Start recording requests that match ${hc(r.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return r.key?`Get the requests that were recorded for ${r.key}`:"Get the requests that were recorded";case"SET_HEADER":return r.name?r.requestMatcher?`Set a ${r.name} header for requests that match ${hc(r.requestMatcher)}`:`Set a ${r.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return r.requestMatcher?`Mock requests that ${hc(r.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return r.key?`Remove the mock with key ${r.key}`:"Remove all route mocks";case"OFFLINE_MODE":return r.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"})(r)}}function NE(r){let e=[];for(let t of r){t.sort((a,l)=>a.timestamp-l.timestamp);let n=[],o,i=1;for(let a of t)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 K9}from"lodash-es";import{v4 as eZ}from"uuid";import{cloneDeep as iL}from"lodash-es";import HE from"truncate-json";import{v4 as DE}from"uuid";import{cloneDeep as oZ,unset as iZ}from"lodash-es";function Jn(r){switch(r.type){case"AI_ACTION":return`AI action: ${Je(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Je(r.text,100)}`;case"PRESET_ACTION":return Tn(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${r.description?`with goal: ${Je(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function Go(r,e){return r.split(`
17
+ `)}import kO from"fetch-retry";import FO from"os";import EE,{multistream as UO}from"pino";import BO from"pino-pretty";import zO from"pino-std-serializers";var ds=new Map,HO=!0,TE="Log throttle exceeded",GO=100,VO=5e3,jO=kO(global.fetch,{retries:2,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),nm=class r{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:t,disableConsoleLogs:n,flushIntervalMs:o,maxBatchSize:i}){this.hostname=t??FO.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=HO?EE(a):EE(a,UO([{stream:BO({colorize:!0})}]))}getLevel(){return ec[this.minLevelValue]}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}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 t=await jO(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:os(e)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch(t){this.consoleLogger.warn({err:t},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===TE)return!0;let t=Date.now();return t-this.lastWindowStart>VO&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,TE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<GO?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,t,n,...o){try{this.logHelper(e,t,n,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,t,n,...o){if(is[e]<this.minLevelValue||!this.shouldAllowLog(n))return;typeof t=="string"&&!n&&(t={message:t}),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error&&(t.err=zO.err(t.err));let i={...this.bindingAttributes,...t&&typeof t=="object"?t:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,n,...o);let l={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:fy({message:n||"",...i})};this.buffer.push(l),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,ds.set("app",this),ds.delete(t)}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=ec[e]):(this.minLevelValue=is[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ic=({app:r,hostname:e,disableConsoleLogs:t})=>(ds.has(r)||ds.set(r,new nm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ds.get(r));import{hostname as $O}from"os";var Q=ic({app:"cli",hostname:$O(),disableConsoleLogs:!0}).child({cliVersion:"2.17.7"});var qO=5;async function sc({getResults:r,checkDone:e,name:t,timeoutMs:n=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<n;){let a;i>qO&&(T.error(`Failed to fetch ${t} status too many times.`),process.exit(1));try{a=await r(),i=0}catch(s){i++,Q.warn({err:s},"Failed to fetch run status, retrying..."),T.warn({err:s},"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(s=>setTimeout(s,c))}T.error(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function Hi({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let i=r.filter(u=>u.status==="PASSED"&&u.quarantined),a=r.filter(u=>u.status==="PASSED"&&!u.quarantined),l=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),s=r.filter(u=>u.status==="CANCELLED");return SE(()=>{if(c.forEach(u=>{T.log(""),o(u)}),c.length){T.log("");let u=c.length===1?"":"s";T.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{T.dimmed(n(d))})}if(s.length){T.log("");let u=s.length===1?"":"s";T.warn(`${s.length} ${t}${u} cancelled:`),s.forEach(d=>{T.dimmed(n(d))})}if(a.length){T.log("");let u=a.length===1?"":"s";T.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{T.dimmed(n(d))})}if(l.length){T.log("");let u=l.length===1?"":"s";T.warn(`${l.length} quarantined ${t}${u} failed:`),l.forEach(d=>{T.dimmed(n(d))})}if(i.length){T.log("");let u=i.length===1?"":"s";T.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{T.dimmed(n(d))})}T.log(""),T.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:l.length,failed:c.length,cancelled:s.length}}var lc=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=xl[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Ii[r.failureReason],o=r.failureDetails.classification?.rootCause;if(T.error(e),o){T.log(`${st}- Error type: ${Kr.dim(t)}`);let i="- Root cause analysis:",a=yE(`${i} ${o}`,`${st} `,!1),l=a.indexOf(":");T.log(`${st}${i} ${Kr.dim(a.slice(l+1))}`)}else T.log(`${st}Reason: ${Kr.red(t)}`),T.log(`${st}Description: ${Kr.red(n)}`)},ps=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Kr.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Kr.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Kr.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Kr.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Kr.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Kr.bgMagenta.white("RUNNING"),a=0):(T.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),WO||(i=`${i}`),T.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};var eL=!1,vE=(()=>{try{return QO("/.dockerenv"),!0}catch{return!1}})();async function Nt(r,e){return La||eL||vE?!0:(T.flush(),Q.flush(),await new Promise(n=>setTimeout(n,500)),await KO({message:r}))}async function om(r){let e=ZO(r);return hE(e)?XO(r)?Nt(`File '${bE(r)}' already exists. Overwrite existing content?`,!0):!0:await Nt(`Directory '${bE(e)}' doesn't exist. Create it now?`,!0)?(JO(e,{recursive:!0}),!0):!1}function bE(r){return r.replace(/(\s+)/g,"\\$1")}async function RE(r,e){return La||vE?e:(await YO({message:r,default:e})).trim()||e}import tL from"fs";import{tmpdir as rL}from"os";import nL from"path";import{registry as ms}from"playwright-core/lib/server";import AE from"proper-lockfile";var wE=nL.join(rL(),"momenticBrowserInstallation");var im=["chrome","chromium","chrome-for-testing"],oL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},CE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function xE(r){let e=CE[oL[r]??""]??"",t=ms.findExecutable(e);return!t||t.installType==="none"?!1:am(t)}function am(r){let e=r.executablePath();return tL.existsSync(e)}function iL(r,e){let t=CE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=ms.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&am(n)))return n}async function aL({browser:r,force:e}){let t=iL(r,e);if(!t){T.info(`Browser '${r}' is already installed, skipping...`);return}T.info(`Installing browser '${r}'...`);try{await ms.installDeps([t],!1),await ms.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){T.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ms.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!am(o);)T.info("Waiting for browser to finish installing..."),await new Promise(l=>setTimeout(l,5e3))}else throw n}}async function _E({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?im:Array.from(new Set(r));try{await AE.lock(wE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){T.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 aL({browser:i,force:e})}catch(a){o=a,T.error(`Failed to install the ${i} browser: ${a}`)}}finally{await AE.unlock(wE,{realpath:!1})}if(o)throw o}import{randomUUID as RG}from"crypto";import ox from"body-parser";import m1 from"cors";import g1 from"dedent";import{Router as KL}from"express";import jt from"fs";import{globSync as YL}from"glob";import yt from"path";import bm from"fs";import{z as cm}from"zod";var B="v1",sm="cli",gs="2.17.7";var qn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var IE=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function z(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,l;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((c,s)=>{if(e.signal){let{signal:d}=e;if(d.aborted)return s(IE(d));l=()=>s(IE(d)),d.addEventListener("abort",l)}let u=()=>{if(n)try{c(n())}catch(d){s(d)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let d=o instanceof Error?o:new qn(o??`Promise timed out after ${t}ms`);s(d)}};a=i.setTimeout(u,t),Promise.resolve(r).then(d=>c(d)).catch(d=>s(d))}).finally(()=>{i.clearTimeout(a),e.signal&&l&&e.signal.removeEventListener("abort",l)})}var cc=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(l=>n-l<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,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 sL=9e4,lL=3,cL=1500,uL=15e3,Pr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function dL(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var lm=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return gs&&(e[by]=gs),sm&&(e[vy]=sm),e}async sendRequest(e,t){let{retries:n=lL,requestTimeoutMs:o=sL,initialRetryDelayMs:i=cL,maxRetryDelayMs:a=uL}=t,l=n,c=n,s,u={path:e,baseUrl:this.baseUrl,method:t.method};for(;l>0;)try{return l--,await this.sendSingleRequestHelper(e,t,o)}catch(d){if(s=d,d instanceof Pr&&d.status>=400&&d.status<500)throw d;if(d instanceof Error&&d.name==="AbortError"&&(s=new qn),l===0)throw s;let p=c-l,m=Math.min(i*Math.pow(2,p-1),a);await new Promise(g=>setTimeout(g,m))}throw this.logger.warn({...u,err:s},"Got fatal error response from Momentic server"),s}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),l=()=>i.abort();t.signal&&t.signal.addEventListener("abort",l);let c={...this.getHeaders(),...t.extraHeaders};try{let s=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:c,signal:i.signal});if(!s.ok){let d=await dL(s);throw new Pr(s.status,d,`Request to ${t.method} ${e} failed with status ${s.status}: ${d}`)}let u;if(s.status===204)u={};else{let d=await s.text();try{u=JSON.parse(d)}catch{u=d}}return this.logger&&t.logResponse===!0&&u&&this.logger.debug({result:u,status:s.status,...o},"Got response from Momentic server"),u}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",l)}}},Rt=class extends lm{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Je=class extends Rt{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${B}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return By.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${B}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Dy.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${B}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return _y.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${B}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${B}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Py.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${B}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${B}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return My.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${B}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return xy.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${B}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Uy.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${B}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zy.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${B}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return eE.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${B}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${B}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${B}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Hy.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${B}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return tS.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${B}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${B}/billing/events`,{method:"POST",body:t,retries:10,requestTimeoutMs:1e4})}catch(n){e.error({err:n},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${B}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Gy.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${B}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${B}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Vy.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${B}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return jy.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${B}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return $y.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return iE.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){t.error({err:n},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,n,o){let i=new URLSearchParams;i.set("base",n),i.set("head",o);let a=await this.sendRequest(`/${B}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ss.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${B}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ss.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${B}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Qp.parse(a)}async getMergeBaseCommitFromGitlab(e,t,n){let o=new URLSearchParams;o.set("base",t),o.set("head",n);let i=encodeURIComponent(e),a=await this.sendRequest(`/${B}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ss.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${B}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return ss.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${B}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Qp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${B}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return cm.record(cm.string(),cm.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${B}/quarantine`,{method:"GET"});return Wy.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${B}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,n){await this.sendRequest(`/${B}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${B}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return qy.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${B}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:t,md5:n}){let o={channel:e,tag:t,md5:n},i=await this.sendRequest(`/${B}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Ky.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${B}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${B}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Yy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${B}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function um(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(T.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),T.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return T.debug("Got auth info from API"),n}var uc=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Gi=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}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,t){return this.client.saveNewIcons(e,t)}};import{Faker as pL,en as mL}from"@faker-js/faker";var Vi="v1",Yr=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 pL({locale:mL}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Vi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Pr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Vi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Vi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Vi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Vi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Vi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Pr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as gL}from"zod";var Kn=class extends Rt{agentConfig;constructor(e,t){super(t),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return sS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${B}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:gs,...e},signal:t.abortSignal});return aS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${B}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return gL.string().parse(t)}async getElementLocation(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${B}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return wy.parse(o)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${B}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return Kp.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return Ay.parse(o)}async getVisualAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${B}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return Kp.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${B}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Ry.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${B}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let n=await this.sendRequest(`/${B}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return up.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${B}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Cy.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${B}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return lp.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${B}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return Ff.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${B}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return mp.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${B}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return SS.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${B}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Nf.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${B}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return kf.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${B}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Df.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${B}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return df.parse(n)}};var Yn=class extends Rt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${B}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return pf.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function PE(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var dc=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await PE(n,"application/zip",t);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}};import{diff as DE}from"deep-object-diff";function hs(r){let e={parentChain:[]};return pc(r,e),e}function pc(r,e){let{onPresetAction:t,onSimpleStepContainer:n,onConditional:o,earlyStop:i}=r;for(let a of r.steps)switch(a.type){case"PRESET_ACTION":if(t(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(t(c.assertion,e)&&i||pc({...r,steps:c.steps},e)&&i)return!0;if(pc({...r,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),pc({...r,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 ME(r,e,t,n){let o=Array.from(e),i=Array.from(n);for(let l=0;l<o.length;l++){if(o[l]!==i[l])return!1;i.shift()}return!!hL([r],t,i).result}function hL(r,e,t=[]){let n,o=[],i=(a,l)=>{let c=JSON.stringify(l.parentChain.map(u=>u.id)),s=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&s?(n=a,o=l.parentChain,!0):!1};return hs({steps:r,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:n,parentChain:o}}function OE(r,e){e(r);for(let t in r){let n=r[t];n&&(Array.isArray(n)?gc(n,e):typeof n=="object"&&OE(n,e))}}function gc(r,e){for(let t of r)t&&(Array.isArray(t)?gc(t,e):typeof t=="object"&&OE(t,e))}function dm(r,e){if(r.length>e.length)return dm(e,r);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function mc(r){for(let e of r.results)switch(e.type){case"PRESET_ACTION":r.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":r.onSimpleStepContainer?.(e),mc({...r,results:e.results});break;case"CONDITIONAL":r.onConditional?.(e),e.assertionResult&&r.onPresetAction(e.assertionResult),mc({...r,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}import{cloneDeep as LE}from"lodash-es";import{v4 as pm}from"uuid";async function Fe(r){let e=new Map,t=new Set,n=LE(r.stepLists.steps),o=await zo({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let a of["beforeSteps","afterSteps"]){let l=LE(r.stepLists[a]);if(!l)continue;let c=await zo({...r,steps:l,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});i.cachesToSave.push(...c.cachesToSave),i.moduleUpdates.push(...c.moduleUpdates),i.stepsToSave[a]=c.stepsToSave}return i}async function zo({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:l,createNewCacheIds:c}=e,s={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(delete u.index,delete u.aiSuggested,u.id=c?pm():u.id,u.type){case"PRESET_ACTION":{let p=u.command;p.id=c?pm():p.id,"cache"in p&&p.cache&&(n&&(s.cachesToSave=s.cachesToSave.concat(mm({id:p.id,orgId:n.orgId,testId:n.testId,value:mn.parse(p),moduleIdParents:o,moduleStepParents:i}))),delete p.cache),p.thoughts&&delete p.thoughts,s.stepsToSave.push({...u,command:p});break}case"RESOLVED_MODULE":{let p=c?pm():u.id,m=u.moduleId;a.has(m)?m=a.get(m):l!==void 0&&(m=await l(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await zo({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,p],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});s.moduleUpdates=s.moduleUpdates.concat(f),s.cachesToSave=s.cachesToSave.concat(g),t.has(m)||(t.add(m),s.moduleUpdates.push({...Wt.parse(u),steps:Le.array().parse(h),moduleId:m}));let E=_r.parse({...u,type:"MODULE",moduleId:m,inputs:u.inputs,id:p,skipped:u.skipped,cacheConfig:u.cacheConfig,envKey:u.envKey});s.stepsToSave.push(E);break}case"AI_ACTION":{if(!u.steps){s.stepsToSave.push(u);break}let{stepsToSave:p,cachesToSave:m}=await zo({...e,steps:u.steps});try{u.steps=Zt.array().parse(p)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}s.stepsToSave.push(u),s.cachesToSave=s.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{s.stepsToSave.push(u);break}case"CONDITIONAL":{let p=[];for(let g of u.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:E}=await zo({...e,steps:g.steps});p.push({...g,steps:h}),s.cachesToSave=s.cachesToSave.concat(f),s.moduleUpdates=s.moduleUpdates.concat(E)}let m={...u,elseSteps:void 0,blocks:p};if(u.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await zo({...e,steps:u.elseSteps});m.elseSteps=g,s.cachesToSave=s.cachesToSave.concat(h),s.moduleUpdates=s.moduleUpdates.concat(f)}s.stepsToSave.push(m);break}case"SECTION":{let{stepsToSave:p,cachesToSave:m,moduleUpdates:g}=await zo({...e,steps:u.steps}),h={...u,steps:p};s.moduleUpdates=s.moduleUpdates.concat(g),s.stepsToSave.push(h),s.cachesToSave=s.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 s}function ji({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],l=[],c=[],s=0,u=(p,m)=>{try{let g=mn.parse(m.value);if(g.type!==p.type){o.warn({parsedCacheEntry:g,command:p},"Not using step cache due to type mismatch"),l.push(m.key);return}p.cache=g.cache,a.push(m.key),c.push(m.uniqueKey)}catch(g){l.push(m.key),o.error({err:g,cacheEntry:m},"Not using step cache due to parsing error")}},d=(p,m)=>{let g=fL(p.id,m),h=g.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_ASSERTION")return;l.push(g[0])}};for(let p of r)switch(p.type){case"RESOLVED_MODULE":{s+=p.steps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=ji({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(s+=p.steps?.length??0,!p.steps?.length)break;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=ji({...t,steps:p.steps,topLevel:!1});a.push(...m),l.push(...g),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!vl.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;s++,d(p.command,i);break}case"CONDITIONAL":{for(let m of p.blocks){s++,d(m.assertion.command,i),s+=m.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=ji({...t,steps:m.steps,topLevel:!1});a.push(...g),l.push(...h),c.push(...f)}if(p.elseSteps){s+=p.elseSteps.length;let{cacheKeysHit:m,cacheKeysMissed:g,uniqueKeysHit:h}=ji({...t,steps:p.elseSteps,topLevel:!1});a.push(...m),l.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&&s&&l.length>0&&o.warn({totalSteps:s,cacheKeysMissed:l,cacheKeysHit:a,uniqueKeysHit:c,cacheEntries:n.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:l,uniqueKeysHit:c}}function kE(r,e){return e?`${e}:${r}`:r}function fL(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let i=[...n.slice(o),r];t.push(i.join(":"))}return t.reverse(),t}function mm(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
18
+ ${JSON.stringify(t)}`);let n=[];return n.push({key:kE(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function FE(r){let e=new Set;return gc(r,t=>{if("type"in t&&t.type==="RESOLVED_MODULE"&&"moduleId"in t){let n=t.moduleId;typeof n=="string"&&!e.has(n)&&e.add(n)}}),e}function Ho({cmd:r,newTarget:e,key:t,logger:n}){r.type==="DRAG"?t!=="fromTarget"&&t!=="toTarget"?n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command"):r.cache={...r.cache,[t]:e}:t==="target"&&Af(r)?r.cache={...r.cache,target:e}:n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function hc(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;return JSON.stringify(n)===JSON.stringify(e)?{changed:!1}:(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e}},{changed:!0})}async function fc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=DE(o,i);if(Object.keys(a).length!==0){r.debug("Updating step caches post-success");try{let{cachesToSave:l}=await Fe({stepLists:i,cacheCreationParams:{testId:n,orgId:t}});await e.saveStepCacheEntries({logger:r,testId:n,entries:l})}catch(l){r.error({err:l},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Sc({logger:r,cacheStorage:e,orgId:t,testId:n,originalSteps:o,updatedSteps:i}){let a=DE(o,i);if(Object.keys(a).length===0)return;r.debug({changes:a},"Updating memory post-run failure");let l={};for(let u of["steps","beforeSteps","afterSteps"]){let d=o[u];if(!d||!d.length)continue;let p=SL({steps:d});for(let[m,g]of Object.entries(p))l[m]=g}let{cachesToSave:c}=await Fe({stepLists:i,cacheCreationParams:{testId:n,orgId:t}}),s=yL({newEntries:c,originalCachesMap:l,logger:r});if(s.length){r.debug({prunedCaches:s},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:r,testId:n,entries:c})}catch(u){r.error({err:u},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}function SL({steps:r}){let e={};return hs({steps:r,onPresetAction:(t,n)=>{let o=t.command;if(!("cache"in o)||!o.cache)return;let i=n.parentChain.filter(c=>c.type==="RESOLVED_MODULE").map(c=>c.id).join(":"),a=kE(t.id,i),l=mn.parse(o);e[a]=l},onSimpleStepContainer:(t,n)=>{},onConditional:(t,n)=>{}}),e}function yL({newEntries:r,originalCachesMap:e,logger:t}){let n=[];for(let o of r){let i=e[o.key];if(!i||!i.cache||o.value.type!==i.type)continue;let a=o.value.cache;if(o.value={...i},!a){n.push(o);continue}if("memory"in a&&a.memory)t.debug({cacheKey:o.key,newCacheMemory:a.memory,originalCache:i},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:a.memory};else if("target"in a&&a.target.memory){let l=Qt.parse(o.value.cache);if(!l)continue;t.debug({cacheKey:o.key,newCacheMemory:a.target.memory,originalCache:i},"Overwriting target cache memory"),l.target.memory=a.target.memory,o.value.cache=l}else if("fromTarget"in a||"toTarget"in a){let l=Yd.optional().parse(o.value.cache);if(!l)continue;l.fromTarget&&a.fromTarget&&(l.fromTarget.memory=a.fromTarget.memory),l.toTarget&&a.toTarget&&(l.toTarget.memory=a.toTarget.memory),t.debug({cacheKey:o.key,fromTargetMemory:a.fromTarget?.memory,toTargetMemory:a.toTarget?.memory,originalCache:i},"Overwriting drag cache memory"),o.value.cache=l}n.push(o)}return n}function Qe(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var mr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},gr={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},gm={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},hm={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function EL(r){switch(r.type){case"ELEMENT_CONTENT":return`content ${r.negated?gr[r.operation]:mr[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?gr[r.operation]:mr[r.operation];return r.operation==="EXISTS"?`attribute '${r.attr}' ${t}`:`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_NAME":{let t=r.negated?gr[r.operation]:mr[r.operation];return r.operation==="EXISTS"?`tag name ${t}`:`tag name ${t} '${r.value}'`}case"ELEMENT_STYLE":{let t=r.negated?gr[r.operation]:mr[r.operation];return r.operation==="EXISTS"?`style property '${r.property}' ${t}`:`style property '${r.property}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?hm[r.condition]:gm[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var aZ={CONTENT:"The page"};function TL(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function Ec(r){switch(r.type){case"SUBSTRING":return`match substring '${r.url}'`;case"REGEX":return`match regex '${r.regex}'`;case"GLOB":return`match glob '${r.glob}'`;case"DOMAIN":return`match domain '${r.domain}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function yc(r){let e="";return r.method&&(e=` with method ${r.method}`),`${Ec(r.urlMatcher)}${e}`}function bL(r){switch(r.type){case"CONTENT":return`${r.negated?gr.CONTAINS:mr.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function En(r,e=!0){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${e?Qe(r.url,30):r.url}`;case"DIALOG":return`Automatically ${r.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 ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${It(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${It(r.target)}`;let n="";return r.target?.elementDescriptor.length?n=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${It(r.target)}`;case"BLUR":return`Focus ${It(r.target)}`;case"DRAG":return`Drag ${It(r.fromTarget)} onto ${It(r.toTarget)}`;case"MOUSE_DRAG":return r.target?.type==="description"&&r.target.elementDescriptor?`Click and drag ${It(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let n="";return r.target?.type==="coordinates"?n=` in element at coordinates: ${It(r.target)}`:r.target?.elementDescriptor.length?n=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${n||""}`}case"HOVER":{let n="";return r.target.type==="coordinates"?n=` over coordinates: ${It(r.target)}`:r.target.elementDescriptor.length>0?n=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${r.value}`;case"KEY_DOWN":return`Hold down ${r.value} on the keyboard`;case"KEY_UP":return`Release ${r.value} on the keyboard`;case"SELECT_OPTION":{let n="",o=TL(r.choice);return r.target.type==="coordinates"?n=` from element at coordinates: ${It(r.target)}`:r.target.elementDescriptor.length>0?n=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?Qe(r.code,30):r.code}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${It(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return r.fileSource.type==="URL"?`Upload file: ${r.fileSource.url}`:`Upload file: ${r.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${It(r.target)} ${EL(r.assertion)}`;case"PAGE_CHECK":return`Check the page ${bL(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${Ec(r.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return r.requestMatcher?`Register a listener for network requests that ${yc(r.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return r.key?`Wait for the listener ${r.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return r.requestMatcher?`Start recording requests that match ${yc(r.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return r.key?`Get the requests that were recorded for ${r.key}`:"Get the requests that were recorded";case"SET_HEADER":return r.name?r.requestMatcher?`Set a ${r.name} header for requests that match ${yc(r.requestMatcher)}`:`Set a ${r.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return r.requestMatcher?`Mock requests that ${yc(r.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return r.key?`Remove the mock with key ${r.key}`:"Remove all route mocks";case"OFFLINE_MODE":return r.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"})(r)}}function UE(r){let e=[];for(let t of r){t.sort((a,l)=>a.timestamp-l.timestamp);let n=[],o,i=1;for(let a of t)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 uZ}from"lodash-es";import{v4 as fZ}from"uuid";import{cloneDeep as vL}from"lodash-es";import $E from"truncate-json";import{v4 as BE}from"uuid";import{cloneDeep as TZ,unset as bZ}from"lodash-es";function Xn(r){switch(r.type){case"AI_ACTION":return`AI action: ${Qe(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${Qe(r.text,100)}`;case"PRESET_ACTION":return En(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${r.description?`with goal: ${Qe(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function Go(r,e){return r.split(`
19
19
  `).map(t=>" ".repeat(e)+t).join(`
20
- `)}function mm(r){switch(r.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;return`AI action: ${r.text}
21
- ${Go(`Sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return Tn(r.command,!1);case"MODULE":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;if("moduleName"in r){let t=r.moduleName;return`Module: ${r.id} ModuleName: ${t}
20
+ `)}function fm(r){switch(r.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;return`AI action: ${r.text}
21
+ ${Go(`Sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return En(r.command,!1);case"MODULE":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;if("moduleName"in r){let t=r.moduleName;return`Module: ${r.id} ModuleName: ${t}
22
22
  ${Go(`Sub-steps: ${e}`,2)}`}return`Module: ${r.id}
23
- ${Go(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in r&&r.assertionResult&&(e.push(Go("Conditional check:",2)),e.push(Go(mm(r.assertionResult),2))),"results"in r&&Array.isArray(r.results)){let t=r.results.length,n="assertionResult"in r&&r.assertionResult?"Branch steps":"Else branch steps";e.push(Go(`${n}: ${t}`,2))}return e.join(`
23
+ ${Go(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in r&&r.assertionResult&&(e.push(Go("Conditional check:",2)),e.push(Go(fm(r.assertionResult),2))),"results"in r&&Array.isArray(r.results)){let t=r.results.length,n="assertionResult"in r&&r.assertionResult?"Branch steps":"Else branch steps";e.push(Go(`${n}: ${t}`,2))}return e.join(`
24
24
  `)}case"SECTION":{let e="results"in r&&Array.isArray(r.results)?r.results.length:0;return`Section${r.description?`with goal: ${r.description}`:""}
25
- ${Go(`Sub-steps: ${e}`,2)}`}default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}var kE=1e3,FE=3e6,aL="[FAILED]";async function UE(r,e,t){if(t){let n=await e.getScreenshot(r,t);if(n)return`data:image/jpeg;base64,${Buffer.from(n).toString("base64")}`}}function sL(r,e){let t=(()=>{switch(r.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")})(r)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${t}
26
- ${o}`:o)(mm(r))}function yc(r,e={}){let t=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:DE(),message:`Starting the ${r.replace("-"," ")} section`,startedAt:t,finishedAt:t,status:"SUCCESS",command:{id:DE(),type:"SUCCESS"},results:[]}}function Sc(r,e={}){let{index:t,includeDomState:n=!1,header:o}=e,i=sL(r,o),a;r.type==="PRESET_ACTION"&&(a=r.results?.[0]?.elementInteracted);let l=r.message!=="Successfully executed preset action."?r.message:void 0,c=i;r.status==="FAILED"&&(c=`${aL} ${c}`);let s={description:c,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),beforeUrl:r.beforeUrl,afterUrl:r.afterUrl,beforeSnapshot:r.beforeSnapshot,afterSnapshot:r.afterSnapshot,elementInteracted:a,message:l,index:t};if(r.status==="FAILED"&&n)try{let u=Qf.array().parse(r.details);for(let d of u)"pageState"in d&&(s.pageState=d.pageState)}catch{}return s}async function GE(r,e,t,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:l=0}){let c,s=[];for(let u=0;u<t.length;u++){let d=t[u],p=n?u+l:void 0;switch(d.type){case"PRESET_ACTION":{s.push(Sc(d,{index:p,includeDomState:o,header:void 0})),d.status==="FAILED"&&(c=p);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){s.push(Sc(d,{index:n?p:void 0,includeDomState:o,header:"start"})),l+=1;let{failureIndex:m,results:g}=await GE(r,e,d.results,{addIndices:n,includeDomState:o,flatten:i,maxItemsFromEnd:a,indexOffset:l+u});s.push(...g),m!==void 0&&(c=m),l+=g.length,s.push(Sc(d,{index:n?l+u:void 0,includeDomState:o,header:"end"})),l+=1}else s.push(Sc(d,{index:n?l+u:void 0,includeDomState:o,header:void 0}));break}default:return(g=>{throw new Error("You missed a case in the switch above")})(d)}}return{results:s,failureIndex:c}}async function Wi(r,e,t,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,flatten:l=!0,maxItemsFromEnd:c=20}){let s=await GE(r,e,t,{addIndices:o,includeDomState:a,flatten:l,maxItemsFromEnd:c,indexOffset:0}),{results:u}=s,{failureIndex:d}=s;d!==void 0&&u.length>0&&(u=u.slice(0,d+1));let p=[],m=0;if(c!==void 0&&u.length>c&&(m=u.length-c),d!==void 0&&d<u.length-1&&r.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:u.length,lastIndex:u.length-1,isLastIndex:d===u.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let g=m;g<u.length;g++){let h=u[g],f={description:h.description,startedAt:h.startedAt,finishedAt:h.finishedAt,beforeUrl:h.beforeUrl,afterUrl:h.afterUrl,elementInteracted:h.elementInteracted,message:h.message,pageState:h.pageState,index:h.index},y,S;(n===void 0||n>0&&g>=u.length-n)&&(h.afterSnapshot&&(S=await UE(r,e,h.afterSnapshot)),i&&h.beforeSnapshot&&(y=await UE(r,e,h.beforeSnapshot))),f.beforeScreenshot=y,f.afterScreenshot=S,p.push(f)}return{results:p,failureIndex:d!==void 0?d-m:void 0}}function hm({json:r,keysToRedact:e,maxJsonStringSize:t}){try{if(!r)return r;if(typeof r=="string")return Je(r,t??2e4);if(typeof r=="object"){let{jsonString:n}=HE(JSON.stringify(r,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),t??2e4);return JSON.parse(n)}return r}catch{return r}}function gm(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=HE(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":BE(n);break;case"CONDITIONAL":n.assertionResult&&BE(n.assertionResult),gm(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{gm(n.results,e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}}function BE(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function zE(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function Ec(r,e){let t=iL(r);if(gm(t,e),t.length>kE)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,kE);let n=zE(t,e);if(n.length>FE)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>FE;)t.pop(),n=zE(t,e);try{return mt.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 CZ}from"lodash-es";var lL=/^(?!.*\S+\s+\S+).*$/,cL=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,uL=/style="([^"]*)/g,dL=/data-[\w-]+/g,pL=r=>{switch(r.type){case"AI_ASSERTION":return{type:r.type,assertion:r.assertion};case"DRAG":if(r.fromTarget.type==="description")return{type:r.type,description:r.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(r.target?.type==="description")return{type:r.type,description:r.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function VE(r){let e=pL(r),t=e.type==="AI_ASSERTION"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:lL.test(t)&&cL.test(t)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:uL.test(t)?{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"}:dL.test(t)?{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(t)?{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"}}function jE(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import{cloneDeep as ST}from"lodash-es";import SL from"diff-lines";import bc,{gte as yL}from"semver";var $E={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var WE={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 r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var mL=["target","fromTarget","toTarget"];function qE(r){for(let e of mL){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var KE={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return qE(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])qE(n);return e}default:return e}})};import{v4 as gL}from"uuid";var YE={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=gL()),e;default:return e}})};import{v4 as XE}from"uuid";var JE={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??XE(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??XE()}})),delete e.commands),e;default:return e}})};var QE={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 r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as hL}from"uuid";var ZE={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 r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=hL()),e))};import{v4 as eT}from"uuid";var tT={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 r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=eT())}return e.id=eT(),e})};var rT={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 r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as fL}from"uuid";var nT={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=fL()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var oT={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var iT={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&aT(t),e})};function aT(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){aT(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var sT={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var lT={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var cT={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 r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var uT={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 r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var dT={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var pT={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.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 Tc=new Set(["CLICK","TYPE","SELECT_OPTION"]),mT={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||Tc.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||Tc.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||Tc.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||Tc.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var gT={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var hT={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.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,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var Vo=[pT,gT,hT,mT,$E,WE,KE,YE,JE,QE,ZE,tT,rT,nT,oT,iT,sT,lT,cT,uT,dT];if(oe!==Vo[Vo.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Vo.forEach((r,e)=>{if(!bc.valid(r.toVersion)||!bc.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!bc.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(Vo[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function EL(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var ms=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:i,id:a}=r,l=Vo.findIndex(u=>bc.gt(u.toVersion,i));if(l===-1)return{steps:o,newVersion:i};let c=i;for(let u=l;u<Vo.length;u++){if(n&&yL(c,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=Vo[u],p={id:a,migration:d.name,toVersion:d.toVersion};try{o=await fT(o,d),c=d.toVersion}catch(m){throw t.error({err:m,...p},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let s=SL(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return s.trim()&&t.debug({diffs:s,id:a},"Migration diffs"),{newVersion:c,steps:o}};async function fT(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||EL(i)&&(n[o]=await fT(i,e))}return t}async function yT({rawSteps:r,metadata:e,logger:t,callbacks:n}){jE(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await vc({rawSteps:r.steps,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o}),l={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let s=r[c];if(!s)continue;let{resolvedSteps:u}=await vc({rawSteps:s,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o});l[c]=u}return{resolvedTest:l,moduleIds:Array.from(Object.keys(o))}}async function jo(r,e,t){let{newVersion:n,steps:o}=await ms({metadata:r,steps:e,logger:t});try{return{steps:Oe.array().parse(o),newVersion:n}}catch(i){throw t.error({type:"zod",err:i,newVersion:n,id:r.id,steps:o},"Failed to parse test steps while migrating test"),new jl(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function vc({rawSteps:r,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await jo(e,r,t),l=[];for(let c of a)l.push(await gs({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function gs({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let c=r.moduleId,s=n[c];if(s)return{...ST(s),...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:t});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await ms({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),m;try{m=Oe.array().parse(p)}catch(f){throw t.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=>gs({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let h={...u,steps:g};return n[c]=ST(h),{...h,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of r.blocks){let s=[];for(let u of c.steps)s.push(await gs({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...c,steps:s})}let i;if(r.elseSteps){i=[];for(let c of r.elseSteps)i.push(await gs({step:c,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of r.steps)a.push(await gs({step:c,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function TL(r){return typeof r=="object"&&r!==null}function bn(r){if(Array.isArray(r))return r.map(bn);if(TL(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=bn(n))}),e}return r}import{cloneDeep as bL}from"lodash-es";import{stringify as ET}from"yaml";async function TT({test:r,processedModuleNames:e=new Set,createNewCacheIds:t=!1}){let n={id:r.id,name:r.name,description:r.description,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs,disabled:r.disabled,labels:r.labels},o={},i=await vL({originalStepLists:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:t}),a={fileType:he.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:ET(a),modules:o}}async function vL({originalStepLists:r,modules:e,processedModuleNames:t,createNewCacheIds:n}){let o=bL(r);Object.values(o).forEach(l=>{RL(l??[])});let{stepsToSave:i,moduleUpdates:a}=await ke({stepLists:o,createNewCacheIds:n});for(let l of a)t.has(l.name)||(e[l.name]=AL(l),t.add(l.name));return i}function RL(r){ps({steps:r,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 AL(r){let e=Wt.parse(r),t={fileType:he.MODULE,...e,schemaVersion:oe,steps:r.steps};return ET(t)}async function Z(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function hs({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function $o({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await hs({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function bT(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}function Rc(r){let e=[];for(let t of r)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let n={...t,type:"MODULE"};e.push(xr.parse(n));break}case"SECTION":{let n={...t,steps:Rc(t.steps)};e.push(Oe.parse(n));break}case"CONDITIONAL":{let n={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Rc(o.steps)})),elseSteps:t.elseSteps?Rc(t.elseSteps):void 0};e.push(Mo.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Ac(r){return Rc([r])[0]}import wL from"picomatch";var wc=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||wL(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},Cc=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},qi=r=>{try{return new URL(r),!0}catch{return!1}},vT=r=>!r.toLowerCase().startsWith("http"),Ki=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Wo(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}async function CL(r){let{logger:e,browserStateStorage:t,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:l,disableCache:c}=r,s=[];if(o.length>0){let{results:d}=await Wi(e,t,o,{numStepsWithScreenshots:l,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});s=d}return await n.getTestResultClassification({results:s,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1})}async function RT(r){let{logger:e,browserStateStorage:t,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s}=r,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[yc("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=yc("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=yc("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!t||!u||u.length===0)return{};try{let d=await CL({logger:e,browserStateStorage:t,generator:n,results:u,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as AT}from"uuid";function fm(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var xc=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:fm({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(e.type==="MOBILE_PRESET_STEP"){this.creditsUsedV2+=1;return}let t=Rp(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Ap(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:AT(),properties:fm({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:AT(),properties:fm({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};function Yi({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new Zl:new Sm(r,e,t,n)}var Sm=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Wp(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,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}for(let l of[t,n,o])l&&$i({steps:l,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await ke({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import _L from"path";var IL=new ic(30,60*1e3),bm="https://api.momentic.ai",wT,CT=r=>{bm=r},Qn=()=>bm;var Xi,Tm,_c,xT=async r=>{if(wT&&Xi&&_c)return Xi;let e=new Xe({baseUrl:bm,apiKey:r,logger:E});wT=e;try{let t=await e.getAuthInfo();return Xi=t.orgId,Tm=t.userId,_c=r,Xi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},At=()=>{if(!Xi)throw new Error("Your organization ID is invalid.");return Xi},Ji=()=>{if(!Tm)throw new Error("Your user ID is invalid.");return Tm},Qi=()=>{if(!_c)throw new Error("Your API key is invalid.");return _c},vm,ym,Ic=(r,e)=>{vm=r,ym?.abort(),ym=new AbortController;let t=ym.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=_L.resolve(r.rootDir,o.envFile);try{if(Em.lstatSync(i).isSymbolicLink())return;Em.existsSync(i)&&n.push(i)}catch(a){E.warn({err:a},`Failed to check if env file ${i} exists`)}});try{PL({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){E.error({err:o},"Failed to start config file watchers")}},ae=()=>vm;function PL({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{Em.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(IL.increment("setLocalProject")&&E.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.`),vm=e(n.configFilePath))})})}function ge(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Ss=ML();function fs(r){let e=ae(),t=Et.dirname(e.configFilePath);return Et.join(t,...r)}function LL(r){let e=ae(),t=Et.dirname(e.configFilePath),n=Et.relative(t,r);return n?n.split(Et.sep):[]}function NL(r,e){let t=jt.statSync(r),n=LL(r);return Up.parse({name:e,absolutePath:r,relativePath:n.join(Et.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Ss.post("/",ge(async(r,e,t)=>{let n;try{n=sy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=fs(n);if(!jt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(Et.sep)}`});return}if(!jt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Et.sep)}`});return}let a=ae(),l=Array.from(a.config.exclude??[]).concat(Kl),s=OL("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=Et.join(o,d);return NL(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));Ss.put("/",ge(async(r,e,t)=>{let n;try{n=ly.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=fs(n);if(jt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(Et.sep)}`,pathSegments:n});return}jt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(Et.sep)}`,pathSegments:n};e.status(201).json(i)}));Ss.patch("/",ge(async(r,e,t)=>{let n,o;try{let s=cy.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=fs(n),a=fs(o);if(!jt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(Et.sep)}`});return}if(jt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(Et.sep)}`});return}let l=Et.dirname(a);jt.existsSync(l)||jt.mkdirSync(l,{recursive:!0}),jt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(Et.sep)} to ${o.join(Et.sep)}`,pathSegments:o};e.status(200).json(c)}));Ss.delete("/",ge(async(r,e,t)=>{let n,o=!0;try{let c=uy.parse(r.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=fs(n);if(!jt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(Et.sep)}`,pathSegments:n});return}if(!jt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(Et.sep)}`});return}if(o)jt.rmSync(i,{recursive:!0,force:!0});else{if(jt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}jt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var Rm=Ss;import e1 from"events";import $C,{Router as t1}from"express";import{diff as UL}from"deep-object-diff";import Pr from"fs";import Ko from"path";import Zi from"yaml";import{z as PT}from"zod";import{execSync as DL}from"child_process";function qo(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,E.debug({postSaveCommand:n},"Executing post-save hook command");try{DL(n,{encoding:"utf-8"})}catch(o){E.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as _T}from"deep-object-diff";import Xr from"fs";import{cloneDeep as kL}from"lodash-es";import ys from"path";import{v4 as FL}from"uuid";import Es from"yaml";function Dt({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.modules[r.moduleId]?.fullFilePath;if(!i||!Xr.existsSync(i))throw new Error(`Tried to update module ${r.moduleId} that could not be found on disk`);let a=Xr.readFileSync(i,"utf-8"),l=Es.parse(a),c;if(r.name&&r.name!==l.name){let m=`${xe(r.name)}.${yt.MODULE}`;if(c=ys.join(ys.dirname(i),m),Xr.existsSync(c))throw new Error(`Module with name '${r.name}' already exists at path '${c}'`)}let s={...r,schemaVersion:e},u=bn({fileType:he.MODULE,...Hp.parse(s),steps:Oe.array().parse(r.steps)}),d=_T(u,l);if(d&&Object.keys(d).length===0&&!o){E.debug(`Skipping save for module ${r.moduleId} since there are no changes`);return}let p=Es.stringify(u);Xr.writeFileSync(i,p,"utf-8"),c&&Xr.renameSync(i,c),qo(c||i,n.config)}function IT({moduleId:r,content:e,momenticFiles:t,project:n,logger:o}){let i=t.modules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${r} that could not be found on disk`);let a=vn(i,o),l={...a,...e},c=bn({fileType:he.MODULE,...Hp.parse(l),steps:a.steps}),s=_T(c,a);if(s&&Object.keys(s).length===0){E.debug(`Skipping save for module ${r} since there are no changes`);return}let u=Es.stringify(c);Xr.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${xe(e.name)}.${yt.MODULE}`;if(d=ys.join(ys.dirname(i),p),Xr.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);Xr.renameSync(i,d)}qo(d||i,n.config)}async function Pc({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=xe(r),l=ys.join(o,`${a}.module.yaml`),c=FL(),{stepsToSave:s}=await ke({stepLists:{steps:n}}),u={fileType:he.MODULE,schemaVersion:oe,moduleId:c,name:r,description:e,enabled:t,steps:s.steps},d=Es.stringify(u);return Xr.writeFileSync(l,d,"utf-8"),qo(l,i.config),{moduleId:c,name:r,description:e,enabled:t,steps:n}}function vn(r,e){let t=Xr.readFileSync(r,"utf-8"),n=Es.parse(t);try{return Ip.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic module`),o}}async function fr(r,e,t,n){let o=vn(r.fullFilePath,t),{resolvedSteps:i}=await vc({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:t,callbacks:{onFetchModule:async({id:l})=>{let c=e.modules[l]?.fullFilePath;if(c)return vn(c,t)}}}),a={...o,steps:i};return n&&(n[r.id]=kL(a)),a}async function Mc(r,e){let t={};return await Promise.all(Object.values(r.modules).map(async n=>{await fr(n,r,e,t)})),Array.from(Object.values(t))}async function MT({test:r,name:e,folder:t}){let n=await TT({test:r});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${xe(e)}.${yt.TEST}`,a=Ko.join(t,i);return Pr.writeFileSync(a,n.test,"utf-8"),a}function Am(r,e,t){let n=Ko.join(t.rootDir,r);if(!Pr.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=Pr.readFileSync(n,"utf-8"),i=Zi.parse(o),a,l;if(e.name&&e.name!==i.name){let p=`${xe(e.name)}.${yt.TEST}`;if(a=Ko.join(Ko.dirname(r),p),l=Ko.join(t.rootDir,a),Pr.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let c={...i,...e},s=mr.parse(c),u={fileType:he.TEST,...mr.parse(s),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=Zi.stringify(u);return Pr.writeFileSync(n,d,"utf-8"),l&&Pr.renameSync(n,l),qo(n,t.config),{newRelativeTestPath:a}}function wt({relativeTestPath:r,steps:e,schemaVersion:t,project:n,forceSaveOnNoDiffs:o}){let i=Ko.join(n.rootDir,r);if(!Pr.existsSync(i))throw new Error(`Test not found at path '${r}' in project '${n.rootDir}'`);let a=Pr.readFileSync(i,"utf-8"),l=Zi.parse(a),c=mr.parse({...l,schemaVersion:t}),s=Oe.array().or(PT.undefined()).parse(e.beforeSteps),u=Oe.array().parse(e.steps),d=Oe.array().or(PT.undefined()).parse(e.afterSteps),p=bn({fileType:he.TEST,...c,beforeSteps:s&&s.length>0?s:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=UL(p,l);if(m&&Object.keys(m).length===0&&!o){E.debug(`Skipping save for test ${c.name} since there are no changes`);return}let g=Zi.stringify(p);Pr.writeFileSync(i,g,"utf-8"),E.debug(`Saving test ${c.name} to ${i}`),qo(i,n.config)}function Oc(r,e){let t=Ko.join(e.rootDir,r);if(!t)throw new Error(`Could not find test with path ${r} in Momentic project (${e.rootDir})`);let n;try{n=Pr.readFileSync(t,"utf8"),n=n.replace(/\r\n|\r/g,`
27
- `)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=Zi.parse(n)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return Ot.parse(o)}function Yo(r,e,t){let n=t.project.rootDir,o;try{o=Pr.readFileSync(r,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=Zi.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${r} is missing steps`);return i}async function tt(r,e,t){let n=Yo(r,e,t),o;try{o=mr.parse(n)}catch(a){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await yT({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:l})=>{let c=t.modules[a]?.fullFilePath;if(c)return vn(c,l)}}});return i}import BL from"@dotenvx/dotenvx";import zL from"fs";import OT from"path";function Lc(r,e){return(r.config.environments??[]).map(t=>Ts(t.name,r,e))}function LT(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function HL(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=LT(i);l&&(n[o]=l);continue}let a;try{a=zL.readFileSync(OT.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&E.debug(n,"Set environment variables with interpolation from project configuration"),n}function GL(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=BL.config({path:OT.resolve(e.rootDir,t),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 Ts(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);if(!n.baseUrl)throw new Error(`Browser environment ${r} does not have a baseUrl configured`);let o={[ft]:LT(n.baseUrl)},i=HL({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=GL({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o,browser:n.browser}}import{existsSync as eN,readFileSync as tN,readdirSync as rN,writeFileSync as nN}from"fs";import{globSync as oN}from"glob";import Xo,{dirname as FT}from"path";import{cwd as Im}from"process";import UT from"yaml";import{z as Fe}from"zod";import NT from"fs";import{globSync as VL}from"glob";import bs from"path";import jL from"yaml";import{z as wm}from"zod";var DT=!1,Cm=[`**/*.${yt.TEST}`,`**/*.${yt.MODULE}`],xm=wm.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),_m=50,$L=wm.object({fileType:wm.nativeEnum(he)});function W(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},n=r.config.include??Cm,o=Array.from(r.config.exclude??[]).concat(Kl),i=VL(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:_m,nodir:!0});for(let a of i){let l=WL(r.rootDir,a,t,e?En:E);l&&(t.duplicateEntities[l.id]=l.paths)}return DT=!0,t}function WL(r,e,t,n){let o=bs.join(r,e),i=qL(o,n);if(!i)return;let a=KL(i,o,n);if(!a)return;let l=$L.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=YL(o,n);if(!s)return;let u=XL(e,o,s);switch(c){case he.TEST:try{return JL(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case he.MODULE:try{return QL(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case he.MOBILE_TEST:try{return ZL(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}default:{let d=c;return}}}function qL(r,e){try{return NT.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function KL(r,e,t){try{let n=jL.parse(r);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){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function YL(r,e){try{return NT.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function XL(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:bs.sep,fullPathSegments:e.split(bs.sep),relativePathSegments:r.split(bs.sep),fileName:bs.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function JL(r,e,t,n,o){let i=mr.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:he.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function QL(r,e,t,n,o){let i=Wt.parse(r),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:he.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let l=t.fileName.replace(`.${yt.MODULE}`,"");return!DT&&xe(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function ZL(r,e,t,n,o){let i=Mp.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(`.${yt.TEST}`,"");return e.mobileTests[i.id]={type:he.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var ea="momentic.config.yaml",kT="momentic.workspace.yaml",iN=Fe.object({projects:Fe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),aN=Fe.union([Fe.string(),Fe.object({fromFile:Fe.string(),json:Fe.boolean().optional()})]),sN=Fe.object({name:xm,baseUrl:Fe.string().optional().describe("Optional for mobile tests"),envFile:Fe.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Fe.record(Fe.string(),aN).optional(),inheritFromShell:Fe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:No.optional().describe("deprecated: use project-level configuration only")}),lN=Fe.object({postSave:Fe.string().optional()}),cN=Fe.object({name:xm,include:Fe.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Fe.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Fe.string().optional(),reporterDir:Fe.string().optional(),outputDir:Fe.string().optional(),retries:Fe.number().optional().describe("number of retries per test"),parallel:Fe.number().optional().describe("degree of parallelism"),environments:Fe.array(sN).optional(),gitMainBranch:Fe.string().optional(),gitProtectedBranches:Fe.string().array().optional(),ai:Gp.optional(),browser:No.optional(),emulator:Pp.optional(),advanced:Vp.optional(),hooks:lN.optional()});function BT(r,e){let t;try{t=tN(r,"utf-8")}catch(o){E.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=UT.parse(t),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){E.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Pm(r){let e=BT(r,"project configuration");if(e!==void 0)try{return cN.parse(e)}catch(t){E.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function uN(r){let e=BT(r,"workspace configuration");if(e!==void 0)try{return iN.parse(e)}catch(t){E.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function dN(){let r=[],e=Im(),t=Xo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Xo.basename(e);if(ql.includes(i))return E.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of rN(e))if(a.endsWith(ea)){let l=Xo.join(e,a),c=Pm(l);c&&r.push({configFilePath:l,config:c,rootDir:FT(l)})}if(r.length)return r;if(e=Xo.dirname(e),e===t)break}return r}function Tt(r={}){let{configFilePath:e,nameFilter:t}=r,n=Mm(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
28
- ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return E.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function pN(r){let e=uN(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ea}`)),n=oN(t,{absolute:!1,cwd:Im(),dotRelative:!1,maxDepth:_m,nodir:!0}),o=[];for(let i of n){let a=Xo.join(Im(),i),l=Pm(a);l&&o.push({configFilePath:a,config:l,rootDir:FT(a)})}return o}function Mm(r){if(r){r=Xo.resolve(r);let t=Pm(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Xo.dirname(r)}]}if(eN(kT)){let t=pN(kT);if(t)return t}return dN()}function ta(r,e){let t=UT.stringify(r);nN(e,t)}import ra from"fs";import Om from"path";import{z as Lm}from"zod";var zT="golden/visual-diff",HT="reports",GT="test-results";var mN=Lm.object({width:Lm.number(),height:Lm.number()}),na=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let n=Om.join(e.rootDir,e.config.goldenFileDir??zT);this.defaultGoldenScreenshotDir=n,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,n){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Om.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ra.mkdirSync(Om.dirname(o),{recursive:!0}),ra.writeFileSync(o,n.buffer),ra.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(ra.existsSync(o)){let a=ra.readFileSync(o),l=mN.parse(JSON.parse(ra.readFileSync(i,"utf-8")));return{buffer:a,width:l.width,height:l.height}}else throw new C("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var Jr=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import{execFile as gN}from"node:child_process";import{promisify as hN}from"node:util";import fN from"simple-git";var Ue=fN(),VT=hN(gN);async function SN(r){let e=await Be(r,Ue.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
29
- `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function yN(r,e,t){try{let o=t["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 VT("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await VT("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function EN(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return yN(r,e,t);if(o)return}catch{}}function Nc(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function Be(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function TN(){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 bN(r){let[e,t,n]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.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{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:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function vN(r){let[e,t,n]=await Promise.all([Be(r,Ue.listRemote(["--get-url","origin"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"]))]);return{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:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function RN(r){let[e,t,n,o]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.listRemote(["--get-url","origin"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Nc(t):void 0;return{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:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function AN(r){let[e,t,n]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Nc(o):void 0;return{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:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function wN(r){let[e,t,n]=await Promise.all([Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Nc(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function CN(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([Be(r,Ue.revparse(["HEAD"])),Be(r,Ue.revparse(["--short","HEAD"])),Be(r,Ue.revparse(["--abbrev-ref","HEAD"])),Be(r,Ue.listRemote(["--get-url","origin"])),Be(r,Ue.show(["--no-patch","--format=%ci"])),Be(r,Ue.show(["-s","--pretty=%B"])),Be(r,Ue.show(["-s","--pretty=%an"])),e?Be(r,Ue.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),SN(r)]),d=s?await Be(r,Ue.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Nc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,y=u["user.username"]||void 0,S=await EN(r,i,u)??y??void 0;return r.debug({userUsername:S,gitLocalUserLogin:y,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:S,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function xN(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function _N(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Nm(r,e){let t=TN();if(!t)return CN(r,e);switch(t){case"GithubActions":return bN(r);case"GitlabCI":return vN(r);case"CircleCI":return RN(r);case"Buildkite":return AN(r);case"AzureDevOps":return wN(r);case"GCPCloudBuild":return xN()}}async function IN(r,e,t,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(t,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){r.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(t,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){r.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(t,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){r.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function PN(r,e,t,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(t,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){r.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(t,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){r.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(t,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){r.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function MN(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await PN(r,e,n,o,t)}else if(t.gitlabProjectPath)return await IN(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Zn(r,e,t){let n=await _N(t),o=await Nm(r,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await MN(r,e,i);return{...n,...o,...a}}import cie from"yaml";import{randomUUID as ON}from"crypto";import Rn from"fs";import Jo from"path";var jT={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function LN(r,e,t){if(jT[t]){let i=jT[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var $T=new Set([".DS_Store","__MACOSX"]);function WT(r,e,t){let n=ON(),o=r.child({runGroupId:n});Rn.rmSync(e,{recursive:!0,force:!0});let i=Rn.readdirSync(t).filter(s=>!$T.has(s)).map(s=>Jo.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Rn.mkdirSync(e,{recursive:!0});let a=Jo.join(i[0],"metadata.json"),l={...as.parse(JSON.parse(Rn.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=Jo.join(s,"runs");if(!Rn.existsSync(u))continue;let d=Rn.readdirSync(u);for(let g of d){if($T.has(g))continue;let h=Jo.join(u,g),f=Jo.join(e,"runs",g);Rn.cpSync(h,f,{recursive:!0})}let p=Jo.join(s,"metadata.json"),m=as.parse(JSON.parse(Rn.readFileSync(p,"utf-8")));o.info({oldRunGroupId:m.id},"Merging metadata from run groups");for(let g in m){if(g==="id")continue;let h=g;l[h]=LN(l,m,h)}}let c=Jo.join(e,"metadata.json");Rn.writeFileSync(c,JSON.stringify(l,null,2))}import qT from"adm-zip";import Dm from"fs";import Dc from"path";function NN(r){let e=new qT,t=Dc.join(r,"metadata.json"),n=as.parse(JSON.parse(Dm.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Dm.readdirSync(Dc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new qT(Dc.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(Dc.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function kc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Dm.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new sc(e);try{let{runGroupId:i,buffer:a}=NN(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;t.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",t.error(`Failed to upload test results: ${a}.`);return}}import DN from"adm-zip";import $t from"fs";import Mr from"path";var vs=class r{constructor(e){this.filePath=e;$t.rmSync(this.filePath,{recursive:!0,force:!0}),$t.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Mr.join(this.filePath,e))}mkdir(e){$t.mkdirSync(Mr.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Mr.join(this.filePath,e);if($t.existsSync(t))return $t.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Mr.join(this.filePath,t);try{$t.writeFileSync(o,n)}catch{}}createRunArchive(e){return new km(Mr.join(this.filePath,"runs"),e)}},km=class{constructor(e,t){this.filePath=e;this.tempPath=Mr.join(e,`.${t}`),this.finalPath=Mr.join(e,`${t}.zip`),$t.rmSync(this.tempPath,{recursive:!0,force:!0}),$t.rmSync(this.finalPath,{recursive:!0,force:!0}),$t.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Mr.join(this.tempPath,e);if($t.existsSync(t))return $t.readFileSync(t)}mkdir(e){$t.mkdirSync(Mr.join(this.tempPath,e),{recursive:!0})}cd(e){return new vs(Mr.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Mr.join(this.tempPath,t);$t.writeFileSync(o,n)}close(){let e=new DN;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();$t.writeFileSync(this.finalPath,t),$t.rmSync(this.tempPath,{recursive:!0,force:!0})}};import r1 from"http";import n1 from"path";import{Server as Fz}from"socket.io";var kN=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{e.info({sessionId:n},"Cancel event received");let o=t.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},KT={event:"cancel",createHandler:kN};var FN=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let s=(await l.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:s},"Fetched a11y tree from the browser"),i({a11yTree:s})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},YT={event:"fetchA11yTree",createHandler:FN};var UN=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let c=await l.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})}}},XT={event:"fetchDom",createHandler:UN};var BN=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),t.removeSession(n,e)}},JT={event:"disconnect",createHandler:BN};function Qr(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=zN(t);HN(e,n,o);let i=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await GN(i,e,n,o)}catch(a){r.logger.error({result:r.result,err:a},"Error hoisting scalar result metadata")}})())}function zN(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.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"})(e)}if(t)break}let n=r[r.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:t,lastMetadata:o}}function HN(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function GN(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeSnapshot=t.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import Rs from"os";import VN from"v8";var QT,Zr,jN=Rs.platform(),$N=Rs.cpus().map(r=>({model:r.model,speed:r.speed})).reduce((r,e)=>(r[e.model]={speed:e.speed},r.totalCores=(r.totalCores??0)+1,r),{});function ZT(r){if(yn)return;let e=()=>{try{let t=!1,n=WN(),o=qN();n.freeMemory<1e6&&(t=!0);let i=VN.getHeapStatistics(),a=i.used_heap_size,l=i.heap_size_limit;a/l>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:$N,platform:jN}}function WN(){let r=Rs.totalmem(),e=Rs.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function qN(){let r=Rs.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!Zr)return Zr=t,null;let n={user:t.user-Zr.user,nice:t.nice-Zr.nice,sys:t.sys-Zr.sys,idle:t.idle-Zr.idle,irq:t.irq-Zr.irq,total:t.total-Zr.total};return QT={measurementTime:e,intervalMs:e-Zr.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},Zr=t,QT}import{randomUUID as oD}from"crypto";import{faker as KN}from"@faker-js/faker";import YN from"assert";import XN from"axios";import*as JN from"child_process";import QN from"moment";import*as ZN from"otpauth";import eD from"pg";async function eb(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Ul(n,e);t.push(...o)}),t}function tD(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function rD(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var nD=Object.getPrototypeOf(async function(){}).constructor;async function tb(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(T,A)=>{o[T]=A,s[T]=A},d={},p=(T,A)=>{o[T]=A,d[T]=A},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 nD("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(XN,QN,c.fakerInstance??KN,YN,eD,m,g,ZN,JN,eb,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,A=>c.sms.send(A),A=>c.sms.fetchLatest(A),c.email,c.sms,c.ai,tD(a,l),...Object.values(i??{}))),f=!0,y,S;try{let T=await H(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});y=await rD(e.options.responseSerialization??"RAW",T)}catch(T){t.error({err:T,env:o,evalCode:n},`[${r}] Error executing code: ${T}`),f=!1,T instanceof Kn?S=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:S=T instanceof Error?T.message:`${T}`}return{result:y,variableUpdates:s,persistentVariableUpdates:d,success:f,error:S}}async function rb({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=$n,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=oD(),p=await tb(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return E.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as iD,randomUUID as aD}from"crypto";import sD from"fetch-retry";var lD=sD(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),nb=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,ob=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ib({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=$n,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!nb)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!ob)throw new Error("Missing lambda auth secret.");let h=iD("sha256",ob).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let y={id:aD(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await H(lD(nb,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),{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(S){m=S}}if(m)throw l.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=FS.parse(await p.json())}catch(y){throw new Error(`Code evaluation server returned invalid response: ${y}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function eo(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ib(r);else if(r.localTools)e=await rb({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
25
+ ${Go(`Sub-steps: ${e}`,2)}`}default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}var zE=1e3,HE=3e6,RL="[FAILED]";async function GE(r,e,t){if(t){let n=await e.getScreenshot(r,t);if(n)return`data:image/jpeg;base64,${Buffer.from(n).toString("base64")}`}}function AL(r,e){let t=(()=>{switch(r.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")})(r)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${t}
26
+ ${o}`:o)(fm(r))}function bc(r,e={}){let t=e.followingStepStart??e.precedingStepEnd??new Date;return{type:"PRESET_ACTION",id:BE(),message:`Starting the ${r.replace("-"," ")} section`,startedAt:t,finishedAt:t,status:"SUCCESS",command:{id:BE(),type:"SUCCESS"},results:[]}}function Tc(r,e={}){let{index:t,includeDomState:n=!1,header:o}=e,i=AL(r,o),a;r.type==="PRESET_ACTION"&&(a=r.results?.[0]?.elementInteracted);let l=r.message!=="Successfully executed preset action."?r.message:void 0,c=i;r.status==="FAILED"&&(c=`${RL} ${c}`);let s={description:c,startedAt:r.startedAt.toISOString(),finishedAt:r.finishedAt.toISOString(),beforeUrl:r.beforeUrl,afterUrl:r.afterUrl,beforeSnapshot:r.beforeSnapshot,afterSnapshot:r.afterSnapshot,elementInteracted:a,message:l,index:t};if(r.status==="FAILED"&&n)try{let u=rS.array().parse(r.details);for(let d of u)"pageState"in d&&(s.pageState=d.pageState)}catch{}return s}async function WE(r,e,t,{addIndices:n=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:l=0}){let c,s=[];for(let u=0;u<t.length;u++){let d=t[u],p=n?u+l:void 0;switch(d.type){case"PRESET_ACTION":{s.push(Tc(d,{index:p,includeDomState:o,header:void 0})),d.status==="FAILED"&&(c=p);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){s.push(Tc(d,{index:n?p:void 0,includeDomState:o,header:"start"})),l+=1;let{failureIndex:m,results:g}=await WE(r,e,d.results,{addIndices:n,includeDomState:o,flatten:i,maxItemsFromEnd:a,indexOffset:l+u});s.push(...g),m!==void 0&&(c=m),l+=g.length,s.push(Tc(d,{index:n?l+u:void 0,includeDomState:o,header:"end"})),l+=1}else s.push(Tc(d,{index:n?l+u:void 0,includeDomState:o,header:void 0}));break}default:return(g=>{throw new Error("You missed a case in the switch above")})(d)}}return{results:s,failureIndex:c}}async function $i(r,e,t,{numStepsWithScreenshots:n=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,flatten:l=!0,maxItemsFromEnd:c=20}){let s=await WE(r,e,t,{addIndices:o,includeDomState:a,flatten:l,maxItemsFromEnd:c,indexOffset:0}),{results:u}=s,{failureIndex:d}=s;d!==void 0&&u.length>0&&(u=u.slice(0,d+1));let p=[],m=0;if(c!==void 0&&u.length>c&&(m=u.length-c),d!==void 0&&d<u.length-1&&r.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:u.length,lastIndex:u.length-1,isLastIndex:d===u.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let g=m;g<u.length;g++){let h=u[g],f={description:h.description,startedAt:h.startedAt,finishedAt:h.finishedAt,beforeUrl:h.beforeUrl,afterUrl:h.afterUrl,elementInteracted:h.elementInteracted,message:h.message,pageState:h.pageState,index:h.index},E,S;(n===void 0||n>0&&g>=u.length-n)&&(h.afterSnapshot&&(S=await GE(r,e,h.afterSnapshot)),i&&h.beforeSnapshot&&(E=await GE(r,e,h.beforeSnapshot))),f.beforeScreenshot=E,f.afterScreenshot=S,p.push(f)}return{results:p,failureIndex:d!==void 0?d-m:void 0}}function Wi({json:r,keysToRedact:e,maxJsonStringSize:t}){try{if(!r)return r;if(typeof r=="string")return Qe(r,t??2e4);if(typeof r=="object"){let{jsonString:n}=$E(JSON.stringify(r,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),t??2e4);return JSON.parse(n)}return r}catch{return r}}function Sm(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=$E(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":VE(n);break;case"CONDITIONAL":n.assertionResult&&VE(n.assertionResult),Sm(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{Sm(n.results,e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}}function VE(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function jE(r,e){let t=JSON.stringify(r),n=t.replaceAll("\\u0000","");if(t.length!==n.length){let o=t.indexOf("\\u0000");e.warn({input:t.slice(Math.max(0,o-500),Math.min(t.length,o+500))},"Database content violation: stripped unicode character from input")}return n}function vc(r,e){let t=vL(r);if(Sm(t,e),t.length>zE)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,zE);let n=jE(t,e);if(n.length>HE)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>HE;)t.pop(),n=jE(t,e);try{return gt.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 GZ}from"lodash-es";var wL=/^(?!.*\S+\s+\S+).*$/,CL=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,xL=/style="([^"]*)/g,_L=/data-[\w-]+/g,IL=r=>{switch(r.type){case"AI_ASSERTION":return{type:r.type,assertion:r.assertion};case"DRAG":if(r.fromTarget.type==="description")return{type:r.type,description:r.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(r.target?.type==="description")return{type:r.type,description:r.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function qE(r){let e=IL(r),t=e.type==="AI_ASSERTION"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:wL.test(t)&&CL.test(t)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:xL.test(t)?{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"}:_L.test(t)?{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(t)?{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"}}function KE(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import{cloneDeep as bT}from"lodash-es";import NL from"diff-lines";import Ac,{gte as DL}from"semver";var YE={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var XE={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 r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var PL=["target","fromTarget","toTarget"];function JE(r){for(let e of PL){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var QE={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return JE(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])JE(n);return e}default:return e}})};import{v4 as ML}from"uuid";var ZE={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=ML()),e;default:return e}})};import{v4 as eT}from"uuid";var tT={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??eT(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??eT()}})),delete e.commands),e;default:return e}})};var rT={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 r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as OL}from"uuid";var nT={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 r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=OL()),e))};import{v4 as oT}from"uuid";var iT={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 r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=oT())}return e.id=oT(),e})};var aT={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 r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as LL}from"uuid";var sT={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=LL()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var lT={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var cT={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&uT(t),e})};function uT(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){uT(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var dT={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||t.url===void 0||(t.action={type:"SUBSTRING",substring:t.url},t.url=void 0),e})};var pT={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TYPE"?e:t.pressKeysSequentially===void 0?(t.delay=0,e):(t.pressKeysSequentially&&(t.pressKeysSequentially=void 0,t.delay=50),e)})};var mT={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 r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="WAIT_FOR_URL"||t.url===void 0||(t.matcher={type:"GLOB",glob:t.url},t.url=void 0),e})};var gT={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 r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t)return e;if(t.type==="SELECT_OPTION"){if(t.option===void 0)return e;t.choice={type:"VALUE",value:t.option},t.option=void 0}else if(t.type==="TAB"){if(t.url===void 0)return e;t.action={type:"SUBSTRING",substring:t.url},t.url=void 0}else if(t.type==="WAIT_FOR_URL"){if(t.url===void 0)return e;t.matcher={type:"GLOB",glob:t.url},t.url=void 0}else t.type==="AI_WAIT"&&(t.type="AI_ASSERTION",t.timeout||(t.timeout=10));return e})};var hT={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="MOCK_ROUTE"&&t.type!=="SET_HEADER"&&t.type!=="RECORD_REQUESTS"&&t.type!=="REGISTER_REQUEST_LISTENER"||(t.type==="REGISTER_REQUEST_LISTENER"||t.type==="RECORD_REQUESTS"?t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.pattern}}:(t.type==="SET_HEADER"||t.type==="MOCK_ROUTE")&&t.urlPattern&&(t.requestMatcher={urlMatcher:{type:"REGEX",regex:t.urlPattern}})),e})};var fT={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.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 Rc=new Set(["CLICK","TYPE","SELECT_OPTION"]),ST={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||Rc.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let l=a?.elementDescriptor,c=a?.type;(l!==void 0||Rc.has(c))&&(a.target={elementDescriptor:l??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let l=a.command,c=l?.elementDescriptor,s=l?.type;(c!==void 0||Rc.has(s))&&(l.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,m=d?.type;(p!==void 0||Rc.has(m))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var yT={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var ET={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.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,l=a?.type;l?.startsWith("PRESET_")&&(a.type=l.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(s=>{let u=s.type;u?.startsWith("PRESET_")&&(s.type=u.slice(7))})}),e}),stopOnFailure:!0};var Vo=[fT,yT,ET,ST,YE,XE,QE,ZE,tT,rT,nT,iT,aT,sT,lT,cT,dT,pT,mT,gT,hT];if(ie!==Vo[Vo.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Vo.forEach((r,e)=>{if(!Ac.valid(r.toVersion)||!Ac.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Ac.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(Vo[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function kL(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var fs=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:i,id:a}=r,l=Vo.findIndex(u=>Ac.gt(u.toVersion,i));if(l===-1)return{steps:o,newVersion:i};let c=i;for(let u=l;u<Vo.length;u++){if(n&&DL(c,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=Vo[u],p={id:a,migration:d.name,toVersion:d.toVersion};try{o=await TT(o,d),c=d.toVersion}catch(m){throw t.error({err:m,...p},"Migration failed"),new Error(`Step migration ${d.name} failed: ${m}`)}}let s=NL(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return s.trim()&&t.debug({diffs:s,id:a},"Migration diffs"),{newVersion:c,steps:o}};async function TT(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let i=n[o];!i||!Array.isArray(i)||kL(i)&&(n[o]=await TT(i,e))}return t}async function vT({rawSteps:r,metadata:e,logger:t,callbacks:n}){KE(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await wc({rawSteps:r.steps,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o}),l={...e,steps:i,schemaVersion:a};for(let c of["beforeSteps","afterSteps"]){let s=r[c];if(!s)continue;let{resolvedSteps:u}=await wc({rawSteps:s,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o});l[c]=u}return{resolvedTest:l,moduleIds:Array.from(Object.keys(o))}}async function jo(r,e,t){let{newVersion:n,steps:o}=await fs({metadata:r,steps:e,logger:t});try{return{steps:Le.array().parse(o),newVersion:n}}catch(i){throw t.error({type:"zod",err:i,newVersion:n,id:r.id,steps:o},"Failed to parse test steps while migrating test"),new Kl(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function wc({rawSteps:r,migrationMetadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await jo(e,r,t),l=[];for(let c of a)l.push(await Ss({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:i}}async function Ss({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let c=r.moduleId,s=n[c];if(s)return{...bT(s),...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:c,logger:t});if(!u)throw new Error(`Could not find module with id ${c}`);let{newVersion:d,steps:p}=await fs({metadata:{id:c,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),m;try{m=Le.array().parse(p)}catch(f){throw t.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=>Ss({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let h={...u,steps:g};return n[c]=bT(h),{...h,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of r.blocks){let s=[];for(let u of c.steps)s.push(await Ss({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...c,steps:s})}let i;if(r.elseSteps){i=[];for(let c of r.elseSteps)i.push(await Ss({step:c,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let c of r.steps)a.push(await Ss({step:c,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:a};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function FL(r){return typeof r=="object"&&r!==null}function Tn(r){if(Array.isArray(r))return r.map(Tn);if(FL(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=Tn(n))}),e}return r}import{cloneDeep as UL}from"lodash-es";import{stringify as RT}from"yaml";async function AT({test:r,processedModuleNames:e=new Set,createNewCacheIds:t=!1}){let n={id:r.id,name:r.name,description:r.description,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs,disabled:r.disabled,labels:r.labels},o={},i=await BL({originalStepLists:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:t}),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:RT(a),modules:o}}async function BL({originalStepLists:r,modules:e,processedModuleNames:t,createNewCacheIds:n}){let o=UL(r);Object.values(o).forEach(l=>{zL(l??[])});let{stepsToSave:i,moduleUpdates:a}=await Fe({stepLists:o,createNewCacheIds:n});for(let l of a)t.has(l.name)||(e[l.name]=HL(l),t.add(l.name));return i}function zL(r){hs({steps:r,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 HL(r){let e=Wt.parse(r),t={fileType:Se.MODULE,...e,schemaVersion:ie,steps:r.steps};return RT(t)}async function Z(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function ys({promiseGenerator:r,signal:e,codePath:t,logger:n}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}n?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((l,c)=>{function s(){clearInterval(a),e?.removeEventListener("abort",s),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",s),(async()=>{try{l(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",s)}})()})}async function $o({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,l=()=>{a.abort()},c=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",l);try{return await ys({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",l),clearTimeout(c)}}function wT(r){let e;return r>10*60*1e3?e=2*60*1e3:r>60*1e3?e=20*1e3:r>10*1e3?e=2*1e3:e=1e3,e}function Cc(r){let e=[];for(let t of r)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let n={...t,type:"MODULE"};e.push(_r.parse(n));break}case"SECTION":{let n={...t,steps:Cc(t.steps)};e.push(Le.parse(n));break}case"CONDITIONAL":{let n={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:Cc(o.steps)})),elseSteps:t.elseSteps?Cc(t.elseSteps):void 0};e.push(Po.parse(n));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function xc(r){return Cc([r])[0]}import GL from"picomatch";var _c=(r,e,t)=>{t?.caseInsensitive&&(r=r.toLowerCase());let n;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;n=r.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;n=r===e.glob||GL(o)(r);break}case"REGEX":{n=new RegExp(e.regex).test(r);break}case"DOMAIN":{let o=t?.caseInsensitive?e.domain.toLowerCase():e.domain;n=new URL(r).hostname===o;break}}return t?.negated?!n:n},Ic=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:i}=new URL(e);return t!==o||n!==i}catch{return!1}},qi=r=>{try{return new URL(r),!0}catch{return!1}},CT=r=>!r.toLowerCase().startsWith("http"),Ki=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Wo(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}async function VL(r){let{logger:e,browserStateStorage:t,generator:n,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:l,disableCache:c}=r,s=[];if(o.length>0){let{results:d}=await $i(e,t,o,{numStepsWithScreenshots:l,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});s=d}return await n.getTestResultClassification({results:s,errorMessage:i.message,errorStack:i.stack},{disableCache:c??!1})}async function xT(r){let{logger:e,browserStateStorage:t,generator:n,fullResults:o,failureReason:i,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s}=r,u=o?.results??[];if(i==="SetupFailureError"){let d=(o?.beforeResults??[]).at(0);u=[bc("setup",{followingStepStart:d?.startedAt}),...o?.beforeResults??[]]}else if(i==="TeardownFailureError"){let d=u.at(-1),p=(o?.afterResults??[])[0],m=bc("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=bc("main-test-body",{precedingStepEnd:d?.finishedAt,followingStepStart:p?.startedAt});u=[...o?.beforeResults??[],m,...u]}if(!t||!u||u.length===0)return{};try{let d=await VL({logger:e,browserStateStorage:t,generator:n,results:u,error:a,maxItemsFromEnd:l,numStepsWithScreenshots:c,disableCache:s});return{classification:d,aiFailureReason:d.reason}}catch(d){return e.error({err:d},"Failed to classify test result"),{}}}import{v4 as _T}from"uuid";function ym(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Pc=class{reporter;asyncWork;metadata;creditsUsedV1=0;creditsUsedV2=0;constructor({logger:e,reporter:t,runType:n,runId:o,testMetadata:i,suiteMetadata:a}){this.reporter=t,this.metadata={testId:i.id,testName:i.name,suiteId:a?.id,suiteName:a?.name},this.asyncWork=[t.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:o,properties:ym({},this.metadata)}]).catch(l=>e.error({err:l},"Failed to report billable event"))]}trackStepExecution(e){if(e.type==="MOBILE_PRESET_STEP"){this.creditsUsedV2+=1;return}let t=Cp(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=xp(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:_T(),properties:ym({creditsUsed:this.creditsUsedV1},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),this.creditsUsedV2>0&&this.asyncWork.push(this.reporter.reportBillableEvents(e,[{event:"credits-used-v2",timestamp:new Date().toISOString(),transactionId:_T(),properties:ym({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};function Yi({orgId:r,client:e,gitMetadata:t,alwaysSaveCache:n,noCache:o}){return o?new nc:new Em(r,e,t,n)}var Em=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=Yp(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,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}for(let l of[t,n,o])l&&ji({steps:l,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await Fe({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import $L from"path";var WL=new cc(30,60*1e3),Rm="https://api.momentic.ai",IT,PT=r=>{Rm=r},Jn=()=>Rm;var Xi,vm,Mc,MT=async r=>{if(IT&&Xi&&Mc)return Xi;let e=new Je({baseUrl:Rm,apiKey:r,logger:T});IT=e;try{let t=await e.getAuthInfo();return Xi=t.orgId,vm=t.userId,Mc=r,Xi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},At=()=>{if(!Xi)throw new Error("Your organization ID is invalid.");return Xi},Ji=()=>{if(!vm)throw new Error("Your user ID is invalid.");return vm},Qi=()=>{if(!Mc)throw new Error("Your API key is invalid.");return Mc},Am,Tm,Oc=(r,e)=>{Am=r,Tm?.abort(),Tm=new AbortController;let t=Tm.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=$L.resolve(r.rootDir,o.envFile);try{if(bm.lstatSync(i).isSymbolicLink())return;bm.existsSync(i)&&n.push(i)}catch(a){T.warn({err:a},`Failed to check if env file ${i} exists`)}});try{qL({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){T.error({err:o},"Failed to start config file watchers")}},se=()=>Am;function qL({filesToWatch:r,revalidator:e,signal:t,project:n}){r.forEach(o=>{bm.watch(o,{signal:t,persistent:!1,recursive:!1},(i,a)=>{a&&(WL.increment("setLocalProject")&&T.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.`),Am=e(n.configFilePath))})})}function fe(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Ts=KL();function Es(r){let e=se(),t=yt.dirname(e.configFilePath);return yt.join(t,...r)}function XL(r){let e=se(),t=yt.dirname(e.configFilePath),n=yt.relative(t,r);return n?n.split(yt.sep):[]}function JL(r,e){let t=jt.statSync(r),n=XL(r);return Hp.parse({name:e,absolutePath:r,relativePath:n.join(yt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Ts.post("/",fe(async(r,e,t)=>{let n;try{n=dy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Es(n);if(!jt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(yt.sep)}`});return}if(!jt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(yt.sep)}`});return}let a=se(),l=Array.from(a.config.exclude??[]).concat(Ql),s=YL("*",{absolute:!1,cwd:o,ignore:l,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=yt.join(o,d);return JL(p,d)}),u={absolutePath:o,pathSegments:n,contents:s};e.status(200).json(u)}));Ts.put("/",fe(async(r,e,t)=>{let n;try{n=py.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Es(n);if(jt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(yt.sep)}`,pathSegments:n});return}jt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(yt.sep)}`,pathSegments:n};e.status(201).json(i)}));Ts.patch("/",fe(async(r,e,t)=>{let n,o;try{let s=my.parse(r.body);n=s.pathSegments,o=s.newPathSegments}catch(s){e.status(400).json({error:`Failed to parse folder update body: ${s}`});return}let i=Es(n),a=Es(o);if(!jt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(yt.sep)}`});return}if(jt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(yt.sep)}`});return}let l=yt.dirname(a);jt.existsSync(l)||jt.mkdirSync(l,{recursive:!0}),jt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(yt.sep)} to ${o.join(yt.sep)}`,pathSegments:o};e.status(200).json(c)}));Ts.delete("/",fe(async(r,e,t)=>{let n,o=!0;try{let c=gy.parse(r.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=Es(n);if(!jt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(yt.sep)}`,pathSegments:n});return}if(!jt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(yt.sep)}`});return}if(o)jt.rmSync(i,{recursive:!0,force:!0});else{if(jt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}jt.rmdirSync(i)}let l={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(l)}));var wm=Ts;import h1 from"events";import ix,{Router as f1}from"express";import{diff as tN}from"deep-object-diff";import Mr from"fs";import Ko from"path";import Zi from"yaml";import{z as NT}from"zod";import{execSync as QL}from"child_process";function qo(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,T.debug({postSaveCommand:n},"Executing post-save hook command");try{QL(n,{encoding:"utf-8"})}catch(o){T.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as OT}from"deep-object-diff";import Xr from"fs";import{cloneDeep as ZL}from"lodash-es";import bs from"path";import{v4 as eN}from"uuid";import vs from"yaml";function Dt({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.modules[r.moduleId]?.fullFilePath;if(!i||!Xr.existsSync(i))throw new Error(`Tried to update module ${r.moduleId} that could not be found on disk`);let a=Xr.readFileSync(i,"utf-8"),l=vs.parse(a),c;if(r.name&&r.name!==l.name){let m=`${_e(r.name)}.${St.MODULE}`;if(c=bs.join(bs.dirname(i),m),Xr.existsSync(c))throw new Error(`Module with name '${r.name}' already exists at path '${c}'`)}let s={...r,schemaVersion:e},u=Tn({fileType:Se.MODULE,...jp.parse(s),steps:Le.array().parse(r.steps)}),d=OT(u,l);if(d&&Object.keys(d).length===0&&!o){T.debug(`Skipping save for module ${r.moduleId} since there are no changes`);return}let p=vs.stringify(u);Xr.writeFileSync(i,p,"utf-8"),c&&Xr.renameSync(i,c),qo(c||i,n.config)}function LT({moduleId:r,content:e,momenticFiles:t,project:n,logger:o}){let i=t.modules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${r} that could not be found on disk`);let a=bn(i,o),l={...a,...e},c=Tn({fileType:Se.MODULE,...jp.parse(l),steps:a.steps}),s=OT(c,a);if(s&&Object.keys(s).length===0){T.debug(`Skipping save for module ${r} since there are no changes`);return}let u=vs.stringify(c);Xr.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${_e(e.name)}.${St.MODULE}`;if(d=bs.join(bs.dirname(i),p),Xr.existsSync(d))throw new Error(`Module with name '${e.name}' already exists at path '${d}'`);Xr.renameSync(i,d)}qo(d||i,n.config)}async function Lc({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=_e(r),l=bs.join(o,`${a}.module.yaml`),c=eN(),{stepsToSave:s}=await Fe({stepLists:{steps:n}}),u={fileType:Se.MODULE,schemaVersion:ie,moduleId:c,name:r,description:e,enabled:t,steps:s.steps},d=vs.stringify(u);return Xr.writeFileSync(l,d,"utf-8"),qo(l,i.config),{moduleId:c,name:r,description:e,enabled:t,steps:n}}function bn(r,e){let t=Xr.readFileSync(r,"utf-8"),n=vs.parse(t);try{return Op.parse(n)}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic module`),o}}async function hr(r,e,t,n){let o=bn(r.fullFilePath,t),{resolvedSteps:i}=await wc({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:n,logger:t,callbacks:{onFetchModule:async({id:l})=>{let c=e.modules[l]?.fullFilePath;if(c)return bn(c,t)}}}),a={...o,steps:i};return n&&(n[r.id]=ZL(a)),a}async function Nc(r,e){let t={};return await Promise.all(Object.values(r.modules).map(async n=>{await hr(n,r,e,t)})),Array.from(Object.values(t))}async function DT({test:r,name:e,folder:t}){let n=await AT({test:r});if(Object.keys(n.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${_e(e)}.${St.TEST}`,a=Ko.join(t,i);return Mr.writeFileSync(a,n.test,"utf-8"),a}function Cm(r,e,t){let n=Ko.join(t.rootDir,r);if(!Mr.existsSync(n))throw new Error(`Test not found at path '${r}' in project '${t.rootDir}'`);let o=Mr.readFileSync(n,"utf-8"),i=Zi.parse(o),a,l;if(e.name&&e.name!==i.name){let p=`${_e(e.name)}.${St.TEST}`;if(a=Ko.join(Ko.dirname(r),p),l=Ko.join(t.rootDir,a),Mr.existsSync(l))throw new Error(`Test with name '${e.name}' already exists at path '${l}'`)}let c={...i,...e},s=pr.parse(c),u={fileType:Se.TEST,...pr.parse(s),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},d=Zi.stringify(u);return Mr.writeFileSync(n,d,"utf-8"),l&&Mr.renameSync(n,l),qo(n,t.config),{newRelativeTestPath:a}}function wt({relativeTestPath:r,steps:e,schemaVersion:t,project:n,forceSaveOnNoDiffs:o}){let i=Ko.join(n.rootDir,r);if(!Mr.existsSync(i))throw new Error(`Test not found at path '${r}' in project '${n.rootDir}'`);let a=Mr.readFileSync(i,"utf-8"),l=Zi.parse(a),c=pr.parse({...l,schemaVersion:t}),s=Le.array().or(NT.undefined()).parse(e.beforeSteps),u=Le.array().parse(e.steps),d=Le.array().or(NT.undefined()).parse(e.afterSteps),p=Tn({fileType:Se.TEST,...c,beforeSteps:s&&s.length>0?s:void 0,steps:u,afterSteps:d&&d.length>0?d:void 0}),m=tN(p,l);if(m&&Object.keys(m).length===0&&!o){T.debug(`Skipping save for test ${c.name} since there are no changes`);return}let g=Zi.stringify(p);Mr.writeFileSync(i,g,"utf-8"),T.debug(`Saving test ${c.name} to ${i}`),qo(i,n.config)}function Dc(r,e){let t=Ko.join(e.rootDir,r);if(!t)throw new Error(`Could not find test with path ${r} in Momentic project (${e.rootDir})`);let n;try{n=Mr.readFileSync(t,"utf8"),n=n.replace(/\r\n|\r/g,`
27
+ `)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=Zi.parse(n)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return Ot.parse(o)}function Yo(r,e,t){let n=t.project.rootDir,o;try{o=Mr.readFileSync(r,"utf-8")}catch(a){throw e.error({err:a,projectRoot:n},a.message),new Error(a.message)}let i=Zi.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${r} is missing steps`);return i}async function rt(r,e,t){let n=Yo(r,e,t),o;try{o=pr.parse(n)}catch(a){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await vT({rawSteps:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:l})=>{let c=t.modules[a]?.fullFilePath;if(c)return bn(c,l)}}});return i}import rN from"@dotenvx/dotenvx";import nN from"fs";import kT from"path";function kc(r,e){return(r.config.environments??[]).map(t=>Rs(t.name,r,e))}function FT(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),i=process.env[n];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):r}function oN(r){let{envVariables:e,project:t}=r;if(!e)return{};let n={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let l=FT(i);l&&(n[o]=l);continue}let a;try{a=nN.readFileSync(kT.resolve(t.rootDir,i.fromFile),"utf-8")}catch(l){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${l}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(l){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${l}`)}else n[o]=a}return Object.keys(n).length>0&&T.debug(n,"Set environment variables with interpolation from project configuration"),n}function iN(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=rN.config({path:kT.resolve(e.rootDir,t),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 Rs(r,e,t){let n=(e.config.environments??[]).find(c=>c.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);if(!n.baseUrl)throw new Error(`Browser environment ${r} does not have a baseUrl configured`);let o={[ht]:FT(n.baseUrl)},i=oN({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=iN({project:e,envFile:n.envFile,logger:t});return Object.assign(o,a),n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o,browser:n.browser}}import{existsSync as SN,readFileSync as yN,readdirSync as EN,writeFileSync as TN}from"fs";import{globSync as bN}from"glob";import Xo,{dirname as HT}from"path";import{cwd as Mm}from"process";import GT from"yaml";import{z as Ue}from"zod";import UT from"fs";import{globSync as aN}from"glob";import As from"path";import sN from"yaml";import{z as xm}from"zod";var BT=!1,_m=[`**/*.${St.TEST}`,`**/*.${St.MODULE}`],Im=xm.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Pm=50,lN=xm.object({fileType:xm.nativeEnum(Se)});function W(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},n=r.config.include??_m,o=Array.from(r.config.exclude??[]).concat(Ql),i=aN(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Pm,nodir:!0});for(let a of i){let l=cN(r.rootDir,a,t,e?yn:T);l&&(t.duplicateEntities[l.id]=l.paths)}return BT=!0,t}function cN(r,e,t,n){let o=As.join(r,e),i=uN(o,n);if(!i)return;let a=dN(i,o,n);if(!a)return;let l=lN.safeParse(a);if(l.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${l.error}`);return}let c=l.data.fileType,s=pN(o,n);if(!s)return;let u=mN(e,o,s);switch(c){case Se.TEST:try{return gN(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Se.MODULE:try{return hN(a,t,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 fN(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}default:{let d=c;return}}}function uN(r,e){try{return UT.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function dN(r,e,t){try{let n=sN.parse(r);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){t.warn(`Could not parse possible Momentic file at ${e}, skipping: ${n}`);return}}function pN(r,e){try{return UT.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function mN(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:As.sep,fullPathSegments:e.split(As.sep),relativePathSegments:r.split(As.sep),fileName:As.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function gN(r,e,t,n,o){let i=pr.parse(r),a;if(e.tests[i.id]){let l=e.tests[i.id].fullFilePath;a={id:i.id,paths:[l,n]}}return e.tests[i.id]={type:Se.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function hN(r,e,t,n,o){let i=Wt.parse(r),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,...t};let l=t.fileName.replace(`.${St.MODULE}`,"");return!BT&&_e(i.name)!==l&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${l}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function fN(r,e,t,n,o){let i=Np.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let l=t.fileName.replace(`.${St.TEST}`,"");return e.mobileTests[i.id]={type:Se.MOBILE_TEST,name:l,id:i.id,description:i.description??void 0,...t},a}var ea="momentic.config.yaml",zT="momentic.workspace.yaml",vN=Ue.object({projects:Ue.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),RN=Ue.union([Ue.string(),Ue.object({fromFile:Ue.string(),json:Ue.boolean().optional()})]),AN=Ue.object({name:Im,baseUrl:Ue.string().optional().describe("Optional for mobile tests"),envFile:Ue.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ue.record(Ue.string(),RN).optional(),inheritFromShell:Ue.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Lo.optional().describe("deprecated: use project-level configuration only")}),wN=Ue.object({postSave:Ue.string().optional()}),CN=Ue.object({name:Im,include:Ue.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ue.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ue.string().optional(),reporterDir:Ue.string().optional(),outputDir:Ue.string().optional(),retries:Ue.number().optional().describe("number of retries per test"),parallel:Ue.number().optional().describe("degree of parallelism"),environments:Ue.array(AN).optional(),gitMainBranch:Ue.string().optional(),gitProtectedBranches:Ue.string().array().optional(),ai:$p.optional(),browser:Lo.optional(),emulator:Lp.optional(),advanced:Wp.optional(),hooks:wN.optional()});function VT(r,e){let t;try{t=yN(r,"utf-8")}catch(o){T.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=GT.parse(t),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){T.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Om(r){let e=VT(r,"project configuration");if(e!==void 0)try{return CN.parse(e)}catch(t){T.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function xN(r){let e=VT(r,"workspace configuration");if(e!==void 0)try{return vN.parse(e)}catch(t){T.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function _N(){let r=[],e=Mm(),t=Xo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Xo.basename(e);if(Jl.includes(i))return T.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of EN(e))if(a.endsWith(ea)){let l=Xo.join(e,a),c=Om(l);c&&r.push({configFilePath:l,config:c,rootDir:HT(l)})}if(r.length)return r;if(e=Xo.dirname(e),e===t)break}return r}function Et(r={}){let{configFilePath:e,nameFilter:t}=r,n=Lm(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
28
+ ${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return T.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}function IN(r){let e=xN(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ea}`)),n=bN(t,{absolute:!1,cwd:Mm(),dotRelative:!1,maxDepth:Pm,nodir:!0}),o=[];for(let i of n){let a=Xo.join(Mm(),i),l=Om(a);l&&o.push({configFilePath:a,config:l,rootDir:HT(a)})}return o}function Lm(r){if(r){r=Xo.resolve(r);let t=Om(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Xo.dirname(r)}]}if(SN(zT)){let t=IN(zT);if(t)return t}return _N()}function ta(r,e){let t=GT.stringify(r);TN(e,t)}import ra from"fs";import Nm from"path";import{z as Dm}from"zod";var jT="golden/visual-diff",$T="reports",WT="test-results";var PN=Dm.object({width:Dm.number(),height:Dm.number()}),na=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let n=Nm.join(e.rootDir,e.config.goldenFileDir??jT);this.defaultGoldenScreenshotDir=n,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,n){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Nm.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ra.mkdirSync(Nm.dirname(o),{recursive:!0}),ra.writeFileSync(o,n.buffer),ra.writeFileSync(i,JSON.stringify({width:n.width,height:n.height})),{buffer:Buffer.from(n.buffer),width:n.width,height:n.height};if(ra.existsSync(o)){let a=ra.readFileSync(o),l=PN.parse(JSON.parse(ra.readFileSync(i,"utf-8")));return{buffer:a,width:l.width,height:l.height}}else throw new C("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var Jr=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import{execFile as MN}from"node:child_process";import{promisify as ON}from"node:util";import LN from"simple-git";var Be=LN(),qT=ON(MN);async function NN(r){let e=await ze(r,Be.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
29
+ `)){let o=n.indexOf("=");if(o===-1)continue;let i=n.slice(0,o),a=n.slice(o+1).trim();t[i]=a}return t}async function DN(r,e,t){try{let o=t["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 qT("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),l=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(l?.[1])return l[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await qT("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function kN(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return DN(r,e,t);if(o)return}catch{}}function Fc(r){if(r.startsWith("git@")){let e=r.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let n=t[0],o=t[1];return`${n}/${o}`}}}else if(r.startsWith("http")||r.startsWith("https")){let t=new URL(r).pathname.split("/").filter(Boolean);if(t.length>=2){let n=t[0],o=t[1].replace(".git","");return`${n}/${o}`}}}async function ze(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function FN(){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 UN(r){let[e,t,n]=await Promise.all([ze(r,Be.show(["--no-patch","--format=%ci"])),ze(r,Be.show(["-s","--pretty=%B"])),ze(r,Be.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{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:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function BN(r){let[e,t,n]=await Promise.all([ze(r,Be.listRemote(["--get-url","origin"])),ze(r,Be.show(["-s","--pretty=%B"])),ze(r,Be.show(["-s","--pretty=%an"]))]);return{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:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function zN(r){let[e,t,n,o]=await Promise.all([ze(r,Be.show(["--no-patch","--format=%ci"])),ze(r,Be.listRemote(["--get-url","origin"])),ze(r,Be.show(["-s","--pretty=%B"])),ze(r,Be.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),l=t?Fc(t):void 0;return{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:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function HN(r){let[e,t,n]=await Promise.all([ze(r,Be.show(["--no-patch","--format=%ci"])),ze(r,Be.show(["-s","--pretty=%B"])),ze(r,Be.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Fc(o):void 0;return{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:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function GN(r){let[e,t,n]=await Promise.all([ze(r,Be.show(["--no-patch","--format=%ci"])),ze(r,Be.show(["-s","--pretty=%B"])),ze(r,Be.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),l=o?Fc(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?l:void 0,gitlabProjectPath:a?l:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function VN(r,e){let[t,n,o,i,a,l,c,s,u]=await Promise.all([ze(r,Be.revparse(["HEAD"])),ze(r,Be.revparse(["--short","HEAD"])),ze(r,Be.revparse(["--abbrev-ref","HEAD"])),ze(r,Be.listRemote(["--get-url","origin"])),ze(r,Be.show(["--no-patch","--format=%ci"])),ze(r,Be.show(["-s","--pretty=%B"])),ze(r,Be.show(["-s","--pretty=%an"])),e?ze(r,Be.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),NN(r)]),d=s?await ze(r,Be.show(["--no-patch","--format=%ci",s])):void 0,p=i?.includes("github.com"),m=i?.includes("gitlab.com"),g=i?Fc(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,S=await kN(r,i,u)??E??void 0;return r.debug({userUsername:S,gitLocalUserLogin:E,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:l,gitCommitAuthorName:c,gitLocalUsername:S,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?g:void 0,gitlabProjectPath:m?g:void 0,pipelineId:void 0}}async function jN(){let r=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:r?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:r?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function $N(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function km(r,e){let t=FN();if(!t)return VN(r,e);switch(t){case"GithubActions":return UN(r);case"GitlabCI":return BN(r);case"CircleCI":return zN(r);case"Buildkite":return HN(r);case"AzureDevOps":return GN(r);case"GCPCloudBuild":return jN()}}async function WN(r,e,t,n){let o=n;if(!n.gitCommitSha)return o;if(n.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp))try{let i=await e.getMergeBaseCommitFromGitlab(t,n.gitMainBranch,n.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}catch(i){r.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(t,n.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}catch(i){r.warn({err:i},"Failed to get commit from Gitlab")}if(n.gitBranchName&&n.gitBranchName===n.gitMainBranch&&!o.mergedGitBranchName)try{let i=await e.getMergedBranchFromGitlab(t,n.gitBranchName??"",n.gitCommitSha);i.mergedBranch&&(o={...o,mergedGitBranchName:i.mergedBranch})}catch(i){r.warn({err:i},"Failed to get merged branch from Gitlab")}return o}async function qN(r,e,t,n,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp))try{let a=await e.getMergeBaseCommitFromGithub(t,n,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}catch(a){r.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(t,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){r.warn({err:a},"Failed to get commit from GitHub")}if(o.gitBranchName&&o.gitBranchName===o.gitMainBranch&&!i.mergedGitBranchName)try{let a=await e.getMergedBranchFromGithub(t,n,o.gitBranchName??"",o.gitCommitSha);a.mergedBranch&&(i={...i,mergedGitBranchName:a.mergedBranch})}catch(a){r.warn({err:a},"Failed to get merged branch from GitHub")}return i}async function KN(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await qN(r,e,n,o,t)}else if(t.gitlabProjectPath)return await WN(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Qn(r,e,t){let n=await $N(t),o=await km(r,n.gitMainBranch),i={...n,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===n.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await KN(r,e,i);return{...n,...o,...a}}import wie from"yaml";import{randomUUID as YN}from"crypto";import vn from"fs";import Jo from"path";var KT={status:(r,e)=>{if(r.status===e.status)return r.status;if(r.status==="FAILED"||e.status==="FAILED")return"FAILED";if(r.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(r.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(r.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(r.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${r.status} and ${e.status}`)},startedAt:(r,e)=>r.startedAt<e.startedAt?r.startedAt:e.startedAt,updatedAt:(r,e)=>r.updatedAt>e.updatedAt?r.updatedAt:e.updatedAt,finishedAt:(r,e)=>!r.finishedAt||!e.finishedAt?new Date:r.finishedAt>e.finishedAt?r.finishedAt:e.finishedAt,gitCommitTimestamp:(r,e)=>{if(!(!r&&!e)){if(!r.gitCommitTimestamp||!e.gitCommitTimestamp||r.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${r.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return r.gitCommitTimestamp}},pipelineId:(r,e)=>r.pipelineId===e.pipelineId?r.pipelineId:!r.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&r.pipelineId?r.pipelineId:r.startedAt<e.startedAt?e.pipelineId:r.pipelineId,labels:(r,e)=>{let t=new Set([...r.labels??[],...e.labels??[]]);return Array.from(t)}};function XN(r,e,t){if(KT[t]){let i=KT[t];return i(r,e)}let n=r[t],o=e[t];if(n!==o)throw new Error(`Metadata values for key "${t}" do not match: "${n}" vs "${o}"`);return n}var YT=new Set([".DS_Store","__MACOSX"]);function XT(r,e,t){let n=YN(),o=r.child({runGroupId:n});vn.rmSync(e,{recursive:!0,force:!0});let i=vn.readdirSync(t).filter(s=>!YT.has(s)).map(s=>Jo.join(t,s));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);vn.mkdirSync(e,{recursive:!0});let a=Jo.join(i[0],"metadata.json"),l={...cs.parse(JSON.parse(vn.readFileSync(a,"utf-8"))),id:n};for(let s of i){let u=Jo.join(s,"runs");if(!vn.existsSync(u))continue;let d=vn.readdirSync(u);for(let g of d){if(YT.has(g))continue;let h=Jo.join(u,g),f=Jo.join(e,"runs",g);vn.cpSync(h,f,{recursive:!0})}let p=Jo.join(s,"metadata.json"),m=cs.parse(JSON.parse(vn.readFileSync(p,"utf-8")));o.info({oldRunGroupId:m.id},"Merging metadata from run groups");for(let g in m){if(g==="id")continue;let h=g;l[h]=XN(l,m,h)}}let c=Jo.join(e,"metadata.json");vn.writeFileSync(c,JSON.stringify(l,null,2))}import JT from"adm-zip";import Fm from"fs";import Uc from"path";function JN(r){let e=new JT,t=Uc.join(r,"metadata.json"),n=cs.parse(JSON.parse(Fm.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Fm.readdirSync(Uc.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new JT(Uc.join(r,"runs",o));for(let l of a.getEntries())l.isDirectory||e.addFile(Uc.join("runs",i,l.entryName),l.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Bc(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Fm.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new dc(e);try{let{runGroupId:i,buffer:a}=JN(n),l=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${l}`;t.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",t.error(`Failed to upload test results: ${a}.`);return}}import QN from"adm-zip";import $t from"fs";import Or from"path";var ws=class r{constructor(e){this.filePath=e;$t.rmSync(this.filePath,{recursive:!0,force:!0}),$t.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Or.join(this.filePath,e))}mkdir(e){$t.mkdirSync(Or.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Or.join(this.filePath,e);if($t.existsSync(t))return $t.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Or.join(this.filePath,t);try{$t.writeFileSync(o,n)}catch{}}createRunArchive(e){return new Um(Or.join(this.filePath,"runs"),e)}},Um=class{constructor(e,t){this.filePath=e;this.tempPath=Or.join(e,`.${t}`),this.finalPath=Or.join(e,`${t}.zip`),$t.rmSync(this.tempPath,{recursive:!0,force:!0}),$t.rmSync(this.finalPath,{recursive:!0,force:!0}),$t.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Or.join(this.tempPath,e);if($t.existsSync(t))return $t.readFileSync(t)}mkdir(e){$t.mkdirSync(Or.join(this.tempPath,e),{recursive:!0})}cd(e){return new ws(Or.join(this.tempPath,e))}storeFile(e){let{name:t,contents:n}=e,o=Or.join(this.tempPath,t);$t.writeFileSync(o,n)}close(){let e=new QN;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();$t.writeFileSync(this.finalPath,t),$t.rmSync(this.tempPath,{recursive:!0,force:!0})}};import S1 from"http";import y1 from"path";import{Server as Qz}from"socket.io";var ZN=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{e.info({sessionId:n},"Cancel event received");let o=t.getSession(n);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},QT={event:"cancel",createHandler:ZN};var eD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let s=(await l.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:s},"Fetched a11y tree from the browser"),i({a11yTree:s})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),i({err:c.message})}}},ZT={event:"fetchA11yTree",createHandler:eD};var tD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async(o,i)=>{let a=t.getSession(n);if(!a)throw new Error("No active session found");a.controller.setOpen();let l=a.controller.browser;try{let c=await l.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})}}},eb={event:"fetchDom",createHandler:tD};var rD=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return o=>{e.info({sessionId:n,reason:o},`Disconnect event received (${o})`),t.removeSession(n,e)}},tb={event:"disconnect",createHandler:rD};function Qr(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=nD(t);oD(e,n,o);let i=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await iD(i,e,n,o)}catch(a){r.logger.error({result:r.result,err:a},"Error hoisting scalar result metadata")}})())}function nD(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.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"})(e)}if(t)break}let n=r[r.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:t,lastMetadata:o}}function oD(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function iD(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeSnapshot=t.beforeSnapshot),n&&(e.afterSnapshot=n.afterSnapshot)}import Cs from"os";import aD from"v8";var rb,Zr,sD=Cs.platform(),lD=Cs.cpus().map(r=>({model:r.model,speed:r.speed})).reduce((r,e)=>(r[e.model]={speed:e.speed},r.totalCores=(r.totalCores??0)+1,r),{});function nb(r){if(Sn)return;let e=()=>{try{let t=!1,n=cD(),o=uD();n.freeMemory<1e6&&(t=!0);let i=aD.getHeapStatistics(),a=i.used_heap_size,l=i.heap_size_limit;a/l>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:i},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:lD,platform:sD}}function cD(){let r=Cs.totalmem(),e=Cs.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function uD(){let r=Cs.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of r)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!Zr)return Zr=t,null;let n={user:t.user-Zr.user,nice:t.nice-Zr.nice,sys:t.sys-Zr.sys,idle:t.idle-Zr.idle,irq:t.irq-Zr.irq,total:t.total-Zr.total};return rb={measurementTime:e,intervalMs:e-Zr.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},Zr=t,rb}import{randomUUID as bD}from"crypto";import{faker as dD}from"@faker-js/faker";import pD from"assert";import mD from"axios";import*as gD from"child_process";import hD from"moment";import*as fD from"otpauth";import SD from"pg";async function ob(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Gl(n,e);t.push(...o)}),t}function yD(r,e){if(!r&&!e)return;let t;if(r){let{url:o,options:i}=r;t=new Request(o,i)}let n;if(e){let{body:o,options:i}=e;n=new Response(o??null,i)}return{request:t,response:n}}async function ED(r,e){switch(r){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let t=[];return e.headers.forEach((o,i)=>{t.push([i,o])}),{status:e.status,headers:t,body:await e.text()}}else throw new Error("Result is not a Response object")}}var TD=Object.getPrototypeOf(async function(){}).constructor;async function ib(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:l}=e.bindings,c=e.tools,s={},u=(y,A)=>{o[y]=A,s[y]=A},d={},p=(y,A)=>{o[y]=A,d[y]=A},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 TD("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(mD,hD,c.fakerInstance??dD,pD,SD,m,g,fD,gD,ob,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,A=>c.sms.send(A),A=>c.sms.fetchLatest(A),c.email,c.sms,c.ai,yD(a,l),...Object.values(i??{}))),f=!0,E,S;try{let y=await z(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await ED(e.options.responseSerialization??"RAW",y)}catch(y){t.error({err:y,env:o,evalCode:n},`[${r}] Error executing code: ${y}`),f=!1,y instanceof qn?S=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:S=y instanceof Error?y.message:`${y}`}return{result:E,variableUpdates:s,persistentVariableUpdates:d,success:f,error:S}}async function ab({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=Vn,disallowVariableUpdates:l,additionalBindings:c,responseSerialization:s,mock:u}){let d=bD(),p=await ib(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:l,responseSerialization:s},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return T.debug(`[${d}] Got execution result: ${JSON.stringify(p)}`),p}import{createHmac as vD,randomUUID as RD}from"crypto";import AD from"fetch-retry";var wD=AD(global.fetch,{retries:3,retryOn:function(r,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(r){return Math.pow(2,r)*500}}),sb=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,lb=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function cb({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=Vn,retries:i=2,signal:a,logger:l,additionalBindings:c,disallowVariableUpdates:s,responseSerialization:u,mock:d}){if(!sb)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,m,g=0;if(!lb)throw new Error("Missing lambda auth secret.");let h=vD("sha256",lb).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let E={id:RD(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:s,responseSerialization:u};try{if(p=await z(wD(sb,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{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(S){m=S}}if(m)throw l.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=HS.parse(await p.json())}catch(E){throw new Error(`Code evaluation server returned invalid response: ${E}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Zn(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await cb(r);else if(r.localTools)e=await ab({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
30
30
  ${e.error}
31
31
  Code received:
32
- ${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as cD}from"lodash-es";async function er(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=$n,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await eo({orgId:e,code:m,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new C("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 Fc(r){return ab(r)}async function ab({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await er({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await ab({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function sb(r,e){for(let{path:t,original:n}of e)cD(r,t,n)}import uD from"fetch-retry";var ose=process.env.MAILINATOR_API_KEY,ise=uD(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{hostname as SD}from"os";async function lb(r){let{command:e,tracer:t,timeoutMs:n,targetingWrapper:o,disableCache:i,fixtures:a}=r,{logger:l,abortSignal:c}=a;if(e.target&&!Dn(e.target))throw new Error("Element assertion with x/y is not supported yet");let s=pD(e.assertion),u=ff(e.cache)?e.cache:void 0,d=Date.now(),p=0,m,g=500;for(;p<2||Date.now()-d<n;){p++,p>1&&await Z(g,c),c?.throwIfAborted();try{let{elementInteractedDisplayString:h,result:f,thoughts:y}=await o({ctx:a.ctx,tracer:t,command:e,target:e.target,cache:u?.target,action:async S=>dD(S.locator,r),options:{...e,disableCache:i,disableGlobalLocatorRedirect:!0,source:Lo(e),allowZeroOpacityOverride:!0,targetName:"target"}});if(m={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:h,thoughts:y},!f.success){m={...f,thoughts:y},g=Math.min(g*2,1e4);continue}return m}catch(h){if(c?.throwIfAborted(),s)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`,err:void 0,data:void 0};if(l.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof C)||h.reason!="ActionFailureError")throw h;m={success:!1,err:h,data:void 0,thoughts:void 0}}}if(!m)throw new Error(`Failed to evaluate manual element assertion in ${n}ms.`);return m}async function dD(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Je(c,500,!0)},!Uc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Je(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Uc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Gr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:Gr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:Gr*1e3});break}case"FOCUSED":{o=await r.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"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?dm[n.condition]:pm[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Uc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Uc(c,n.value,n.operation,!!n.negated)){let s=n.negated?gr[n.operation]:hr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${s}`):i=new C("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Uc(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function pD(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function cb(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as mD}from"jimp";async function As(r,e){let t=await r.screenshot(e),n=await mD.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as ub}from"jimp";import Fm from"jpeg-js";import gD from"pixelmatch";async function db({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Dn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async $=>As(o,{locator:$.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,targetName:"target"}})).result:s=await As(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let Y=`${s.width}x${s.height}`,$=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${Y}) does not match saved screenshot dimensions (${$}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await ub.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await ub.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,y=g.width*g.height,S=Math.abs(p.height-g.height),T=Math.abs(p.width-g.width);if(f>y){let Y=d.cover({w:g.width,h:g.height});s.buffer=await Y.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(y>f){let Y=m.cover({w:p.width,h:p.height});u.buffer=await Y.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},R=t.threshold??.1,x=gD(Fm.decode(u.buffer).data,Fm.decode(s.buffer).data,A.data,s.width,s.height,{threshold:R,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,_=x>R*100,P=`Visual diff of ${x.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${R*100}%.`;if(h&&(P+=` The ${h} screenshot was cropped since it was taller by ${S} pixels and wider by ${T} pixels.`),_)throw new C("ActionFailureError",P);return{fail:_,thoughts:P,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Fm.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hD=3e4;async function pb({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??hD/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let l=a.toString(),c;if(qi(r.url)&&(c=r.url),t&&Ki(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await H((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var fD=5e3;async function Bc({timeout:r=Gr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await mb(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await Z(l,e.signal),l=Math.min(Math.floor(l*1.5),fD);else return i}return i=await mb(e),i}async function mb({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(gb,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(gb,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?gr.CONTAINS:hr.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}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"})(r.type)}}function gb({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var Um=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:l}=r.fixtures,c=l.browser,{orgId:s,runId:u}=r.inputs,d=l.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),n.info(hm({json:{inputs:t,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||"",y=await er({orgId:s,s:f,context:o,logger:n,localTools:a,signal:d});h={orgId:s,cacheKeys:[y,...Object.entries(t).map(([T,A])=>`${T}:${A}`)]},n.info({original:f,keyParams:h},"Module cache key params");let S=Date.now();for(;Date.now()-S<gy;){d?.throwIfAborted();let T=await i.getCacheResult(h);if(T){n.info({cacheResult:Je(T,1e3,!0)},"Got result from module execution cache"),p=zc(e,t,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(T),m=!0;break}else n.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let A=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${SD()};runId:${u}`},d);if(A.acquired){g=A.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 Z(2500+Math.random()*1e4,d)}}try{if(!p)p=await yD(r);else if(e.autoAuth){let f=Bl.safeParse(p.data);if(!f.success)throw new C("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 y=!1,S=e.advanced?.cacheInvalidation;if(S&&S.type==="PAGE_CHECK"){let T={type:"CONTENT",value:S.substring},A=await Bc({timeout:Gr,assertion:T,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});A.success?n.debug({invalResult:A},"Cached result still valid after page check, continuing..."):(n.info({invalResult:A},"Invalidating cached result due to page check failure"),y=!0)}if(h&&y)return await i.deleteCacheResult(h),Um(r)}}finally{try{g!==void 0&&!m&&p?.status==="SUCCESS"&&await ED({step:e,result:p,browser:l.browser,cacheKeyPrefix:g,logger:n,storage:i})}finally{g!==void 0&&await i.releaseCacheLock(g)}}return p},yD=async r=>{let{step:e,tracer:t}=r.moduleParams,n=zc(e,r.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,Qr({asyncTasks:r.work.asyncTasks,nestedResults:a,result:n,logger:r.fixtures.logger}),n};function zc(r,e,t){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function hb({orgId:r,step:e,context:t,logger:n,flagStore:o,codeEvalTools:i,signal:a}){let l={};try{for(let c of e.parameters??[]){let s=e.inputs?.[c]??e.defaultParameters?.[c];if(!s){n.warn(`No value or default found for parameter '${c}' that is required by module '${e.name}'`);continue}l[c]=await eo({orgId:r,code:s,fragment:!0,context:t,logger:n,localTools:i,signal:a})}return l}catch(c){throw a?.throwIfAborted(),new C("UserConfigurationError",`Failed to evaluate module inputs: ${c}`)}}async function ED({step:r,result:e,browser:t,cacheKeyPrefix:n,logger:o,storage:i}){let a=r.cacheConfig?.cacheExpiryMs;(!a||a===Jy)&&(a=r.defaultCacheTtl??Qy);let l;r.autoAuth?l=JSON.stringify(await t.saveAuthState()):e.data!==void 0?l=JSON.stringify(e.data):l='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:hm({json:l,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:l,keyPrefix:n,ttlMs:a})}async function Qo(r,e,t){return TD(r,e,t)}async function TD(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",l;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(l="Step aborted by user.",a="CANCELLED"):o instanceof C?l=`${o}`:l=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let c=zc(r,{},"FAILED");return c.message=l,c.startedAt=n,c.finishedAt=i,c}return{...Ac(r),startedAt:n,finishedAt:i,status:a,data:null,message:l,results:[]}}}async function oa(r,e){let t=!1;try{return r&&!r.state.failureRecoveryDisabled&&(r.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{r&&t&&(r.state.failureRecoveryDisabled=void 0)}}import{randomUUID as fb}from"crypto";var Hc=async r=>{let{step:e,tracer:t}=r.presetParams,{logger:n,controller:o,context:i}=r.fixtures,{collectDebugData:a}=r.options,{testMetadata:l}=r.inputs,c=e.command.type,s=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u=o.browser.url(),d=new Date,p,m=fb(),g=fb();if(a)try{if(p=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let T=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:s,snapshotId:m,html:T})}}catch(T){s.debug({err:T},"Failed to take before screenshot, continuing...")}let h,f,y,S=Dl();try{let T=await o.executePresetCommand(S,t,e.command,i,l?.advanced.disableAICaching??!1);T.beforeScreenshotOverride&&(p=T.beforeScreenshotOverride),y=T.afterScreenshotOverride;let A=new Date,R=o.browser.url();f={beforeUrl:u,afterUrl:R,startedAt:d,finishedAt:A,viewport:o.browser.getViewport(),status:T.fail?"FAILED":"SUCCESS",elementInteracted:T.elementInteracted},h={...e,message:T.thoughts??"Successfully executed preset action.",beforeUrl:u,afterUrl:R,finishedAt:A,startedAt:d,status:T.fail?"FAILED":"SUCCESS",data:T.data,results:[f],details:S.details},"assertion"in e.command&&(h.message=T.thoughts||"Assertion passed.")}catch(T){s.error({message:T.message,stack:T.stack},`Failed executing preset step ${Tn(e.command)}`);let A=o.browser.url(),R=new Date,w=T instanceof Error?T.message:`${T}`;f={beforeUrl:u,afterUrl:A,startedAt:d,finishedAt:R,viewport:o.browser.getViewport(),status:T instanceof DOMException&&T.name==="AbortError"?"CANCELLED":"FAILED",message:w},h={...e,startedAt:d,finishedAt:R,beforeUrl:u,afterUrl:A,status:T instanceof DOMException&&T.name==="AbortError"?"CANCELLED":"FAILED",message:w,failureReason:T instanceof C?T.reason:void 0,results:[f],details:S.details}}if(a)try{if(y||(y=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let T=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:s,snapshotId:g,html:T})}}catch(T){s.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 f.beforeSnapshot=m,h.beforeSnapshot=m,f.afterSnapshot=g,h.afterSnapshot=g,p&&t.attachBeforeScreenshot({logger:s,snapshotId:m,screenshot:p}),y&&t.attachAfterScreenshot({logger:s,snapshotId:g,screenshot:y}),h};async function Sb({codePath:r,screenshotBuff:e,storage:t,logger:n}){if(e)try{let o=await t.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:r},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:r},"Failed to save screenshot for debugging")}}async function en({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var bD=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function yb({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(bD.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await Z(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Wo(m,o)&&m!==r&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}var Eb="MOMENTIC_RUN_ID",Tb="FINAL_SCREENSHOT_URL";import{cloneDeep as OD}from"lodash-es";async function bb(r){let{step:e,tracer:t}=r.conditionalParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=Ac(e),l=e.elseSteps,c=!0,s=[],u,d=Dl();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let y=e.blocks[f];try{let S=await Hc({...r,presetParams:{tracer:t,step:y.assertion}});s.push(S),n.info(`Condition ${f} resolved to true, executing the corresponding ${y.steps.length} steps`),c=!1,l=y.steps,u=S}catch(S){n.info({err:S},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(l)c&&n.info("No conditions resolved to true, executing the else block steps");else return n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:s[s.length-1]?.data,message:s[s.length-1]?.message,results:[],finishedAt:new Date,details:d.details};n.info(`Executing ${l.length} steps in the selected conditional block`);let p=await r.conditionalParams.tracer.startSubSteps(),m=await r.executeStepList({...r,listParams:{steps:l,containerName:"conditional block",tracer:p}}),h={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return Qr({asyncTasks:r.work.asyncTasks,nestedResults:[...s,...m.results],result:h,logger:n}),h}import{randomUUID as vb}from"crypto";var Rb=async r=>{let{tracer:e}=r.aiStepParams,{controller:t,logger:n}=r.fixtures;await t.browser.waitForDOMStability();let o=await t.browser.screenshot({}),i=await vD(r);i.finishedAt=new Date,Qr({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await t.browser.screenshot({}),l=vb();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:n,snapshotId:l,screenshot:o});let c=vb();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},vD=async r=>{let{step:e,tracer:t}=r.aiStepParams,{controller:n,context:o,logger:i}=r.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 C("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await t.startSubSteps(),{status:s}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=s,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let s=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=s?"CANCELLED":"FAILED"}return a};import{randomUUID as Bm}from"crypto";var Ab=15,RD=7,wb=async r=>{let{tracer:e}=r.aiStepParams,{logger:t,controller:n}=r.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await AD(r);i.finishedAt=new Date,Qr({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await n.browser.screenshot({quality:75}),l=Bm();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:t,snapshotId:l,screenshot:o});let c=Bm();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:t,snapshotId:c,screenshot:a}),i},AD=async r=>{let{step:e,tracer:t}=r.aiStepParams,{testMetadata:n,orgId:o}=r.inputs,{controller:i,context:a,logger:l,codeEvalTools:c}=r.fixtures,{step:s}=r.callbacks,u=`${e.id}-${Date.now()}`,d=l.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await er({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=[],y=0,S=0,T,A;for(;;){if(y>Ab)return p.message=`Exceeded the maximum number of commands allowed per AI step (${Ab})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let R=await i.evaluateAiAction({goal:m,startingScreenshot:y===0?void 0:h,history:f,logger:d,langfuseSessionId:u,lastError:A}),{evaluation:w,reasoning:x,summary:_}=R;d.info(R,"Got AI evaluation");let P=p.results[y-1]?.id;switch(w.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,p.status="SUCCESS",P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:`${_}
33
- ${x}`}),p;case"RIGHT_TRACK":{T=void 0,y===0?s.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:x}):P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"SUCCESS",message:x});break}case"WRONG_TRACK":{if(T=`${x}
34
- ${w.feedback}`,S++,S>=RD)return p.message=`Our AI agent requires additional information to achieve this goal:
32
+ ${r.code}`;throw r.logger.error({err:e.error,code:r.code,env:r.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await r.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,n]of Object.entries(e.persistentVariableUpdates))r.context.setVariable(t,n)}return e.result}import{set as CD}from"lodash-es";async function er(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:l=Vn,allowUndefined:c=!1}=r,s=/{{(.*?)}}/g,u=t.matchAll(s),d=t;for(let p of u){if(p.length<2)continue;let m=p[1].trim(),g;try{g=await Zn({orgId:e,code:m,fragment:!0,context:n,timeoutMs:l,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(g===void 0&&!c)throw new C("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 zc(r){return ub(r)}async function ub({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let l in r){if(e.includes(l))continue;let c=!1;if(t)if(t.includes(l))c=!0;else continue;let s=r[l],u=[...o,l];if(typeof s=="string"&&s.includes("{{")){let d=await er({s,context:n,...a});if(s===d)continue;i.push({path:u,original:s}),r[l]=d}else typeof s=="object"&&s!==null&&!Array.isArray(s)&&await ub({obj:s,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function db(r,e){for(let{path:t,original:n}of e)CD(r,t,n)}import xD from"fetch-retry";var Tse=process.env.MAILINATOR_API_KEY,bse=xD(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import{hostname as DD}from"os";import{cloneDeep as _D}from"lodash-es";async function mb(r){let{command:e,timeoutMs:t,fixtures:n}=r,{logger:o,abortSignal:i}=n,a=Ef(e.cache)?e.cache:void 0,l=Date.now(),c=0,s,u=500,d=!1;for(;c<2||Date.now()-l<t;){c++,c>1&&await Z(u,i),i?.throwIfAborted();let{result:p,updatedCache:m,elementWasFound:g}=await pb({cacheToUse:a,params:r});if(s=p,d=g,p.success){m?.target&&Ho({cmd:e,key:"target",newTarget:m?.target,logger:o});break}m?.target?.memory&&a?.target&&(a.target.memory=m.target.memory),u=Math.min(u*2,1e4)}if(!s)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(i?.throwIfAborted(),!s.success&&a?.target&&ml(a.target)){let p=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:m,updatedCache:g}=await pb({cacheToUse:p,params:r});s=m,m.success&&g?.target&&Ho({cmd:e,key:"target",newTarget:g.target,logger:o})}return s.success&&a?.target&&!d&&gf(a.target),s}async function pb({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:l}=o;if(t.target&&!Ln(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=PD(t.assertion),s,u=!1,d=_D(r);try{let{elementInteractedDisplayString:p,result:m,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>ID(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:Oo(t),targetName:"target"}});return s={success:m.success,data:m.data,err:m.err,elementInteractedDisplayString:p,thoughts:g},u=!0,m.success||(l.warn({aiThoughts:g,elementString:p,err:m.err},"Element check found an element but failed"),s={...m,thoughts:g}),{result:s,elementWasFound:u,updatedCache:d}}catch(p){if(c)return s={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:s,elementWasFound:u,updatedCache:d};if(!(p instanceof C)||p.reason!="ActionFailureError")throw p;return s={success:!1,err:p,data:void 0,thoughts:void 0},l.warn({err:p},"Element check did not find an element and failed"),{result:s,elementWasFound:u,updatedCache:d}}}async function ID(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Qe(c,500,!0)},!Hc(c,n.value,n.operation,!!n.negated)){let s=n.negated?mr[n.operation]:gr[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${s} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Qe(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(s){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${s}`),o=!1;break}if(!Hc(c,n.value,n.operation,!!n.negated)){let s=n.negated?mr[n.operation]:gr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${s}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${s} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(s,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(m=>setTimeout(m,250));let p=s.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},Gr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:Gr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:Gr*1e3});break}case"FOCUSED":{o=await r.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"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?gm[n.condition]:hm[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(s=>s.tagName);if(!Hc(c,n.value,n.operation,!!n.negated)){let s=n.negated?mr[n.operation]:gr[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${s} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((s,u)=>window.getComputedStyle(s).getPropertyValue(u),n.property);if(!Hc(c,n.value,n.operation,!!n.negated)){let s=n.negated?mr[n.operation]:gr[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${s}`):i=new C("AssertionFailureError",`The style property ${n.property} ${s} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Hc(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function PD(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function gb(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as MD}from"jimp";async function xs(r,e){let t=await r.screenshot(e),n=await MD.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as hb}from"jimp";import Bm from"jpeg-js";import OD from"pixelmatch";async function fb({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:l}){if(t.target&&!Ln(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let c={clearHighlights:!0,hideCaret:!0},s;t.target?.elementDescriptor?s=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async $=>xs(o,{locator:$.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:s=await xs(o,c);let u=await l.prepareGoldenScreenshotForComparison(a,t,s);if((s.height!==u.height||s.width!==u.width)&&a.warn({currHeight:s.height,currWidth:s.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(s.height-u.height)>10||Math.abs(s.width-u.width)>10){let K=`${s.width}x${s.height}`,$=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${K}) does not match saved screenshot dimensions (${$}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:s.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await hb.fromBuffer(s.buffer),p={width:s.width,height:s.height},m=await hb.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=p.width*p.height,E=g.width*g.height,S=Math.abs(p.height-g.height),y=Math.abs(p.width-g.width);if(f>E){let K=d.cover({w:g.width,h:g.height});s.buffer=await K.getBuffer("image/jpeg"),h="current",s.width=g.width,s.height=g.height}else if(E>f){let K=m.cover({w:p.width,h:p.height});u.buffer=await K.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(s.width*s.height*4),width:s.width,height:s.height},R=t.threshold??.1,x=OD(Bm.decode(u.buffer).data,Bm.decode(s.buffer).data,A.data,s.width,s.height,{threshold:R,diffColorAlt:[0,255,0]})/(s.width*s.height)*100,_=x>R*100,M=`Visual diff of ${x.toFixed(2)}% detected, which is ${_?"over":"under"} the threshold of ${R*100}%.`;if(h&&(M+=` The ${h} screenshot was cropped since it was taller by ${S} pixels and wider by ${y} pixels.`),_)throw new C("ActionFailureError",M);return{fail:_,thoughts:M,beforeScreenshotOverride:s.buffer,afterScreenshotOverride:Bm.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var LD=3e4;async function Sb({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??LD/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,g])=>m&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,g])=>m&&g).forEach(([m,g])=>{a.append(m,g)});let l=a.toString(),c;if(qi(r.url)&&(c=r.url),t&&Ki(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:l,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await z((async()=>{let m=l?`${c}?${l}`:c;try{return await n(m,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let m;try{m=await u.text()}catch(g){m=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${m}`)}let d={};u.headers.forEach((m,g)=>{d[g]=m});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var ND=5e3;async function Gc({timeout:r=Gr,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,l=500;for(;a-t<n;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();i=await yb(e),a=Date.now();let s=a-c;if(s>1e3&&e.logger.warn({pageAssertDuration:s},"Page assertion took longer than expected"),!i.success)await Z(l,e.signal),l=Math.min(Math.floor(l*1.5),ND);else return i}return i=await yb(e),i}async function yb({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":{let o,i=!1,a;try{let l;if(t){let c=await e.evaluateFunctionInAllFrames(Eb,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(s=>s.evaluation):c.some(s=>s.evaluation),l=c.find(s=>s.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:l}=await e.evaluateFunctionInPage(Eb,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?mr.CONTAINS:gr.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=l}}catch(l){a=new C("AssertionFailureError",`Failed to evaluate page content assertion: ${l instanceof Error?l.message:`${l}`}`)}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"})(r.type)}}function Eb({value:r,negated:e,returnHtml:t}){let n=document.documentElement.outerHTML,o=n.includes(r)===!e;return n.length>1e4&&(n=n.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?n:void 0}}var zm=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:i,codeEvalTools:a,controller:l}=r.fixtures,c=l.browser,{orgId:s,runId:u}=r.inputs,d=l.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),n.info(Wi({json:{inputs:t,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||"",E=await er({orgId:s,s:f,context:o,logger:n,localTools:a,signal:d});h={orgId:s,cacheKeys:[E,...Object.entries(t).map(([y,A])=>`${y}:${A}`)]},n.info({original:f,keyParams:h},"Module cache key params");let S=Date.now();for(;Date.now()-S<yy;){d?.throwIfAborted();let y=await i.getCacheResult(h);if(y){n.info({cacheResult:Qe(y,1e3,!0)},"Got result from module execution cache"),p=Vc(e,t,"SUCCESS"),p.message="Used cached module result.",p.data=JSON.parse(y),m=!0;break}else n.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let A=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${DD()};runId:${u}`},d);if(A.acquired){g=A.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 Z(2500+Math.random()*1e4,d)}}try{if(!p)p=await kD(r);else if(e.autoAuth){let f=Vl.safeParse(p.data);if(!f.success)throw new C("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 E=!1,S=e.advanced?.cacheInvalidation;if(S&&S.type==="PAGE_CHECK"){let y={type:"CONTENT",value:S.substring},A=await Gc({timeout:Gr,assertion:y,browser:c,logger:n,signal:d,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});A.success?n.debug({invalResult:A},"Cached result still valid after page check, continuing..."):(n.info({invalResult:A},"Invalidating cached result due to page check failure"),E=!0)}if(h&&E)return await i.deleteCacheResult(h),zm(r)}}finally{try{g!==void 0&&!m&&p?.status==="SUCCESS"&&await FD({step:e,result:p,browser:l.browser,cacheKeyPrefix:g,logger:n,storage:i})}finally{g!==void 0&&await i.releaseCacheLock(g)}}return p},kD=async r=>{let{step:e,tracer:t}=r.moduleParams,n=Vc(e,r.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return n.results=a,n.status=i,n.finishedAt=new Date,Qr({asyncTasks:r.work.asyncTasks,nestedResults:a,result:n,logger:r.fixtures.logger}),n};function Vc(r,e,t){let n={};return Object.entries(e).forEach(([i,a])=>{n[i]=JSON.stringify(a)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function Tb({orgId:r,step:e,context:t,logger:n,flagStore:o,codeEvalTools:i,signal:a}){let l={};try{for(let c of e.parameters??[]){let s=e.inputs?.[c]??e.defaultParameters?.[c];if(!s){n.warn(`No value or default found for parameter '${c}' that is required by module '${e.name}'`);continue}l[c]=await Zn({orgId:r,code:s,fragment:!0,context:t,logger:n,localTools:i,signal:a})}return l}catch(c){throw a?.throwIfAborted(),new C("UserConfigurationError",`Failed to evaluate module inputs: ${c}`)}}async function FD({step:r,result:e,browser:t,cacheKeyPrefix:n,logger:o,storage:i}){let a=r.cacheConfig?.cacheExpiryMs;(!a||a===tE)&&(a=r.defaultCacheTtl??rE);let l;r.autoAuth?l=JSON.stringify(await t.saveAuthState()):e.data!==void 0?l=JSON.stringify(e.data):l='""',o.debug({cacheKeyPrefix:n,ttlMs:a,truncatedCacheResultJson:Wi({json:l,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:l,keyPrefix:n,ttlMs:a})}async function Qo(r,e,t){return UD(r,e,t)}async function UD(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",l;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(l="Step aborted by user.",a="CANCELLED"):o instanceof C?l=`${o}`:l=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let c=Vc(r,{},"FAILED");return c.message=l,c.startedAt=n,c.finishedAt=i,c}return{...xc(r),startedAt:n,finishedAt:i,status:a,data:null,message:l,results:[]}}}async function oa(r,e){let t=!1;try{return r&&!r.state.failureRecoveryDisabled&&(r.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{r&&t&&(r.state.failureRecoveryDisabled=void 0)}}import{randomUUID as bb}from"crypto";var jc=async r=>{let{step:e,tracer:t}=r.presetParams,{logger:n,controller:o,context:i}=r.fixtures,{collectDebugData:a}=r.options,{testMetadata:l}=r.inputs,c=e.command.type,s=n.child({commandType:c,stepId:e.id,commandId:e.command.id}),u=o.browser.url(),d=new Date,p,m=bb(),g=bb();if(a)try{if(p=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:s,snapshotId:m,html:y})}}catch(y){s.debug({err:y},"Failed to take before screenshot, continuing...")}let h,f,E,S=Bl();try{let y=await o.executePresetCommand(S,t,e.command,i,l?.advanced.disableAICaching??!1);y.beforeScreenshotOverride&&(p=y.beforeScreenshotOverride),E=y.afterScreenshotOverride;let A=new Date,R=o.browser.url();f={beforeUrl:u,afterUrl:R,startedAt:d,finishedAt:A,viewport:o.browser.getViewport(),status:y.fail?"FAILED":"SUCCESS",elementInteracted:y.elementInteracted},h={...e,message:y.thoughts??"Successfully executed preset action.",beforeUrl:u,afterUrl:R,finishedAt:A,startedAt:d,status:y.fail?"FAILED":"SUCCESS",data:y.data,results:[f],details:S.details},"assertion"in e.command&&(h.message=y.thoughts||"Assertion passed.")}catch(y){s.error({message:y.message,stack:y.stack},`Failed executing preset step ${En(e.command)}`);let A=o.browser.url(),R=new Date,w=y instanceof Error?y.message:`${y}`;f={beforeUrl:u,afterUrl:A,startedAt:d,finishedAt:R,viewport:o.browser.getViewport(),status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:w},h={...e,startedAt:d,finishedAt:R,beforeUrl:u,afterUrl:A,status:y instanceof DOMException&&y.name==="AbortError"?"CANCELLED":"FAILED",message:w,failureReason:y instanceof C?y.reason:void 0,results:[f],details:S.details}}if(a)try{if(E||(E=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let y=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:s,snapshotId:g,html:y})}}catch(y){s.debug({err:y},"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 f.beforeSnapshot=m,h.beforeSnapshot=m,f.afterSnapshot=g,h.afterSnapshot=g,p&&t.attachBeforeScreenshot({logger:s,snapshotId:m,screenshot:p}),E&&t.attachAfterScreenshot({logger:s,snapshotId:g,screenshot:E}),h};async function vb({codePath:r,screenshotBuff:e,storage:t,logger:n}){if(e)try{let o=await t.uploadScreenshot(e);return n.info({screenshotUrl:o,codePath:r},"Saved screenshot for debugging"),o}catch(o){n.error({err:o,codePath:r},"Failed to save screenshot for debugging")}}async function en({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var BD=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function Rb({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(BD.includes(n.type))return;let l=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),s=0;for(;s===0||Date.now()-c<l;){await Z(250),s++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let m=u[p];if(Wo(m,o)&&m!==r&&m!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}var Ab="MOMENTIC_RUN_ID",wb="FINAL_SCREENSHOT_URL";import{cloneDeep as XD}from"lodash-es";async function Cb(r){let{step:e,tracer:t}=r.conditionalParams,{logger:n,controller:o}=r.fixtures,i=new Date,a=xc(e),l=e.elseSteps,c=!0,s=[],u,d=Bl();for(let f=0;f<e.blocks.length;f++){n.info(`Evaluating condition ${f} in conditional step`);let E=e.blocks[f];try{let S=await jc({...r,presetParams:{tracer:t,step:E.assertion}});s.push(S),n.info(`Condition ${f} resolved to true, executing the corresponding ${E.steps.length} steps`),c=!1,l=E.steps,u=S}catch(S){n.info({err:S},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(l)c&&n.info("No conditions resolved to true, executing the else block steps");else return n.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:s[s.length-1]?.data,message:s[s.length-1]?.message,results:[],finishedAt:new Date,details:d.details};n.info(`Executing ${l.length} steps in the selected conditional block`);let p=await r.conditionalParams.tracer.startSubSteps(),m=await r.executeStepList({...r,listParams:{steps:l,containerName:"conditional block",tracer:p}}),h={...a,assertionResult:u,...m,startedAt:i,finishedAt:new Date};return Qr({asyncTasks:r.work.asyncTasks,nestedResults:[...s,...m.results],result:h,logger:n}),h}import{randomUUID as xb}from"crypto";var _b=async r=>{let{tracer:e}=r.aiStepParams,{controller:t,logger:n}=r.fixtures;await t.browser.waitForDOMStability();let o=await t.browser.screenshot({}),i=await zD(r);i.finishedAt=new Date,Qr({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await t.browser.screenshot({}),l=xb();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:n,snapshotId:l,screenshot:o});let c=xb();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:a}),i},zD=async r=>{let{step:e,tracer:t}=r.aiStepParams,{controller:n,context:o,logger:i}=r.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 C("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await t.startSubSteps(),{status:s}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:c}});return a.finishedAt=new Date,a.status=s,a}catch(c){i.warn({err:c},"Failed executing saved deprecated AI action steps");let s=n.executeAbortController.signal.aborted;a.message=c instanceof Error?c.message:`${c}`,a.status=s?"CANCELLED":"FAILED"}return a};import{randomUUID as Hm}from"crypto";var Ib=15,HD=7,Pb=async r=>{let{tracer:e}=r.aiStepParams,{logger:t,controller:n}=r.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({quality:75}),i=await GD(r);i.finishedAt=new Date,Qr({asyncTasks:r.work.asyncTasks,result:i,nestedResults:i.results,logger:r.fixtures.logger});let a=await n.browser.screenshot({quality:75}),l=Hm();i.beforeSnapshot=l,e.attachBeforeScreenshot({logger:t,snapshotId:l,screenshot:o});let c=Hm();return i.afterSnapshot=c,e.attachAfterScreenshot({logger:t,snapshotId:c,screenshot:a}),i},GD=async r=>{let{step:e,tracer:t}=r.aiStepParams,{testMetadata:n,orgId:o}=r.inputs,{controller:i,context:a,logger:l,codeEvalTools:c}=r.fixtures,{step:s}=r.callbacks,u=`${e.id}-${Date.now()}`,d=l.child({stepId:e.id,langfuseSessionId:u}),p={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},m=await er({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=[],E=0,S=0,y,A;for(;;){if(E>Ib)return p.message=`Exceeded the maximum number of commands allowed per AI step (${Ib})`,p.status="FAILED",p;if(i.executeAbortController.signal.aborted)return p.message="Test execution was cancelled",p.status="CANCELLED",p;s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let R=await i.evaluateAiAction({goal:m,startingScreenshot:E===0?void 0:h,history:f,logger:d,langfuseSessionId:u,lastError:A}),{evaluation:w,reasoning:x,summary:_}=R;d.info(R,"Got AI evaluation");let M=p.results[E-1]?.id;switch(w.type){case"DONE":return p.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,p.status="SUCCESS",M&&s.onDynamicAIActionEvaluatingEvent?.({stepId:M,status:"SUCCESS",message:`${_}
33
+ ${x}`}),p;case"RIGHT_TRACK":{y=void 0,E===0?s.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:x}):M&&s.onDynamicAIActionEvaluatingEvent?.({stepId:M,status:"SUCCESS",message:x});break}case"WRONG_TRACK":{if(y=`${x}
34
+ ${w.feedback}`,S++,S>=HD)return p.message=`Our AI agent requires additional information to achieve this goal:
35
35
  ${x}
36
- ${w.feedback}`,p.status="FAILED",s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;P&&s.onDynamicAIActionEvaluatingEvent?.({stepId:P,status:"FAILED",message:w.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,p.status="FAILED",s.onDynamicAIActionEvaluatingEvent?.({stepId:P??e.id,status:"FAILED",message:p.message}),p}let Y=setTimeout(()=>{s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:y,lastActionHint:T},`Generating new sub-command ${y} within AI action`);let $,U;try{({command:$,reasoning:U}=await i.promptToCommand({goal:m,history:f,startingScreenshot:h,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:T,langfuseSessionId:u})),d.info({command:$,reasoning:U},"Got proposed command")}finally{clearTimeout(Y)}if($.type==="FAILURE")return clearTimeout(Y),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${U}`,p;let L={id:Bm(),type:"PRESET_ACTION",command:$},M={substepIndex:y+1,message:U||"Generated new command."};s.onDynamicCommandGenerated?.({...M,step:L,parentStepId:e.id}),d.info({commandId:$.id},`Executing sub-command ${y} within AI step: ${Tn($)}`);let q=await t.startSubSteps(),se=(await r.executeStepList({...r,options:{...r.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[L],tracer:q}})).results[0];s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let ze=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push(se),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${ze.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:Tn($),elementInteracted:se.results[0]?.elementInteracted,thoughts:U});let Qe={substepIndex:y,output:{...se,message:se.message??"Successfully executed preset action."},step:L,parentStepId:e.id};if(s.onDynamicCommandExecuted?.(Qe),await t.finish({output:Cl.parse(se),step:se,message:se.message,attempt:1}),se.status==="FAILED")if(p.status="FAILED",p.message=se.message,S<3)S++,A=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${se.message}`;else return p;else if(se.status==="CANCELLED")return p.status="CANCELLED",p.message=se.message,p;y++}};import{randomUUID as wD}from"crypto";var CD=3;async function Cb(r){let{logger:e}=r.fixtures,{results:t}=r.failureRecoveryParams,n=t[t.length-1],o=_D(r.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}`};r.work.state.failureRecoveryAttempts=(r.work.state.failureRecoveryAttempts??0)+1;try{return await xD(r)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function xD(r){let{fixtures:e,work:t,failureRecoveryParams:n}=r,{controller:o,logger:i}=e,{testMetadata:a}=r.inputs,{results:l,failedStep:c,nextSteps:s,tracer:u}=n;if(!l.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.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 Wi(i,u,l,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=s.map(_=>Jn(_)),f=a?.description?.trim(),y=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:S,thoughts:T,instructions:A}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:g,currentPageState:m,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:y||void 0});if(S!=="RECOVERABLE")return i.info({scenario:S,thoughts:T,instructions:A},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${T}`};if(!A)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let R={id:wD(),type:"AI_ACTION_DYNAMIC",text:A},w=await oa(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures},listParams:{steps:[R,c],containerName:"AI-recovered step list",tracer:u}})),x=w.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(cc({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: ${T}`;return x.message=_,i.info({thoughts:T},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:w,message:_}}else{let _=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${T}`;return x.message=_,i.info({thoughts:T,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:w,message:_}}return null}function _D(r,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let t=e.message;return t?t.includes("AbortError:")?"The user aborted the test":Vf.some(n=>t.includes(n))?"The failed step is an irrecoverable configuration error":(r.state.failureRecoveryAttempts??0)>CD?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as Gc}from"crypto";import ID from"fast-json-patch";import{cloneDeep as PD}from"lodash-es";async function xb(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:l,tracer:c}=r,{step:s}=n,{controller:u,logger:d}=o,p=s?.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=PD(s.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:y}=await Wi(d,c,e.results,{numStepsWithScreenshots:4}),S=await u.runSectionAutohealing({results:y,errorMessage:e.terminalResult?.message,goal:s.description});f=ID.applyPatch(f,S.patches).newDocument;let T=qt.fromSnapshot({snapshot:l,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await MD({logger:d,controller:u,tracer:c,context:T,restartConfig:m,startingUrl:a});let A=await oa(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:T},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(t.push(A.results),A.status==="SUCCESS")return{successfulHealing:{proposedStep:{...s,steps:f},listResult:A,context:T},healingAttempts:t};e=A}return{healingAttempts:t}}async function MD({logger:r,controller:e,tracer:t,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:Gc(),type:"PRESET_ACTION",command:{id:Gc(),type:"NAVIGATE",url:n.url}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:Gc(),type:"PRESET_ACTION",command:{id:Gc(),type:"NAVIGATE",url:i}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}}}function _b(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Tf(e.command.type))}}async function Ib(r){let{step:e,tracer:t}=r.sectionParams,{logger:n,controller:o,context:i}=r.fixtures,a=new Date,l=o.browser.url(),c=i.toObjectCopy(),s=await t.startSubSteps(),u=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list",tracer:s}}),d=e.autohealingConfig?await oa(r.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!r.work.state.autoHealingDisabled&&_b(e.autohealingConfig.trigger,d.terminalResult)){let h=await t.startSubSteps(),f=await xb({...r,startingContextSnapshot:c,startingUrl:l,failedResults:d,tracer:h});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,r.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let g={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return Qr({asyncTasks:r.work.asyncTasks,nestedResults:d.results,result:g,logger:n}),g}var LD=60*60*1e3;async function Or(r){let{results:e=[],containerName:t,steps:n,tracer:o}=r.listParams,{logger:i}=r.fixtures,a=o.getParentStepIdChain(),{fromStep:l,toStep:c}=r.inputs,s=r.work,u="SUCCESS",d,p=0;for(p;p<n.length;p++){let m=n[p];if(m.skipped)continue;if(s.fastForwardingToStep&&l){let T=JSON.stringify(a);if(m.id===l.fromStepId&&T===JSON.stringify(l.parentStepIdChain))s.fastForwardingToStep=!1;else if(!xE(m,a,l.fromStepId,l.parentStepIdChain))continue}let g=Jn(m),h=0,f=1,y=Date.now();"retries"in m&&m.retries&&m.retries>0&&(f+=m.retries);let S;for(;h<f&&Date.now()-y<LD;){h++,i.info({step:m,currentAttempt:h},`Executing step ${p+1}/${n.length} in ${t}: ${g}`);let T=Date.now(),{stepResult:A,status:R,failureRecoveryResults:w,shouldStopExecuting:x}=await ND({attempt:h,params:r,step:m,i:p,steps:n,results:e,currentParentIdChain:a,work:s,fromStep:l,toStep:c,lastRetry:h===f});if(R==="FAILED"&&h<f){S=[...S??[],A],Date.now()-T<1e3&&await Z(1e3-(Date.now()-T));continue}else e.push(A),S&&(A.previousAttempts=S);if(w&&e.push(...w),x)return u=R,d=A,{status:u,results:e,terminalResult:d};break}}return{status:u,results:e,terminalResult:d}}async function ND({attempt:r,params:e,step:t,i:n,steps:o,results:i,currentParentIdChain:a,work:l,fromStep:c,toStep:s,lastRetry:u}){let{tracer:d}=e.listParams,{logger:p,context:m,controller:g,codeEvalTools:h,usageTracker:f}=e.fixtures,{orgId:y}=e.inputs,S=new Date,T=await d.startStep({logger:p,step:t,attempt:r}),A=OD(t),R=m.toRedactedDisplayCopy(),w=g.browser.url(),x=g.executeAbortController.signal;f.trackStepExecution(t);let _,P;switch(t.type){case"PRESET_ACTION":{_="Preset action",P=await Qo(t,async()=>await Hc({...e,presetParams:{tracer:T,step:t}}),x);break}case"AI_ACTION":{_="AI action",P=await Qo(t,()=>Rb({...e,aiStepParams:{step:t,tracer:T},executeStepList:Or}),x);break}case"AI_ACTION_DYNAMIC":{_="AI action",P=await Qo(t,()=>wb({...e,aiStepParams:{step:t,tracer:T},executeStepList:Or}),x);break}case"RESOLVED_MODULE":{_=`Module (${t.name})`,P=await Qo(t,async()=>{let M=await hb({orgId:y,step:t,context:m,logger:p,flagStore:g.flagStore,codeEvalTools:h,signal:x});return Um({...e,executeStepList:Or,moduleParams:{step:t,resolvedInputs:M,tracer:T}})},x);break}case"CONDITIONAL":{_="Conditional step",P=await Qo(t,()=>bb({...e,conditionalParams:{step:t,tracer:T},executeStepList:Or}),x);break}case"SECTION":{_="Section",P=await Qo(t,()=>Ib({...e,sectionParams:{step:t,tracer:T},executeStepList:Or}),x);break}default:return(q=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}P.beforeUrl=P.beforeUrl??w,P.beforeTestContext=R,t.envKey&&m.setVariable(t.envKey,P.data);let Y=g.browser.url();m.setCurrentUrl(Y),P.afterUrl=P.afterUrl??Y,P.afterTestContext=m.toRedactedDisplayCopy(),await DD({startedAt:S,stepTypeName:_,result:P,callbacks:e.callbacks,globalWorkRef:e.work,tracer:T,attempt:r});let $,U;if(u&&P.status==="FAILED"&&!l.state.failureRecoveryDisabled&&c?.fromStepId===void 0&&s?.toStepId===void 0){let M=await Cb({...e,executeStepList:Or,failureRecoveryParams:{failedStep:A,nextSteps:o.slice(n+1),results:i.concat(P),tracer:d}});M&&(M.type==="ATTEMPTED"?($=M.result.results,U=M.status):M.type==="NOT_ELIGIBLE"&&(P.message=P.message?`${P.message} ${M.message}`:M.message),P.type==="PRESET_ACTION"&&(P.failureRecoveryStatus={type:M.type,message:M.message}))}return l.fastForwardingToStep&&c&&(c.fromStepId===t.id&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)&&(l.fastForwardingToStep=!1),t.type==="RESOLVED_MODULE"&&lm(a,c.parentStepIdChain)&&(l.fastForwardingToStep=!1)),P.status!=="SUCCESS"&&U!=="SUCCESS"||g.closed?{shouldStopExecuting:!0,status:P.status,stepResult:P,failureRecoveryResults:$}:s&&t.id===s.toStepId&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)?(g.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:P,failureRecoveryResults:$}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:P,failureRecoveryResults:$}}async function DD({stepTypeName:r,result:e,tracer:t,attempt:n}){let o=r.toLowerCase(),i=r.charAt(0).toUpperCase()+r.slice(1),a="";switch(e.status){case"SUCCESS":a=e.message??`${i} executed successfully.`;break;case"FAILED":a=e.message??`${i} failed.`;break;case"CANCELLED":a=e.message??`${i} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await t.finish({step:e,message:a,output:Cl.parse(e),attempt:n})}import{randomUUID as Pb}from"crypto";async function Mb({browser:r,signal:e}){let t=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:Pb(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:t,finishedAt:new Date,results:[],command:{id:Pb(),type:"NAVIGATE",url:r.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var Vc=async r=>{let{orgId:e,runId:t,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs;r.fixtures.logger=r.fixtures.logger.child({orgId:e,runId:t,testId:n?.id});let{logger:l,controller:c}=r.fixtures,{onTestComplete:s,onTestSuccess:u,onTestFailure:d}=r.callbacks.test,p=ZT(l);if(r.options.reinitializeBrowser){let g=await Mb({browser:c.browser,signal:c.executeAbortController.signal});if(g.status!=="PASSED")return await s?.(),clearInterval(p?.interval),g}let m;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:hy.parse(r.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await FD(r),m}finally{l.info({status:m?.status,labels:n?.labels},"Momentic test final result"),clearInterval(p?.interval),await s?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function kD({beforeStatus:r,mainStatus:e,afterStatus:t}){return r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var FD=async r=>{let{tracer:e}=r.testParams,{fromStep:t,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs,{logger:l,controller:c,context:s,storage:u}=r.fixtures,{collectDebugData:d,disableHealing:p}=r.options;s.setCurrentUrl(c.browser.url());let m="test",g=o,h=[],f=p||t!==void 0||n!==void 0||void 0,y={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},S=!1;t?.fromStepId&&t.fromStepId===n?.toStepId?(m="filtered step",y.fastForwardingToStep=!0):t?.fromStepId?(m="partial steps list from step",y.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",S=!0);let T,A,R;if(S&&i&&i.length>0){let U=await Ob(i,"beforeSteps",r);T=U.status,A=U.results,R=U.terminalResult?{...U.terminalResult,failureReason:"SetupFailureError"}:void 0}let w,x;if(T===void 0||T==="PASSED"){l.info({fromStep:t,toStep:n},`Starting execution of ${m}`);let U=await e.startMainStepList(),L=await Or({...r,work:y,listParams:{steps:g,containerName:m,results:h,tracer:U}});w=L.status,x=L.terminalResult}let _,P,Y;if(S&&a&&a.length>0){let U=await Ob(a,"afterSteps",r);_=U.status,P=U.results,Y=U.terminalResult?{...U.terminalResult,failureReason:"TeardownFailureError"}:void 0}let $=kD({beforeStatus:T,mainStatus:w,afterStatus:_});if(d&&UD({tracer:e,work:y,controller:c,storage:u,context:s,logger:l,status:$}),await Promise.allSettled(y.asyncTasks),y.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:A,afterResults:P}))),$==="FAILED"){let U=T==="FAILED"?R:void 0,L=_==="FAILED"?Y:void 0;return{status:"FAILED",results:h,beforeResults:A,afterResults:P,failedStepResult:U??x??L}}else if($==="CANCELLED")return{status:"CANCELLED",results:h,beforeResults:A,afterResults:P};return{status:"PASSED",failureRecoveryDetails:y.state.failureRecoveryAttempts?{attempts:y.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:A,afterResults:P}};async function Ob(r,e,t){let n=t.fixtures.logger,o=e==="beforeSteps"?await t.testParams.tracer.startBeforeStepList():await t.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:l,results:c,terminalResult:s}=await Or({...t,work:i,callbacks:a,listParams:{steps:r,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return l==="SUCCESS"?u="PASSED":l==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:s}}function UD({tracer:r,work:e,controller:t,storage:n,logger:o,context:i,status:a}){let l=t.browser.retrieveAndClearDebugData(),c=NE(l.logsPerPage),s=Op(l.harPages||{},l.harEntries||{});r.attachConsoleLogs({logger:o,logs:c}),r.attachNetworkLogs({logger:o,logs:s}),e.asyncTasks.push((async()=>{try{let u=await t.browser.screenshot({quality:75}),d=await Sb({codePath:"test-complete-final",storage:n,screenshotBuff:u,logger:o}),p=await H(t.browser.html(),{milliseconds:2e3});i.setVariable(Tb,d),a!=="PASSED"&&a!=="SUCCESS"&&(o.debug({finalPageHtml:p},"Final page state HTML"),o.debug({finalScreenshotUrl:d},"Uploaded final screenshot URL"))}catch{}})())}async function jc({settings:r,customHeaders:e,envVariables:t,envName:n,testName:o,baseUrl:i,logger:a,localTools:l,orgId:c}){let s=Il.parse(r);e&&(s.extraHeaders={...s.extraHeaders,...e});let u=new qt({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:t,currentUrl:i});await Fc({obj:s,context:u,bannedKeys:[],allowList:qf,localTools:l,logger:a,orgId:c});try{return Il.parse(s)}catch(d){throw new C("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as bz}from"lodash-es";var Lb={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
36
+ ${w.feedback}`,p.status="FAILED",s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:p.message}),p;M&&s.onDynamicAIActionEvaluatingEvent?.({stepId:M,status:"FAILED",message:w.feedback});break}case"IMPOSSIBLE":return p.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,p.status="FAILED",s.onDynamicAIActionEvaluatingEvent?.({stepId:M??e.id,status:"FAILED",message:p.message}),p}let K=setTimeout(()=>{s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);d.info({commandIndex:E,lastActionHint:y},`Generating new sub-command ${E} within AI action`);let $,k;try{({command:$,reasoning:k}=await i.promptToCommand({goal:m,history:f,startingScreenshot:h,disableCache:n?.advanced.disableAICaching??!1,logger:d,actionHint:y,langfuseSessionId:u})),d.info({command:$,reasoning:k},"Got proposed command")}finally{clearTimeout(K)}if($.type==="FAILURE")return clearTimeout(K),p.status="FAILED",p.message=`Our AI agent determined that no supported actions can fulfill the goals: ${k}`,p;let Y={id:Hm(),type:"PRESET_ACTION",command:$},I={substepIndex:E+1,message:k||"Generated new command."};s.onDynamicCommandGenerated?.({...I,step:Y,parentStepId:e.id}),d.info({commandId:$.id},`Executing sub-command ${E} within AI step: ${En($)}`);let j=await t.startSubSteps(),re=(await r.executeStepList({...r,options:{...r.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[Y],tracer:j}})).results[0];s.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:d});let Re=await i.browser.screenshot({clearHighlights:!0,retries:1});p.results.push(re),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${Re.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:En($),elementInteracted:re.results[0]?.elementInteracted,thoughts:k});let He={substepIndex:E,output:{...re,message:re.message??"Successfully executed preset action."},step:Y,parentStepId:e.id};if(s.onDynamicCommandExecuted?.(He),await t.finish({output:Pl.parse(re),step:re,message:re.message,attempt:1}),re.status==="FAILED")if(p.status="FAILED",p.message=re.message,S<3)S++,A=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${re.message}`;else return p;else if(re.status==="CANCELLED")return p.status="CANCELLED",p.message=re.message,p;E++}};import{randomUUID as VD}from"crypto";var jD=3;async function Mb(r){let{logger:e}=r.fixtures,{results:t}=r.failureRecoveryParams,n=t[t.length-1],o=WD(r.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}`};r.work.state.failureRecoveryAttempts=(r.work.state.failureRecoveryAttempts??0)+1;try{return await $D(r)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function $D(r){let{fixtures:e,work:t,failureRecoveryParams:n}=r,{controller:o,logger:i}=e,{testMetadata:a}=r.inputs,{results:l,failedStep:c,nextSteps:s,tracer:u}=n;if(!l.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(t.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 $i(i,u,l,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=s.map(_=>Xn(_)),f=a?.description?.trim(),E=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:S,thoughts:y,instructions:A}=await o.getFailureRecoveryPlan({currentUrl:d,currentScreenshot:p,failedResults:g,currentPageState:m,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:E||void 0});if(S!=="RECOVERABLE")return i.info({scenario:S,thoughts:y,instructions:A},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${y}`};if(!A)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let R={id:VD(),type:"AI_ACTION_DYNAMIC",text:A},w=await oa(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures},listParams:{steps:[R,c],containerName:"AI-recovered step list",tracer:u}})),x=w.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(mc({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: ${y}`;return x.message=_,i.info({thoughts:y},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:w,message:_}}else{let _=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${y}`;return x.message=_,i.info({thoughts:y,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:w,message:_}}return null}function WD(r,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let t=e.message;return t?t.includes("AbortError:")?"The user aborted the test":qf.some(n=>t.includes(n))?"The failed step is an irrecoverable configuration error":(r.state.failureRecoveryAttempts??0)>jD?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as $c}from"crypto";import qD from"fast-json-patch";import{cloneDeep as KD}from"lodash-es";async function Ob(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:l,tracer:c}=r,{step:s}=n,{controller:u,logger:d}=o,p=s?.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=KD(s.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:E}=await $i(d,c,e.results,{numStepsWithScreenshots:4}),S=await u.runSectionAutohealing({results:E,errorMessage:e.terminalResult?.message,goal:s.description});f=qD.applyPatch(f,S.patches).newDocument;let y=qt.fromSnapshot({snapshot:l,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await YD({logger:d,controller:u,tracer:c,context:y,restartConfig:m,startingUrl:a});let A=await oa(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:y},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(t.push(A.results),A.status==="SUCCESS")return{successfulHealing:{proposedStep:{...s,steps:f},listResult:A,context:y},healingAttempts:t};e=A}return{healingAttempts:t}}async function YD({logger:r,controller:e,tracer:t,restartConfig:n,context:o,startingUrl:i}){switch(n.type){case"NAVIGATE_URL":{let a={id:$c(),type:"PRESET_ACTION",command:{id:$c(),type:"NAVIGATE",url:n.url}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:$c(),type:"PRESET_ACTION",command:{id:$c(),type:"NAVIGATE",url:i}},l=await t.startStep({logger:r,step:a,attempt:1});await e.executePresetCommand(null,l,a.command,o,!1);break}}}function Lb(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Rf(e.command.type))}}async function Nb(r){let{step:e,tracer:t}=r.sectionParams,{logger:n,controller:o,context:i}=r.fixtures,a=new Date,l=o.browser.url(),c=i.toObjectCopy(),s=await t.startSubSteps(),u=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list",tracer:s}}),d=e.autohealingConfig?await oa(r.work,u):await u(),p,m;if(d.status==="FAILED"&&e.autohealingConfig&&!r.work.state.autoHealingDisabled&&Lb(e.autohealingConfig.trigger,d.terminalResult)){let h=await t.startSubSteps(),f=await Ob({...r,startingContextSnapshot:c,startingUrl:l,failedResults:d,tracer:h});f.successfulHealing&&(p=f.successfulHealing.proposedStep,d=f.successfulHealing.listResult,r.fixtures.context=f.successfulHealing.context),m=f.healingAttempts}let g={...e,...d,startedAt:a,finishedAt:new Date,proposedStep:p,healingAttempts:m};return Qr({asyncTasks:r.work.asyncTasks,nestedResults:d.results,result:g,logger:n}),g}var JD=60*60*1e3;async function Lr(r){let{results:e=[],containerName:t,steps:n,tracer:o}=r.listParams,{logger:i}=r.fixtures,a=o.getParentStepIdChain(),{fromStep:l,toStep:c}=r.inputs,s=r.work,u="SUCCESS",d,p=0;for(p;p<n.length;p++){let m=n[p];if(m.skipped)continue;if(s.fastForwardingToStep&&l){let y=JSON.stringify(a);if(m.id===l.fromStepId&&y===JSON.stringify(l.parentStepIdChain))s.fastForwardingToStep=!1;else if(!ME(m,a,l.fromStepId,l.parentStepIdChain))continue}let g=Xn(m),h=0,f=1,E=Date.now();"retries"in m&&m.retries&&m.retries>0&&(f+=m.retries);let S;for(;h<f&&Date.now()-E<JD;){h++,i.info({step:m,currentAttempt:h},`Executing step ${p+1}/${n.length} in ${t}: ${g}`);let y=Date.now(),{stepResult:A,status:R,failureRecoveryResults:w,shouldStopExecuting:x}=await QD({attempt:h,params:r,step:m,i:p,steps:n,results:e,currentParentIdChain:a,work:s,fromStep:l,toStep:c,lastRetry:h===f});if(R==="FAILED"&&h<f){S=[...S??[],A],Date.now()-y<1e3&&await Z(1e3-(Date.now()-y));continue}else e.push(A),S&&(A.previousAttempts=S);if(w&&e.push(...w),x)return u=R,d=A,{status:u,results:e,terminalResult:d};break}}return{status:u,results:e,terminalResult:d}}async function QD({attempt:r,params:e,step:t,i:n,steps:o,results:i,currentParentIdChain:a,work:l,fromStep:c,toStep:s,lastRetry:u}){let{tracer:d}=e.listParams,{logger:p,context:m,controller:g,codeEvalTools:h,usageTracker:f}=e.fixtures,{orgId:E}=e.inputs,S=new Date,y=await d.startStep({logger:p,step:t,attempt:r}),A=XD(t),R=m.toRedactedDisplayCopy(),w=g.browser.url(),x=g.executeAbortController.signal;f.trackStepExecution(t);let _,M;switch(t.type){case"PRESET_ACTION":{_="Preset action",M=await Qo(t,async()=>await jc({...e,presetParams:{tracer:y,step:t}}),x);break}case"AI_ACTION":{_="AI action",M=await Qo(t,()=>_b({...e,aiStepParams:{step:t,tracer:y},executeStepList:Lr}),x);break}case"AI_ACTION_DYNAMIC":{_="AI action",M=await Qo(t,()=>Pb({...e,aiStepParams:{step:t,tracer:y},executeStepList:Lr}),x);break}case"RESOLVED_MODULE":{_=`Module (${t.name})`,M=await Qo(t,async()=>{let I=await Tb({orgId:E,step:t,context:m,logger:p,flagStore:g.flagStore,codeEvalTools:h,signal:x});return zm({...e,executeStepList:Lr,moduleParams:{step:t,resolvedInputs:I,tracer:y}})},x);break}case"CONDITIONAL":{_="Conditional step",M=await Qo(t,()=>Cb({...e,conditionalParams:{step:t,tracer:y},executeStepList:Lr}),x);break}case"SECTION":{_="Section",M=await Qo(t,()=>Nb({...e,sectionParams:{step:t,tracer:y},executeStepList:Lr}),x);break}default:return(j=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}M.beforeUrl=M.beforeUrl??w,M.beforeTestContext=R,t.envKey&&m.setVariable(t.envKey,M.data);let K=g.browser.url();m.setCurrentUrl(K),M.afterUrl=M.afterUrl??K,M.afterTestContext=m.toRedactedDisplayCopy(),await ZD({startedAt:S,stepTypeName:_,result:M,callbacks:e.callbacks,globalWorkRef:e.work,tracer:y,attempt:r});let $,k;if(u&&M.status==="FAILED"&&!l.state.failureRecoveryDisabled&&c?.fromStepId===void 0&&s?.toStepId===void 0){let I=await Mb({...e,executeStepList:Lr,failureRecoveryParams:{failedStep:A,nextSteps:o.slice(n+1),results:i.concat(M),tracer:d}});I&&(I.type==="ATTEMPTED"?($=I.result.results,k=I.status):I.type==="NOT_ELIGIBLE"&&(M.message=M.message?`${M.message} ${I.message}`:I.message),M.type==="PRESET_ACTION"&&(M.failureRecoveryStatus={type:I.type,message:I.message}))}return l.fastForwardingToStep&&c&&(c.fromStepId===t.id&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)&&(l.fastForwardingToStep=!1),t.type==="RESOLVED_MODULE"&&dm(a,c.parentStepIdChain)&&(l.fastForwardingToStep=!1)),M.status!=="SUCCESS"&&k!=="SUCCESS"||g.closed?{shouldStopExecuting:!0,status:M.status,stepResult:M,failureRecoveryResults:$}:s&&t.id===s.toStepId&&JSON.stringify(a)===JSON.stringify(s.parentStepIdChain)?(g.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:M,failureRecoveryResults:$}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:M,failureRecoveryResults:$}}async function ZD({stepTypeName:r,result:e,tracer:t,attempt:n}){let o=r.toLowerCase(),i=r.charAt(0).toUpperCase()+r.slice(1),a="";switch(e.status){case"SUCCESS":a=e.message??`${i} executed successfully.`;break;case"FAILED":a=e.message??`${i} failed.`;break;case"CANCELLED":a=e.message??`${i} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await t.finish({step:e,message:a,output:Pl.parse(e),attempt:n})}import{randomUUID as Db}from"crypto";async function kb({browser:r,signal:e}){let t=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(n){let o={id:Db(),type:"PRESET_ACTION",status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:n.message,startedAt:t,finishedAt:new Date,results:[],command:{id:Db(),type:"NAVIGATE",url:r.baseUrl}};return{status:e.aborted||n.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var Wc=async r=>{let{orgId:e,runId:t,testMetadata:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs;r.fixtures.logger=r.fixtures.logger.child({orgId:e,runId:t,testId:n?.id});let{logger:l,controller:c}=r.fixtures,{onTestComplete:s,onTestSuccess:u,onTestFailure:d}=r.callbacks.test,p=nb(l);if(r.options.reinitializeBrowser){let g=await kb({browser:c.browser,signal:c.executeAbortController.signal});if(g.status!=="PASSED")return await s?.(),clearInterval(p?.interval),g}let m;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:n?.labels,orgSettings:Ey.parse(r.inputs.orgSettings)},`Starting run for Momentic test '${n?.name??"Unnamed test"}'`),m=await tk(r),m}finally{l.info({status:m?.status,labels:n?.labels},"Momentic test final result"),clearInterval(p?.interval),await s?.(),m?.status==="PASSED"?await u?.({steps:o,beforeSteps:i,afterSteps:a}):m?.status==="FAILED"&&await d?.({steps:o,beforeSteps:i,afterSteps:a})}};function ek({beforeStatus:r,mainStatus:e,afterStatus:t}){return r==="FAILED"?"FAILED":r==="CANCELLED"?"CANCELLED":t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var tk=async r=>{let{tracer:e}=r.testParams,{fromStep:t,toStep:n,steps:o,beforeSteps:i,afterSteps:a}=r.inputs,{logger:l,controller:c,context:s,storage:u}=r.fixtures,{collectDebugData:d,disableHealing:p}=r.options;s.setCurrentUrl(c.browser.url());let m="test",g=o,h=[],f=p||t!==void 0||n!==void 0||void 0,E={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},S=!1;t?.fromStepId&&t.fromStepId===n?.toStepId?(m="filtered step",E.fastForwardingToStep=!0):t?.fromStepId?(m="partial steps list from step",E.fastForwardingToStep=!0):n?m="partial steps list until step":(m="entire test",S=!0);let y,A,R;if(S&&i&&i.length>0){let k=await Fb(i,"beforeSteps",r);y=k.status,A=k.results,R=k.terminalResult?{...k.terminalResult,failureReason:"SetupFailureError"}:void 0}let w,x;if(y===void 0||y==="PASSED"){l.info({fromStep:t,toStep:n},`Starting execution of ${m}`);let k=await e.startMainStepList(),Y=await Lr({...r,work:E,listParams:{steps:g,containerName:m,results:h,tracer:k}});w=Y.status,x=Y.terminalResult}let _,M,K;if(S&&a&&a.length>0){let k=await Fb(a,"afterSteps",r);_=k.status,M=k.results,K=k.terminalResult?{...k.terminalResult,failureReason:"TeardownFailureError"}:void 0}let $=ek({beforeStatus:y,mainStatus:w,afterStatus:_});if(d&&rk({tracer:e,work:E,controller:c,storage:u,context:s,logger:l,status:$}),await Promise.allSettled(E.asyncTasks),E.asyncTasks.push(Promise.resolve(r.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:A,afterResults:M}))),$==="FAILED"){let k=y==="FAILED"?R:void 0,Y=_==="FAILED"?K:void 0;return{status:"FAILED",results:h,beforeResults:A,afterResults:M,failedStepResult:k??x??Y}}else if($==="CANCELLED")return{status:"CANCELLED",results:h,beforeResults:A,afterResults:M};return{status:"PASSED",failureRecoveryDetails:E.state.failureRecoveryAttempts?{attempts:E.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:A,afterResults:M}};async function Fb(r,e,t){let n=t.fixtures.logger,o=e==="beforeSteps"?await t.testParams.tracer.startBeforeStepList():await t.testParams.tracer.startAfterStepList();n.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{}},a={...t.callbacks,test:{...t.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:l,results:c,terminalResult:s}=await Lr({...t,work:i,callbacks:a,listParams:{steps:r,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let u;return l==="SUCCESS"?u="PASSED":l==="CANCELLED"?u="CANCELLED":u="FAILED",{status:u,results:c,terminalResult:s}}function rk({tracer:r,work:e,controller:t,storage:n,logger:o,context:i,status:a}){let l=t.browser.retrieveAndClearDebugData(),c=UE(l.logsPerPage),s=Dp(l.harPages||{},l.harEntries||{});r.attachConsoleLogs({logger:o,logs:c}),r.attachNetworkLogs({logger:o,logs:s}),e.asyncTasks.push((async()=>{try{let u=await t.browser.screenshot({quality:75}),d=await vb({codePath:"test-complete-final",storage:n,screenshotBuff:u,logger:o}),p=await z(t.browser.html(),{milliseconds:2e3});i.setVariable(wb,d),a!=="PASSED"&&a!=="SUCCESS"&&(o.debug({finalPageHtml:p},"Final page state HTML"),o.debug({finalScreenshotUrl:d},"Uploaded final screenshot URL"))}catch{}})())}async function qc({settings:r,customHeaders:e,envVariables:t,envName:n,testName:o,baseUrl:i,logger:a,localTools:l,orgId:c}){let s=Ll.parse(r);e&&(s.extraHeaders={...s.extraHeaders,...e});let u=new qt({baseUrl:i,envName:n,testName:o,variablesFromEnvironment:t,currentUrl:i});await zc({obj:s,context:u,bannedKeys:[],allowList:Jf,localTools:l,logger:a,orgId:c});try{return Ll.parse(s)}catch(d){throw new C("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${d.message}`)}}import{cloneDeep as kz}from"lodash-es";var Ub={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
37
37
  var momenticConstants = {
38
38
  bannedClassSubstrings: [
39
39
  "relative",
@@ -251,7 +251,8 @@ var momenticConstants = {
251
251
  "data-ved",
252
252
  "aria-controls",
253
253
  "d"
254
- ]
254
+ ],
255
+ ineligibleElementAttribute: "momentic-ineligible"
255
256
  };
256
257
  function addMomenticConstantsToWindow() {
257
258
  const customWindow = window;
@@ -3996,45 +3997,45 @@ function registerAllMomenticListeners() {
3996
3997
 
3997
3998
  // src/html/index.ts
3998
3999
  registerAllMomenticListeners();
3999
- `};var Lr={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"]};var Nb="BoundingBoxMovedError",Db="ZeroOpacityError",$c="visual_actions",An="data-momentic-id";function kb(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
4000
+ `};var fr={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var Bb="BoundingBoxMovedError",zb="ZeroOpacityError",Kc="visual_actions",Rn="data-momentic-id";function Hb(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
4000
4001
  `,o);a>0&&a<n&&(o=a);let l=i,c=0;for(;c<1e3&&l>n&&r[l]!==`
4001
4002
  `;)c++,l--;return l>n&&r[l]===`
4002
- `&&(i=l),r.slice(o,i)}function Nr(r){let e=typeof r=="string"?r:r.toString();return`[${An}="${e}"]`}import{execSync as f0}from"child_process";import{randomUUID as pg}from"crypto";import{diff as mg}from"deep-object-diff";import{existsSync as ru,mkdirSync as S0,readFileSync as y0,writeFileSync as E0}from"fs";import{Jimp as Hv}from"jimp";import T0 from"js-beautify";import{cloneDeep as xs}from"lodash-es";import b0 from"mime";import{homedir as hg,hostname as v0,platform as R0}from"os";import{basename as A0,extname as w0,join as sa,resolve as C0}from"path";import{chromium as Vv,devices as x0}from"playwright";import{addExtra as _0}from"playwright-extra";import I0 from"puppeteer-extra-plugin-recaptcha";import{v4 as P0}from"uuid";import{rmSync as ov}from"fs";import{basename as mk,join as gk}from"path";import{errors as hk}from"playwright-core";var Fb=new Set(["about:blank","chrome-error://chromewebdata/"]);var zm=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Hm=1e4,ws=500;import{mkdirSync as zD,rmSync as Ub,statSync as HD}from"fs";import*as $m from"node:fs";import GD from"nodejs-file-downloader";import{tmpdir as VD}from"os";import to,{basename as jD,dirname as $D}from"path";var Wm="file://",jm=to.join(VD(),"momentic","downloads"),Vm=1e4,WD=50*1024*1024;async function Bb(r){let{uri:e}=r;if(e.startsWith(Wm))return KD(r);if(e.startsWith("http"))return XD(r);if(dy)return YD(r);throw new C("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function qD(r,e){let t=to.join(jm,r,e.slice(Wm.length)),n=to.join(jm,r),o=t.startsWith(n);if(!$m.existsSync(t)||!o)throw new C("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function KD({uri:r,orgId:e}){let t=qD(e,r);return{filePath:t,cleanup:()=>{Ub($D(t),{recursive:!0,force:!0})}}}async function YD({uri:r}){let e=to.resolve(r);if(!$m.existsSync(e))throw new C("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function XD({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=jD(n.href),i=Km(o),a=to.extname(i);if(XS.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=qm(t),c=new GD({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:Vm}),{downloadStatus:s,filePath:u}=await H(c.download(),{milliseconds:Vm,message:`Download timed out after ${Vm}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=HD(u).size;if(p>WD)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let m;return{filePath:u,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>Ub(l,{recursive:!0,force:!0}),10*60*1e3)}}}function zb(r,e){return`${Wm}${r}/${e}`}function qm(r){let e=Math.random().toString(36).substring(4),t=to.join(jm,r,e);return zD(t,{recursive:!0}),t}function Km(r){let e=to.extname(r),t=to.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function wn(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}async function Hb(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await H(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function Gb(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await H(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Vb(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await H(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function jb(r,e,t,n,o){try{await JD(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function JD(r,e,t,n){let o=n.text();o.length>ws&&(o=o.slice(0,ws)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>ws?i.push(c.slice(0,ws)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}Ym(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function Ym(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>Hm&&(i[t]=i[t].slice(Math.floor(Hm/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function Sr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await hs({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import QD from"truncate-json";var ZD="[redacted due to size]",$b=5e3,ek=5e3;async function qb(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function Xm(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await Yb(e),url:n.toString(),method:e.method(),queryString:o,postData:await rk(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:Xb(t).timings}}async function Kb(r,e,t){await t.finished();let n={};try{n=await ak(t)}catch{}let o={...await Yb(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=Xb(a);r.time=c,r.timings=l}function Cs(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Wb(r){try{return new Date(r).toISOString()}catch{return}}function tk(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=tn(i),e.value=tn(a);continue}i==="Domain"&&(e.domain=tn(a)),i==="Expires"&&(e.expires=Wb(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Wb(Date.now()+ +a*1e3)),i==="Path"&&(e.path=tn(a)),i==="Secure"&&(e.secure=!0)}return e}async function Yb(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(tk)??[];return{headers:Object.entries(e).map(([n,o])=>({name:tn(n),value:tn(o)})),cookies:t}}async function rk(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:tn(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:tn(i),value:a?tn(a):void 0})}return n}var nk=["text"],ok=["json","xml","html","javascript"];function ik(r){let[e,t]=r.split("/");return e?nk.includes(e)?!0:t?!!ok.some(n=>t?.includes(n)):!1:!1}async function ak(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&ik(t)&&(n.text=tn(await r.text())),n}function tn(r){try{let e=JSON.parse(r),{jsonString:t}=QD(r,ek);return t}catch{return r.length>$b?r.slice(0,$b)+ZD:r}}function Zo(r){return r<0?0:r}function Xb(r){return{timings:{blocked:Zo(r.domainLookupStart),dns:Zo(r.domainLookupEnd-r.domainLookupStart),connect:Zo(r.connectEnd-r.connectStart),send:Zo(r.responseStart-r.requestStart),wait:0,receive:Zo(r.responseEnd-r.responseStart),ssl:Zo(r.connectEnd-r.secureConnectionStart)},total:Zo(r.responseEnd)}}function Jb(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function ct({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await H(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function Jm(){return window.lastCursorPos}import{errors as sk}from"playwright-core";async function ei({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){let s=c;if(Za(s)){t.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[u]=await Promise.all([r(i),n.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return u}else if(s instanceof sk.TimeoutError)t.warn({err:s,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await lk(s,i.locator,n,t);else throw s}throw l instanceof C?l:new C("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function lk(r,e,t,n){return r.message.includes("attempt #")?ck(r,e,t,n):uk(r)}async function ck(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
4003
- `,";").replace(/\s+/g," ");let a="",l=await wn(e,n);if(l&&(a=`Target element HTML: ${Je(l,100,!0)}`),i.includes("element is not enabled"))return new C("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(Nr(s)),d=await wn(u,n);d&&(c=`Covering element HTML: ${Je(d,100,!0)}`)}return new C("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
4004
- ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new C("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new C("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function uk(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new C("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function Qb(r){try{return await dk(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function dk({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await wn(r,e),i=await r.boundingBox({timeout:1e3});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(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=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=s._MOMENTIC_FEATURE_FLAGS?.[$c],h=c.getAttribute(An),f=!g&&h?Nr(h):s.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:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var ev=["date","datetime-local","month","time","week"],Zb={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 tv(r){try{await H(pk(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function pk({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await ct({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Zb[i])return;Zb[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`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Xt}from"zod";var rv=Xt.object({doubleClick:Xt.boolean().optional(),rightClick:Xt.boolean().optional(),force:Xt.boolean().optional(),waitForDownload:Xt.boolean().optional(),delayMs:Xt.number().optional(),downloadTimeoutMs:Xt.number().optional(),relativePosition:Xt.object({x:Xt.number(),y:Xt.number()}).optional()}),ype=Xt.object({repeat:Xt.number().optional(),convertMeta:Xt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Xt.number().optional()});async function Wc({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await Qm(e,n);let o=r.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 l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=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,s),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 H(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function Qm(r,e=1e3){let t=await r.state.getRoot();await ct({root:t,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:r.waitForPageLoad,codePath:"removing element highlights"})}async function Zm(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return ei({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>iv({...r,targetingResult:t,useVisualClick:e})})}async function fk(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await Sk(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function Sk(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),iv({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function yk(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await $o({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new C("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:p}=await bk({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),m=rv.safeParse(i);t.info({frameCoordinates:c,position:o,options:m.success?m.data:void 0,clickLocation:{clickX:u,clickY:d,reason:p},duration:Date.now()-s},"Visual click")}async function Ek(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await Qb({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(Rk(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),fk(s,{...r,targetingResult:{...i,locator:i}})}}async function iv(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof hk.TimeoutError?new C("ActionFailureError",`Download did not complete in ${c}ms`):new C("ActionFailureError",`Download failed: ${s.message}`)}})());try{await Wc({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await yk(r):await Ek(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await H(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await vk(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function Tk(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new C("ActionFailureError","Element does not have a bounding box");let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function bk({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,p]=await Tk(r,n);i=d.x,a=d.y,l=p}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function vk(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Km(r.suggestedFilename()),i=e();await r.saveAs(gk(i,o)),ov(n,{force:!0}),setTimeout(()=>{ov(i,{recursive:!0,force:!0})},5*60*1e3);let a=zb(mk(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function Rk(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as Ak}from"os";var wk={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 Ck(){let r=Ak();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function av(r){return JSON.stringify(r.split("+").sort())}function qc(r){let e=Ck(),t=av(r);for(let n of Object.values(wk))if(Object.values(n).some(o=>av(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function eg({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await ct({root:r,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Mt,p=await ct({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[m,g,h]=await ct({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let y=f.getBoundingClientRect();return[f.scrollTop,y.x,y.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let y=await H(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[S,T,A]=await H(e.evaluate(()=>{let R=document.activeElement;if(!R)return[void 0,void 0,void 0];let w=R.getBoundingClientRect();return[R.scrollTop,w.x,w.y]}),{milliseconds:1e3});if(y===p&&S===m&&T===g&&A===h)break;p=y,m=S,g=T,h=A,await Z(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function tg(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.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 Z(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as Dk}from"crypto";import{cloneDeep as ng}from"lodash-es";function ro(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as xk}from"crypto";var _k="v1";function Kc(r,e){if(r.tagName.toLowerCase()==="svg"&&!Pk(r))try{let t=sv(r,e),n=Ik(JSON.stringify(t));return{version:_k,json:t,hash:n}}catch{return}}function Ik(r){return xk("md5").update(r).digest("hex")}function sv(r,e){let t=r.tagName.toLowerCase(),n=Mk(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=sv(a,e);l&&o.children.push(l)}}return o}function Pk(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function Mk(r){let e={},t=r.attributes;for(let n of Object.keys(t))Lr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var ti={r:147,g:196,b:125,a:.55},cv={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:ti,paddingColor:ti,borderColor:ti,marginColor:ti,eventTargetColor:ti,shapeColor:ti,shapeMarginColor:ti,showInfo:!0,showAccessibilityInfo:!0};function uv({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=Ok({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function Ok({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((x,_)=>{u[x]=_});let d=s.styles,p=s.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],y=m.parentIndex??[],S=m.nodeName??[],T=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},R=m.inputChecked??{index:[]},w=e[c.frameId];for(let x=0;x<h.length;x++){let _=h[x],P=T[x],Y=f[x]??[],$=y[x]!==void 0&&y[x]>=0?y[x]:void 0,U=$!==void 0?h[$]:void 0,L=U!==void 0?a[U]:void 0,M=A.index.indexOf(x),q=M!==-1?e[A.value[M]]:void 0,we=u[x],se;we?se=p[we]??[]:se=[];let ze=S[x]!==void 0?e[S[x]]?.toLowerCase():void 0;if(!ze){l.warn({backendNodeId:_,frameId:w,frameIndex:o,nodeBounds:se},"DOM node has no tag name");continue}let Qe={backendNodeId:_,psuedoType:q,nodeType:P,frameIndex:o,parentFrameId:w,ownedFrameId:void 0,bounds:{x:se[0]??null,y:se[1]??null,width:se[2]??null,height:se[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:U??null,tagName:ze,parent:L??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};L&&L.childrenBackendIds.push(_);let ir=g.index.indexOf(x);if(ir!==-1){let re=g.value[ir];i[re]=Qe;let Ce=r[re]?.frameId;Qe.ownedFrameId=Ce!==void 0?e[Ce]:void 0}for(let re of Object.keys(Qe.bounds)){let Ce=re;Qe.bounds[Ce]!==null&&(Qe.bounds[Ce]/=n)}let dt=we!==void 0?d[we]??[]:[];for(let re=0;re<dt.length&&!(re>=t.length);re++){let Ce=dt[re];if(Ce===void 0||isNaN(Ce))continue;let He=e[Ce];if(He===void 0)continue;let Ar=t[re];Qe.computedStyles[Ar]=He}for(let re=0;re<Y.length;re+=2){let Ce=Y[re],He=Y[re+1];if(!Ce||!He)continue;let Ar=e[Ce],fi=e[He];!Ar||!fi||(Qe.attributes[Ar]=fi)}R.index.includes(x)&&(Qe.attributes.checked="true"),a[Qe.backendNodeId]=Qe}return a[h[0]]}function rg(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${rg(t,e)}${a}`}return r.mPathSelector=n,n}function lv(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var Lk=["html","#document","#document-fragment"];function dv({node:r,domGraph:e}){let t=[],n=r,o=lv(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=lv(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++,Lk.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function pv(r,e){let t=r.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?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function mv(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=ro(o,An);if(!i)throw new Error(`Could not find attribute ${An} for object ${e}`);return i}function gv(r){let e=[];for(let t=0;t<r.domGraph.roots.length;t++){let n=r.domGraph.roots[t],o=Nk({root:n,domGraph:r.domGraph,existingHashes:r.existingHashes,flagStore:r.flagStore,logger:r.logger});e=e.concat(o)}return e}function Nk(r){let{root:e,domGraph:t,existingHashes:n}=r,o=[],i=[e];for(;i.length;){let a=i.pop();if(a.nodeType===1&&a.tagName.toLowerCase()==="svg"){let l=Kc(a,t);l&&!n[l.hash]&&o.push(l)}for(let l of a.childrenBackendIds){let c=t.backendIdToNode[l];c&&i.push(c)}}return o}var kk=["focusable","keyshortcuts","controls","live","relevant","orientation"],Fk=["selected","readonly","modal","required","invalid"],Uk=["id","name","role","content"],hv=["absolute","fixed","sticky"],Bk=["path"],zk=["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"],yv=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Ev=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],Hk=["menulistpopup","statictext","inlinetextbox"],Gk=80,fv=100,Tv=50,ag=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],Vk=["cite"],jk={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"]},$k={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Sv={indentLevel:0},og=class r{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;mPathSelector;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;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,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<Tv?t:""),this.role=this.role||(e.domNode.attributes.role??""),Yk(this.properties,e.domNode,e.importantProperties)}Jk(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&&Bk.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Ev.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>wv(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Cv(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(zk.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Lr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>Av(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")?!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"))}serialize(e=Sv){let t=Object.assign({},Sv,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=ng(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(R=>!R.superseded&&R.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(R=>!R.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let R=h.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===m&&(m="")}let f=ag.includes(this.role)||Vk.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
4005
- `;let y=`${u}<${p}`;!a&&!f&&(y+=` id="${this.id}"`);let S=l??!1;(s.multiline||s.contenteditable)&&this.children.length>0&&(S=!0),d&&d!=="generic"&&d!==p&&!(jk[d]??[]).includes(p)&&(y+=` role=${JSON.stringify(d)}`),m&&(y+=` name=${JSON.stringify(m)}`),this.content&&!S&&(y+=` content=${JSON.stringify(this.content)}`);let T=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-T>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(s).forEach(([R,w])=>{if(!kk.includes(R)){{if(Fk.includes(R)&&(!w||w==="false"))return;if(R==="value"&&S&&(s.type==="text"||this.role==="textbox"))return;if(R==="level"&&`${w}`=="1")return;if(R==="url"&&s.src&&p==="img")return;if(R==="url"&&s.href&&p==="a")return;if(R==="editable"&&w==="plaintext")return;if(R==="type"&&w===p)return;if(c&&!$k[R])return}typeof w=="string"?y+=` ${R}="${Je(w,fv,!0)}"`:typeof w=="boolean"?w?y+=` ${R}`:y+=` ${R}={false}`:typeof w<"u"&&(y+=` ${R}={${Je(JSON.stringify(w),fv,!0)}}`)}})}if(p==="::before"||p==="::after"){let R="";for(let w of this.children)R+=w.serialize({...e,indentLevel:n,neighbors:0});return R}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)y+=` />
4006
- `;else{let R="";for(let x of this.children)R+=x.serialize({...e,indentLevel:n+2,neighbors:0});let w=R.trim();w.length<=Gk&&!w.includes(`
4007
- `)?y+=`>${w}</${p}>
4008
- `:y+=`>
4003
+ `&&(i=l),r.slice(o,i)}function Nr(r){let e=typeof r=="string"?r:r.toString();return`[${Rn}="${e}"]`}import{execSync as D0}from"child_process";import{randomUUID as gg}from"crypto";import{diff as hg}from"deep-object-diff";import{existsSync as ou,mkdirSync as k0,readFileSync as F0,writeFileSync as U0}from"fs";import{Jimp as Wv}from"jimp";import B0 from"js-beautify";import{cloneDeep as sa}from"lodash-es";import z0 from"mime";import{homedir as Sg,hostname as H0,platform as G0}from"os";import{basename as V0,extname as j0,join as la,resolve as $0}from"path";import{chromium as Kv,devices as W0}from"playwright";import{addExtra as q0}from"playwright-extra";import K0 from"puppeteer-extra-plugin-recaptcha";import{v4 as Y0}from"uuid";import{rmSync as cv}from"fs";import{basename as Mk,join as Ok}from"path";import{errors as Lk}from"playwright-core";var Gb=new Set(["about:blank","chrome-error://chromewebdata/"]);var Gm=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],Vm=1e4,_s=500;import{mkdirSync as ok,rmSync as Vb,statSync as ik}from"fs";import*as qm from"node:fs";import ak from"nodejs-file-downloader";import{tmpdir as sk}from"os";import eo,{basename as lk,dirname as ck}from"path";var Km="file://",Wm=eo.join(sk(),"momentic","downloads"),$m=1e4,uk=50*1024*1024;async function jb(r){let{uri:e}=r;if(e.startsWith(Km))return pk(r);if(e.startsWith("http"))return gk(r);if(hy)return mk(r);throw new C("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function dk(r,e){let t=eo.join(Wm,r,e.slice(Km.length)),n=eo.join(Wm,r),o=t.startsWith(n);if(!qm.existsSync(t)||!o)throw new C("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function pk({uri:r,orgId:e}){let t=dk(e,r);return{filePath:t,cleanup:()=>{Vb(ck(t),{recursive:!0,force:!0})}}}async function mk({uri:r}){let e=eo.resolve(r);if(!qm.existsSync(e))throw new C("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function gk({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=lk(n.href),i=Xm(o),a=eo.extname(i);if(ey.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let l=Ym(t),c=new ak({url:r,fileName:i,directory:l,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:$m}),{downloadStatus:s,filePath:u}=await z(c.download(),{milliseconds:$m,message:`Download timed out after ${$m}ms`});if(s!=="COMPLETE")throw new Error(`Download ended in non-success status: ${s}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=ik(u).size;if(p>uk)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let m;return{filePath:u,cleanup:()=>{clearTimeout(m),m=setTimeout(()=>Vb(l,{recursive:!0,force:!0}),10*60*1e3)}}}function $b(r,e){return`${Km}${r}/${e}`}function Ym(r){let e=Math.random().toString(36).substring(4),t=eo.join(Wm,r,e);return ok(t,{recursive:!0}),t}function Xm(r){let e=eo.extname(r),t=eo.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function An(r,e){try{return await r.evaluate(n=>window.serializeElementOnlyWithText?.(n,{truncateToLength:500}),void 0,{timeout:1e3})}catch(t){e.debug({err:t},"Failed to get HTML from locator for Playwright error translation");return}}async function Wb(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let l=await indexedDB.databases();for(let c of l){if(!c.name)continue;let s=await i.exportIdbToObject?.(c.name,c.version);s&&(a[c.name]=s)}return[a,void 0]}catch(l){return[void 0,l.message]}}),[n,o]=await z(t,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function qb(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,l]of Object.entries(o))await i.importObjectToIdb?.(a,l)},e);await z(n,{milliseconds:3e3})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Kb(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await z(t,{milliseconds:3e3})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function Yb(r,e,t,n,o){try{await hk(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function hk(r,e,t,n){let o=n.text();o.length>_s&&(o=o.slice(0,_s)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let l=await a.jsonValue(),c=JSON.stringify(l);c.length>_s?i.push(c.slice(0,_s)+"...(TRUNCATED)"):(typeof l!="object"||Object.keys(l).length>0)&&i.push(l)}catch{}Jm(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function Jm(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>Vm&&(i[t]=i[t].slice(Math.floor(Vm/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function Sr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await ys({promiseGenerator:r,signal:n,codePath:e,logger:o}),l=Date.now();return t[e]=l-i,a}import fk from"truncate-json";var Sk="[redacted due to size]",Xb=5e3,yk=5e3;async function Qb(r,e,t){let n=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[r]={id:r,startedDateTime:n,title:void 0,pageTimings:{}}}async function Qm(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([l,c])=>({name:l,value:c})),i={...await ev(e),url:n.toString(),method:e.method(),queryString:o,postData:await Tk(e)};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:tv(t).timings}}async function Zb(r,e,t){await t.finished();let n={};try{n=await Ak(t)}catch{}let o={...await ev(t),status:t.status(),statusText:t.statusText(),content:n,redirectURL:t.headers().location,_mocked:!1};r.response=o;let i;try{i=await e.sizes(),r.request.bodySize=i.requestBodySize,r.request.headersSize=i.requestHeadersSize}catch{}r.response&&i&&(r.response.bodySize=i.responseBodySize,r.response.headersSize=i.responseHeadersSize,r.response.content.size=i.responseBodySize);let a=e.timing();r.startedDateTime=new Date(a.startTime).toISOString();let{timings:l,total:c}=tv(a);r.time=c,r.timings=l}function Is(r,e,t){r.harEntries||(r.harEntries={}),r.harEntries[t]=e}function Jb(r){try{return new Date(r).toISOString()}catch{return}}function Ek(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=tn(i),e.value=tn(a);continue}i==="Domain"&&(e.domain=tn(a)),i==="Expires"&&(e.expires=Jb(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Jb(Date.now()+ +a*1e3)),i==="Path"&&(e.path=tn(a)),i==="Secure"&&(e.secure=!0)}return e}async function ev(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(Ek)??[];return{headers:Object.entries(e).map(([n,o])=>({name:tn(n),value:tn(o)})),cookies:t}}async function Tk(r){let e=r.postData();if(!e)return;let t=await r.headerValue("content-type"),n={mimeType:t??"application/octet-stream",text:tn(e),params:[]};if(t==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())n.params.push({name:tn(i),value:a?tn(a):void 0})}return n}var bk=["text"],vk=["json","xml","html","javascript"];function Rk(r){let[e,t]=r.split("/");return e?bk.includes(e)?!0:t?!!vk.some(n=>t?.includes(n)):!1:!1}async function Ak(r){let t=((await r.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0,n={mimeType:t,encoding:await r.headerValue("content-encoding")??void 0};return t&&Rk(t)&&(n.text=tn(await r.text())),n}function tn(r){try{let e=JSON.parse(r),{jsonString:t}=fk(r,yk);return t}catch{return r.length>Xb?r.slice(0,Xb)+Sk:r}}function Zo(r){return r<0?0:r}function tv(r){return{timings:{blocked:Zo(r.domainLookupStart),dns:Zo(r.domainLookupEnd-r.domainLookupStart),connect:Zo(r.connectEnd-r.connectStart),send:Zo(r.responseStart-r.requestStart),wait:0,receive:Zo(r.responseEnd-r.responseStart),ssl:Zo(r.connectEnd-r.secureConnectionStart)},total:Zo(r.responseEnd)}}function rv(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function dt({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await z(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function Zm(){return window.lastCursorPos}import{errors as wk}from"playwright-core";async function ei({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),l;for(;Date.now()-a<o;)try{return await r(i)}catch(c){let s=c;if(rs(s)){t.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[u]=await Promise.all([r(i),n.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return u}else if(s instanceof wk.TimeoutError)t.warn({err:s,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),l=await Ck(s,i.locator,n,t);else throw s}throw l instanceof C?l:new C("ActionFailureError",`Failed to interact with targeted element. Error: ${l.message}`,{errOptions:{cause:l}})}async function Ck(r,e,t,n){return r.message.includes("attempt #")?xk(r,e,t,n):_k(r)}async function xk(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
4004
+ `,";").replace(/\s+/g," ");let a="",l=await An(e,n);if(l&&(a=`Target element HTML: ${Qe(l,100,!0)}`),i.includes("element is not enabled"))return new C("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",s=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(s){let u=(await t.state.getRoot()).locator(Nr(s)),d=await An(u,n);d&&(c=`Covering element HTML: ${Qe(d,100,!0)}`)}return new C("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
4005
+ ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let s=await e.boundingBox({timeout:3e3});s?s.height===0?c="The element you attempted to interact with has zero height.":s.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new C("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new C("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function _k(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new C("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}async function nv(r){try{return await Ik(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function Ik({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await An(r,e),i=await r.boundingBox({timeout:1e3});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(t)try{let c=r.page().locator(`label[for=${JSON.stringify(t)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let s=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=s._MOMENTIC_FEATURE_FLAGS?.[Kc],h=c.getAttribute(Rn),f=!g&&h?Nr(h):s.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:1e3});if(a.type==="error")throw new Error(a.error);let l=r.page().locator(a.selector);return await l.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:l,relativePoint:a.relativePoint}}var iv=["date","datetime-local","month","time","week"],ov={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 av(r){try{await z(Pk(r),{milliseconds:3e3})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function Pk({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await dt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!ov[i])return;ov[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`),t.clearContent=!1,n.info("Transforming datetime input to use sequential key presses")}import{z as Xt}from"zod";var sv=Xt.object({doubleClick:Xt.boolean().optional(),rightClick:Xt.boolean().optional(),force:Xt.boolean().optional(),waitForDownload:Xt.boolean().optional(),delayMs:Xt.number().optional(),downloadTimeoutMs:Xt.number().optional(),relativePosition:Xt.object({x:Xt.number(),y:Xt.number()}).optional()}),kpe=Xt.object({repeat:Xt.number().optional(),convertMeta:Xt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Xt.number().optional()});async function Yc({locator:r,callbacks:e,logger:t,timeoutMs:n=1e3}){try{await eg(e,n);let o=r.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 l=0;for(;!a.momenticIsEligible(i)&&l<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,l++}let c=i.style.getPropertyValue("outline"),s=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,s),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 z(o,{milliseconds:n}),!0}catch(o){return t.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function eg(r,e=1e3){let t=await r.state.getRoot();await dt({root:t,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:r.waitForPageLoad,codePath:"removing element highlights"})}async function tg(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return ei({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>uv({...r,targetingResult:t,useVisualClick:e})})}async function Nk(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await Dk(r,e)}catch(n){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:n,originalError:r},"Error handling click error, rethrowing original error"),r):n}}async function Dk(r,e){let{logger:t,redirectionAttempts:n=0}=e,o=e.targetingResult.locator;if(r.message.includes("label")&&r.message.includes("for=")&&r.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),uv({...e,targetingResult:{locator:a},redirectionAttempts:n+1})}else throw t.error({err:r},"Click error does not match any known recoverable patterns, rethrowing"),r}async function kk(r){let{browserCallbacks:e,logger:t,targetingResult:n,position:o,options:i}=r,a=await e.state.getRoot(),l=a&&a!==n.locator.page()&&"frameElement"in a?await a.frameElement():null,c;try{c=l?await $o({promiseGenerator:async()=>l.boundingBox(),timeoutMs:3e3,logger:t}):null}catch(g){throw new C("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await l?.dispose()}let s=Date.now(),{clickX:u,clickY:d,reason:p}=await Bk({frameCoordinates:c,logger:t,targetingResult:n,position:o,options:i}),m=sv.safeParse(i);t.info({frameCoordinates:c,position:o,options:m.success?m.data:void 0,clickLocation:{clickX:u,clickY:d,reason:p},duration:Date.now()-s},"Visual click")}async function Fk(r){let{actionSource:e,targetingResult:t,options:n,logger:o}=r,i=r.targetingResult.locator,a=n?.relativePosition??r.position;if(e==="click"&&!a){let c=await nv({locator:i,logger:o});c&&(i=c.locator,a=c.relativePoint??a)}let l=n?.force||t.hints?.force||!1;try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l}):await i.click({button:n?.rightClick?"right":"left",timeout:3e3,position:a,delay:n?.delayMs??25,force:l})}catch(c){let s=c;if(Hk(s))o.warn({err:s},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:s},"Error clicking on locator, attempting to recover..."),Nk(s,{...r,targetingResult:{...i,locator:i}})}}async function uv(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,l;e?.waitForDownload&&(l=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:c})}catch(s){return s instanceof Lk.TimeoutError?new C("ActionFailureError",`Download did not complete in ${c}ms`):new C("ActionFailureError",`Download failed: ${s.message}`)}})());try{await Yc({locator:a.locator,callbacks:n,logger:t,timeoutMs:1e3})}catch(c){t.warn({err:c},"Error highlighting locator in click, continuing...")}if(i?await kk(r):await Fk(r),e?.waitForDownload)if(l){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let c=await z(l,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await zk(c,o.createIsolatedFolder,t)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function Uk(r,e){if(e.hints?.clickableXY){let i=(r?.x??0)+e.hints.clickableXY.x,a=(r?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let t=await e.locator.boundingBox({timeout:3e3});if(!t)throw new C("ActionFailureError","Element does not have a bounding box");let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function Bk({frameCoordinates:r,logger:e,options:t,targetingResult:n,position:o}){let i,a,l;if(o){let d=await n.locator.boundingBox({timeout:3e3});i=(r?.x??0)+(d?.x??0)+o.x,a=(r?.y??0)+(d?.y??0)+o.y,l="predefined position"}else{let[d,p]=await Uk(r,n);i=d.x,a=d.y,l=p}let c=n.locator.page(),s=t?.rightClick?"right":"left",u=t?.delayMs??25;return t?.doubleClick?await c.mouse.dblclick(i,a,{button:s,delay:u}):await c.mouse.click(i,a,{button:s,delay:u}),{clickX:i,clickY:a,reason:l}}async function zk(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Xm(r.suggestedFilename()),i=e();await r.saveAs(Ok(i,o)),cv(n,{force:!0}),setTimeout(()=>{cv(i,{recursive:!0,force:!0})},5*60*1e3);let a=$b(Mk(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function Hk(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as Gk}from"os";var Vk={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 jk(){let r=Gk();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function dv(r){return JSON.stringify(r.split("+").sort())}function Xc(r){let e=jk(),t=dv(r);for(let n of Object.values(Vk))if(Object.values(n).some(o=>dv(o)===t))return n[e];return process.platform==="darwin"?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function rg({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:l,logger:c}){if(!t&&!o)return;let s=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await dt({root:r,fn:([d,p,m,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*m,window.scrollY+(p??window.innerHeight)*g),arg:[t,o,s,u],waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let d=e.viewportSize()||Mt,p=await dt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[m,g,h]=await dt({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let E=f.getBoundingClientRect();return[f.scrollTop,E.x,E.y]},arg:void 0,waitForPageLoad:l.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*s,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let E=await z(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[S,y,A]=await z(e.evaluate(()=>{let R=document.activeElement;if(!R)return[void 0,void 0,void 0];let w=R.getBoundingClientRect();return[R.scrollTop,w.x,w.y]}),{milliseconds:1e3});if(E===p&&S===m&&y===g&&A===h)break;p=E,m=S,g=y,h=A,await Z(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function ng(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.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 Z(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as Zk}from"crypto";import{cloneDeep as ig}from"lodash-es";function to(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as $k}from"crypto";var Wk="v1";function Jc(r,e){if(r.tagName.toLowerCase()==="svg"&&!Kk(r))try{let t=pv(r,e),n=qk(JSON.stringify(t));return{version:Wk,json:t,hash:n}}catch{return}}function qk(r){return $k("md5").update(r).digest("hex")}function pv(r,e){let t=r.tagName.toLowerCase(),n=Yk(r);if(t==="image"&&n["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:t,props:n,children:[]};for(let i of r.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let l=pv(a,e);l&&o.children.push(l)}}return o}function Kk(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function Yk(r){let e={},t=r.attributes;for(let n of Object.keys(t))fr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var ti={r:147,g:196,b:125,a:.55},gv={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:ti,paddingColor:ti,borderColor:ti,marginColor:ti,eventTargetColor:ti,shapeColor:ti,shapeMarginColor:ti,showInfo:!0,showAccessibilityInfo:!0};function hv({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},l={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:l};return i.forEach((s,u)=>{let d=Xk({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:l,logger:n});c.roots.push(d)}),c}function Xk({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:l}){let c=r[o],s=c.layout,u={};s.nodeIndex.forEach((x,_)=>{u[x]=_});let d=s.styles,p=s.bounds??[],m=c.nodes,g=m.contentDocumentIndex??{index:[],value:[]},h=m.backendNodeId??[],f=m.attributes??[],E=m.parentIndex??[],S=m.nodeName??[],y=m.nodeType??[],A=m.pseudoType??{index:[],value:[]},R=m.inputChecked??{index:[]},w=e[c.frameId];for(let x=0;x<h.length;x++){let _=h[x],M=y[x],K=f[x]??[],$=E[x]!==void 0&&E[x]>=0?E[x]:void 0,k=$!==void 0?h[$]:void 0,Y=k!==void 0?a[k]:void 0,I=A.index.indexOf(x),j=I!==-1?e[A.value[I]]:void 0,ue=u[x],re;ue?re=p[ue]??[]:re=[];let Re=S[x]!==void 0?e[S[x]]?.toLowerCase():void 0;if(!Re){l.warn({backendNodeId:_,frameId:w,frameIndex:o,nodeBounds:re},"DOM node has no tag name");continue}let He={backendNodeId:_,psuedoType:j,nodeType:M,frameIndex:o,parentFrameId:w,ownedFrameId:void 0,bounds:{x:re[0]??null,y:re[1]??null,width:re[2]??null,height:re[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:k??null,tagName:Re,parent:Y??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Y&&Y.childrenBackendIds.push(_);let Ar=g.index.indexOf(x);if(Ar!==-1){let ne=g.value[Ar];i[ne]=He;let xe=r[ne]?.frameId;He.ownedFrameId=xe!==void 0?e[xe]:void 0}for(let ne of Object.keys(He.bounds)){let xe=ne;He.bounds[xe]!==null&&(He.bounds[xe]/=n)}let nt=ue!==void 0?d[ue]??[]:[];for(let ne=0;ne<nt.length&&!(ne>=t.length);ne++){let xe=nt[ne];if(xe===void 0||isNaN(xe))continue;let Ge=e[xe];if(Ge===void 0)continue;let wr=t[ne];He.computedStyles[wr]=Ge}for(let ne=0;ne<K.length;ne+=2){let xe=K[ne],Ge=K[ne+1];if(!xe||!Ge)continue;let wr=e[xe],fi=e[Ge];!wr||!fi||(He.attributes[wr]=fi)}R.index.includes(x)&&(He.attributes.checked="true"),a[He.backendNodeId]=He}return a[h[0]]}function og(r,e){if(r.mPathSelector)return r.mPathSelector;let t=r.parent,n;if(!t)n=r.tagName;else if(r.tagName==="body")n="body";else{let i=t.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(r.backendNodeId),a=` > ${r.tagName}:nth-child(${i+1})`;n=`${og(t,e)}${a}`}return r.mPathSelector=n,n}function mv(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var Jk=["html","#document","#document-fragment"];function fv({node:r,domGraph:e}){let t=[],n=r,o=mv(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=mv(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++,Jk.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,s=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${s})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&s++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function Sv(r,e){let t=r.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?t=t.frameLocator(a):t=t.locator(a)}}if(n.length&&(t=t.locator(n.join(" > "))),"owner"in t)throw new Error("Final locator from mpath is a frame locator");return t}async function yv(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:2e3})).attributes,i=to(o,Rn);if(!i)throw new Error(`Could not find attribute ${Rn} for object ${e}`);return i}function Ev(r){let e=[];for(let t=0;t<r.domGraph.roots.length;t++){let n=r.domGraph.roots[t],o=Qk({root:n,domGraph:r.domGraph,existingHashes:r.existingHashes,flagStore:r.flagStore,logger:r.logger});e=e.concat(o)}return e}function Qk(r){let{root:e,domGraph:t,existingHashes:n}=r,o=[],i=[e];for(;i.length;){let a=i.pop();if(a.nodeType===1&&a.tagName.toLowerCase()==="svg"){let l=Jc(a,t);l&&!n[l.hash]&&o.push(l)}for(let l of a.childrenBackendIds){let c=t.backendIdToNode[l];c&&i.push(c)}}return o}var e0=["focusable","keyshortcuts","controls","live","relevant","orientation"],t0=["selected","readonly","modal","required","invalid"],r0=["id","name","role","content"],Tv=["absolute","fixed","sticky"],n0=["i"],o0=["path"],i0=["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"],Rv=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Av=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],a0=["menulistpopup","statictext","inlinetextbox"],s0=80,bv=100,wv=50,lg=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],l0=["cite"],c0={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"]},u0={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},vv={indentLevel:0},ag=class r{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(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&t.length<wv?t:""),this.role=this.role||(e.domNode.attributes.role??""),g0(this.properties,e.domNode,e.importantProperties)}f0(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&&o0.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Av.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>Pv(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Mv(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),l=i[1]?.trim();if(a===void 0||l===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===l||l==="*")}))return!0}if(this.domNode&&n0.includes(this.domNode.tagName)||i0.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||fr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>Iv(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")?!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"))}isNotActionable(){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=vv){let t=Object.assign({},vv,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:l,condensedMode:c}=t,s=ig(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",m=this.name;d==="heading"&&m==="heading"&&(m=""),this.nameSources?.find(R=>!R.superseded&&R.type==="contents")&&this.children.length>0&&(m="");let h=this.nameSources?.find(R=>!R.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let R=h.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===m&&(m="")}let f=lg.includes(this.role)||l0.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${m}
4006
+ `;let E=`${u}<${p}`;!a&&!f&&(E+=` id="${this.id}"`);let S=l??!1;if((s.multiline||s.contenteditable)&&this.children.length>0&&(S=!0),d&&d!=="generic"&&d!==p&&!(c0[d]??[]).includes(p)&&(E+=` role=${JSON.stringify(d)}`),m&&(E+=` name=${JSON.stringify(m)}`),this.content&&!S&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isNotActionable()&&(E+=` ${fr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let R=this.domNode.bounds,w=Math.round(R.x??0),x=Math.round(R.y??0),_=Math.round((R.x??0)+(R.width??0)),M=Math.round((R.y??0)+(R.height??0));E+=` bounds=[${w} ${x} ${_} ${M}]`}let y=Date.now();if(Object.keys(s).length>0&&!i){if(Date.now()-y>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(s).forEach(([R,w])=>{if(!e0.includes(R)){{if(t0.includes(R)&&(!w||w==="false"))return;if(R==="value"&&S&&(s.type==="text"||this.role==="textbox"))return;if(R==="level"&&`${w}`=="1")return;if(R==="url"&&s.src&&p==="img")return;if(R==="url"&&s.href&&p==="a")return;if(R==="editable"&&w==="plaintext")return;if(R==="type"&&w===p)return;if(c&&!u0[R])return}typeof w=="string"?E+=` ${R}="${Qe(w,bv,!0)}"`:typeof w=="boolean"?w?E+=` ${R}`:E+=` ${R}={false}`:typeof w<"u"&&(E+=` ${R}={${Qe(JSON.stringify(w),bv,!0)}}`)}})}if(p==="::before"||p==="::after"){let R="";for(let w of this.children)R+=w.serialize({...e,indentLevel:n,neighbors:0});return R}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)E+=` />
4007
+ `;else{let R="";for(let x of this.children)R+=x.serialize({...e,indentLevel:n+2,neighbors:0});let w=R.trim();w.length<=s0&&!w.includes(`
4008
+ `)?E+=`>${w}</${p}>
4009
+ `:E+=`>
4009
4010
  ${R}${u}</${p}>
4010
4011
  `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let R=this.parent.children.findIndex(_=>_.id===this.id),w=R>0?this.parent.children[R-1]?.serialize({...e,neighbors:0}):"",x=R<this.parent.children.length-1?this.parent.children[R+1]?.serialize({...e,neighbors:0}):"";return`${w||""}
4011
- ${y}
4012
- ${x||""}`}return y}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:ng(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=ng(this.properties),e}},ig=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let m=n(p,l||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,l||u)return c;if(ag.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function Wk(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function qk(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(Jl({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(Jl({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function bv({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,showZeroOpacityElements:l,filterByViewport:c,viewportDetails:s,useMPaths:u,importantProperties:d,cdpClient:p,logger:m,callId:g}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let h=(L,M={})=>{},f=r.backendDOMNodeId,y=Hk.includes(r.role?.value?.toLowerCase()??"");if(!y&&f===void 0)return h("Filtering out node since it doesn't exist in the DOM"),[];let S=f?i.backendIdToNode[f]:void 0;if(!y&&!S)try{let L=await H(p.send({method:"DOM.describeNode",params:{backendNodeId:f}}),{milliseconds:750,fallback:()=>{m.debug("Timeout getting node from CDP while processing a11y tree")}});if(L&&L.node.nodeName.toLowerCase()==="slot"&&L.node.distributedNodes?.length)m.debug({redirectedDomNode:S,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:L},"Redirecting node to assigned slot");else return h("Filtering out node since it doesn't exist in the DOM",{cdpResult:L}),[]}catch(L){return h("Filtering out node since it doesn't exist in the DOM",{err:L}),[]}if(S&&e&&c&&s&&r.backendDOMNodeId&&!qk(S,s,m,g))return S.momenticIgnored=!0,[];if(S&&S.computedStyles.display==="none")return S.momenticIgnored=!0,[];if(S&&S.computedStyles.opacity==="0"&&l!==!0){if(l==="inputs-only"&&S.tagName.toLowerCase()!=="input")return S.momenticIgnored=!0,[];if(l===!1)return S.momenticIgnored=!0,[]}let T=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",A=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",R=new og({domNode:S,id:parseInt(r.nodeId),role:r.role?.value||"",name:T,nameSources:r.name?.sources,content:A,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(L=>yv.includes(L.name)||Ev.includes(L.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+Wk(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:d,parentFrame:n.type==="root"?void 0:n}),w=n,x=a[t],_=t;if(S?.tagName.toLowerCase()==="iframe"&&S.ownedFrameId){let L=n.childFrames.find(we=>we.frameId===S.ownedFrameId),M=o[L?.frameId??""]?.root,q=a[L?.frameId??""];if(L&&M&&q){r.childIds&&r.childIds.length>0&&m.debug("Replacing existing node's children with children from the iframe");let we=M;r.childIds=we.childIds,w=L,x=q,_=L.frameId}}let P=S?.childrenBackendIds?.length??0,Y=(r.childIds??[]).filter(L=>!!x.get(parseInt(L))).length;if(P>Y){let L=r.childIds?.map(q=>x.get(parseInt(q))).filter(Boolean).map(q=>q?.backendDOMNodeId).filter(q=>q!==void 0)??[],M=0;for(let q of S?.childrenBackendIds??[]){if(L.includes(q)){M=(r.childIds?.findIndex(ir=>x.get(parseInt(ir))?.backendDOMNodeId===q)??0)+1;continue}let we=i.backendIdToNode[q];if(!we||we?.tagName.toLowerCase()!=="svg")continue;let se=Math.floor(-1*Math.random()*1e7),ze={nodeId:se.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:q,frameId:_,role:{type:"string",value:"graphics-symbol"}};x.set(se,ze),r.childIds||(r.childIds=[]),r.childIds.splice(M,0,se.toString()),M++}}if(r.childIds?.length===1&&S){let L=x.get(parseInt(r.childIds[0])),M=L?.role?.value,q=S.childrenBackendIds;if(L&&M==="StaticText"&&q.length===1){let we=i.backendIdToNode[q[0]];if(we?.tagName?.toLowerCase()==="span"){let se=Math.floor(-1*Math.random()*1e7).toString(),ze={nodeId:se,parentId:r.nodeId,ignored:!1,backendDOMNodeId:we.backendNodeId,frameId:_,childIds:[L.nodeId]};L.parentId=se,x.set(parseInt(se),ze),r.childIds=[se]}}}for(let L of r.childIds??[]){if(!L)continue;let M=x.get(parseInt(L));if(!M)continue;let q=await bv({node:M,parent:R,domGraph:i,axGraph:o,frameId:_,frameContext:w,inputNodeMap:a,cdpClient:p,logger:m,callId:g,filterByViewport:c,showZeroOpacityElements:l,importantProperties:d,viewportDetails:s,useMPaths:u});q.length&&(R.children=R.children.concat(q))}if(R.role==="StaticText"&&(R.children=[]),R.children.length===1&&R.children[0].role==="StaticText"){let L=R.name,M=R.children[0]?.name;(L===M||!M)&&(R.children=[])}let $=[];for(let L=R.children.length-1;L>=0;L--){let M=R.children[L];if(M.role!=="StaticText"){$.push(M);continue}if(L===0||R.children[L-1].role!=="StaticText"){$.push(M);continue}R.children[L-1].name+=M.name}if(R.children=$.reverse(),!R.isInteresting(d)&&r.parentId)return S&&(S.momenticIgnored=!0),R.children;for(let L of R.children)L.parent=R;return Xk(R),S&&u&&rg(S,i),[R]}function vv({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:ag.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Kc(d,i),m=p?c[p.hash]:void 0,g=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=g)}for(let p of r.children)s=vv({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function Rv({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,importantProperties:l,viewportDetails:c,useMPaths:s,frameContext:u,iconKnowledgeBase:d}){let p=t??"root",m=r[p]?.root;if(!m)throw new Error("A11y tree has no root");let g=Dk(),h=R=>{let w=R.allNodes.filter(_=>!_.ignoredReasons?.find(Y=>yv.includes(Y.name))),x=new Map;return w.forEach(_=>{x.set(parseInt(_.nodeId),_)}),x},f={};Object.entries(r).forEach(([R,w])=>{f[R]=h(w)});let y=await bv({node:m,domGraph:e,parent:null,inputNodeMap:f,axGraph:r,frameId:p,frameContext:u,cdpClient:o,logger:n,callId:g,showZeroOpacityElements:a,importantProperties:l,filterByViewport:i,viewportDetails:c,useMPaths:s});if(y.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(y)}`);if(y.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let S={},T={},A={};return vv({node:y[0],a11yIdNodeMap:S,dataMomenticIdMap:T,selectorToNodeMap:A,domGraph:e,logger:n,callId:g,useMPaths:s,iconKnowledgeBase:d}),new ig(y[0],S,T,A)}function Kk(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<Tv&&!Lr.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(Av(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function Yk(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||Uk.includes(a);if((Lr.relevantElementAttributes.includes(a)||wv(a,t))&&!c){let u=Kk(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&hv.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of hv)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function Xk(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(Je(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let m=u.children.filter(g=>g.tagName==="th");if(m.length){if(i=m.map(g=>Je(g.name,100,!1)),i.length===m.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,g)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=g+1),p&&(m.properties.col||(m.properties.col=i[g])))})}}}function Jk(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function Av(r,e){if(e&&Cv(r,e))return!0;if(Lr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(Lr.alwaysInterestingClassNames.includes(r))return!0;for(let t of Lr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function wv(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function Cv(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var Yc=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await H(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await Z(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await H(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new C("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await H(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new C("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await H(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await H(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new C("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await H(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await H(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var ia="<empty>";function Qk(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function _v(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||Qk(r.url)}async function Zk(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function aa({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(_v(d.frame))return null;try{return await Iv({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function Iv({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await Zk(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=ro(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},m=(e.childFrames??[]).map(async(g,h)=>{if(_v(g.frame))return null;try{return await Iv({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(g=>g!==null),d}async function e0(r){try{return await r.owner().count()===1}catch{return!1}}async function t0(r){try{return await r.count()===1}catch{return!1}}async function rn(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,ia]){let p=o.frameLocator(d===ia?"iframe":`iframe[${d}]`);if(await e0(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new C("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,ia]){let u=o.locator(s===ia?"iframe":`iframe[${s}]`);if(await t0(u)){a=u,i.push(s);break}}if(!a)throw new C("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new C("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function xv(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function Pv({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===ia?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===ia?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=xv(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=xv(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new jr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Xc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function sg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function Mv(r){let e=sg(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function Ov(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function Lv({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await r0({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function r0({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await $o({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function Nv(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as o0}from"crypto";function Dv(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function kv(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let m=await e.fetch();s={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let u=await n0(t,c,s),d={};u.headers.forEach((m,g)=>{d[g]=m});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([m,g])=>({name:m,value:g})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Cs(o,n,i);for(let m of Object.values(a))m.onRequestComplete(i,n)}catch(m){m.message.includes("has been closed")||l.warn({err:m},"Failed to add response to HAR")}}async function n0(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function lg(r){try{await i0(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function i0(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=o0(),s=await Xm(e,n);try{Cs(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=Dv(n,l);u?await kv({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await a0({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function a0({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await Kb(i,e,l),Cs(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function s0(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function l0(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Jc(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function cg(r){let e=r.request(),t=r.status(),n=r.headers(),o=await l0(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await s0(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var no=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:wc(t,this.requestMatcher.urlMatcher)}};function Qc(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function Fv({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let g=await n.frameElement();p=await H(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as nn}from"crypto";import c0 from"js-beautify";var u0=["Dead"],Zc=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:nn(),type:"PRESET_ACTION",command:pn(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=pn(i);a={id:nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=pn(i);a={id:nn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=pn(i);a={id:nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:Ie(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=c0.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=kb(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...Ie(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,g=m?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(u0.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=pn("TYPE");i={id:nn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=pn("PRESS");i={id:nn(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:nn(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:nn(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=pn(s);u.deltaY=Math.abs(i);let d={id:nn(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=pn(s);u.deltaX=Math.abs(i);let d={id:nn(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as ug}from"zod";var kge=ug.object({type:ug.literal("url"),url:ug.string()});var eu=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let p=d.split(":");if(p.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let m=p[0]?.trim(),g=p[1]?.trim();if(m===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=sg(e),{frame:o,mPathSelectorTokens:i}=await rn(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await aa({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await Pv({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(Xc(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:Xc(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Lv({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await aa({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[H(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(rn(c,n).then(({frame:u})=>H(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await aa({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await Sr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new C("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Sr({fn:()=>aa({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await Sr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await Sr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Sr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Sr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:En,filterByViewport:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=dv({node:o,domGraph:this.domGraph});return pv(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await mv(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(Nr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await aa({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof C&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await Z(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Xc(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=ro(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await rn(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await rn(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new C("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c}){let s=await Rv({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!s||!s.root)throw new Error("Accessibility tree appears empty");return{tree:s}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await rn(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await ct({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(ro(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=ro(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(m){i.warn({err:m},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let m=0;m<3;m++)try{s=await Sr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let g=async()=>{try{let h=await Sr({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,signal:a,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(g())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Sr({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await Sr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await Sr({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await Z(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new C("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return uv({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=Mv(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function dg(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var gg=sa(hg(),"momentic","chromium"),M0=sa(hg(),"video"),nu=process.env.TWO_CAPTCHA_KEY,jv=_0(Vv);jv.use(I0({provider:{id:"2captcha",token:nu},visualFeedback:!0}));var yr=class r{static USER_AGENT=x0["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:t,enricher:n,browser:o,context:i,page:a,baseUrl:l,logger:c,userBrowserSettings:s,viewport:u,properties:d,clientCallbacks:p,iconKnowledgeBase:m}){if(sE(s),this.storage=e,this.flagStore=t,this.enricher=n,this.browser=o,this.context=i,this.page=a,this.baseUrl=l,this.logger=c,this.userControlledBrowserSettings=s,this.viewport=u,this.properties=d,this.clientCallbacks=p,d.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=m}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[$c]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:Lb.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&R0()==="darwin"&&f0("system_profiler SPDisplaysDataType").toString().includes("Retina")?(E.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await Yc.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new eu({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}),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 t=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:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,contextArgs:l,recordVideo:c,iconKnowledgeBase:s,callbacks:u}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let d;switch(a.browserType){case"Google Chrome":d="chrome";break;case"Chrome for Testing":d=void 0;break;case"Chromium":d="chromium";break;default:d="chromium";break}let p={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:d},m={...l??{},geolocation:l?.geolocation||Gn,locale:l?.locale||zn,timezoneId:l?.timezoneId||Hn,colorScheme:l?.colorScheme,httpCredentials:a.basicAuthorization?{username:a.basicAuthorization.username??"",password:a.basicAuthorization.password??""}:void 0,javaScriptEnabled:a.disableJavaScript?!1:void 0,ignoreHTTPSErrors:a.ignoreHttpsErrors??!1,userAgent:a.userAgent??r.USER_AGENT,viewport:l?.viewport??Mt},g=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],h=null,f,y,S={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(d==="chrome"||d==="chromium")&&(S.isNewHeadless=!0,p.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),a.disableGpu&&g.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let T=a.localChromeExtensionPaths?.map(R=>R.startsWith("~")?sa(hg(),R.slice(1)):R);if(T?.length){if(d===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let _ of T){let P=sa(_,"manifest.json");if(!ru(P))throw new C("UserConfigurationError",`Chrome extension path ${P} does not exist.`)}if(yn)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let R=sa(gg,`momentic-session-${Date.now()}`);if(!ru(R))try{S0(R,{recursive:!0})}catch(_){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${gg} folder: ${_}`)}let w=[...g],x=T.map(_=>C0(_)).join(",");w.push(`--disable-extensions-except=${x}`),m?.deviceScaleFactor&&w.push(`--force-device-scale-factor=${m.deviceScaleFactor}`,`--device-scale-factor=${m.deviceScaleFactor}`),m.viewport&&w.push(`--window-size=${m.viewport.width},${m.viewport.height}`),f=await Vv.launchPersistentContext(sa(gg,`momentic-session-${Date.now()}`),{...p,...m,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:w,baseURL:e}),t.debug({sharedContextOptions:m,sharedBrowserOptions:p,userBrowserSettings:a,chromeArgs:w,flags:o.getAllFlags(),properties:S,baseUrl:e},"Browser initialization context args (persistent)"),y=f.pages()[0]}else{h=await jv.launch({...p,args:g});let R={...m,baseURL:e,recordVideo:c?{dir:M0}:void 0};f=await h.newContext(R),t.debug({contextArgs:R,sharedBrowserOptions:p,chromeArgs:g,userBrowserSettings:a,flags:o.getAllFlags(),properties:S,baseUrl:e},"Browser initialization context args (standard)"),y=await f.newPage()}yn&&await f.route("**",Qc);let A=new r({browser:h,context:f,page:y,baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,viewport:m.viewport||Mt,properties:S,clientCallbacks:u,iconKnowledgeBase:s});return await A.initialize({grantPermissions:!0,runInitScripts:!1}),A}static async fromExistingContext({context:e,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,logger:a}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize(),s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,viewport:c,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await tg(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}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,t){let n=pg(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await H(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().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 t=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()||!Wo(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()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=pg(),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);e.on("console",a=>{jb(e,o,this.debugData,a,this.logger)});let i=async()=>{await qb(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await lg({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",Nv(this.customHeaders,this.logger)),yn&&await e.route("**/*",Qc),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let t=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),n=gv({domGraph:t,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(n.forEach(l=>{this.iconKnowledgeBase[l.hash]=l}),!n.length)return;let o=Ie(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:v0()};for(let l of["runId","testId"])o[l]&&(i[l]=o[l]);let a={metadata:i,newSvgs:n};this.clientCallbacks.onSvgsCollected(a)}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)}-${n}`;if(!t||t==="about:blank"||!Wo(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}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(t){this.logger.warn({err:t},"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){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();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 H(Qm(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{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.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await ct({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await Z(500),a%2===0&&t.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),ct({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],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")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)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:t=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:t});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(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await Z(250),this.screenshot({...e,retries:t-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:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await Hv.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&E0(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:3e3});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 y=await Hv.fromBuffer(c),S=y.bitmap.width,T=y.bitmap.height;m=Math.max(0,Math.min(m,S-1)),g=Math.max(0,Math.min(g,T-1)),h=Math.max(1,Math.min(h,S-m)),f=Math.max(1,Math.min(f,T-g)),c=await y.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(y){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${y}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){vT(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(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(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await Z(500),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:1e3})}if(!i)throw new C("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 l=this.url();if(Fb.has(l))throw new C("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await ct({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await tv({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await Z(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(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)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Sf}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"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(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return Wc({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=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:1e3}),this.originsVisited.delete(o);let t=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 Vb(i,this.logger),o!==t&&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 t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,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 Gb(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await Hb(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new C("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return tg(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowZeroOpacityOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowZeroOpacityOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof $r)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!zm.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!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:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<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 s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new C("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||Lr.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new C("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new C("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let S=c.parentFrame,{cache:T,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(S);d=T,p=A,u=A.frame,m="auto iframe"}else c.parentFrame&&s?(p=s,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:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Ie(i),frameCache:d},f,y=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:Ov(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),y=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,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{y&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowZeroOpacityOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await Z(500,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:m?i:En,allowZeroOpacityOverride:l,signal:a});break}catch(g){if(g instanceof Qa)break;if(g instanceof $r){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 Z(500,a)}a?.throwIfAborted(),m&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await Z(500,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowZeroOpacityOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=Ie(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowZeroOpacityOverride:a}){let l=[],c=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowZeroOpacityOverride:a})).serialize(),s;if(t.generatedSelectors||t.hybridSelector){let u;try{u=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowZeroOpacityOverride:a})}catch(d){s=d,d instanceof jr&&l.push(...d.decisions)}if(u)return{...u,pageState:void 0,decisions:[...l,...u.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:s?.message,selectors:xs(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw s;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let u=await this.resolveTargetWithSecondaryMethods({root:e,tree:c,target:t,decisions:l,logger:o,signal:i,allowZeroOpacityOverride:a});if(u)return u}throw new jr(`Could not find any relevant node given target: ${JSON.stringify(t)}`,l)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowZeroOpacityOverride:o}){if(!t.nodeOnlySerializedHtml)throw new Qa("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await ct({fn:S=>window.evaluatePrimaryCaches(S),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a},hybridParams:i&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=c.result;let S={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(S),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let S=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,T=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:S,selectors:T}),n.debug({reason:S,workingSelectors:T},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new jr("Cache evaluation failed",d);let p,m,g,h=!1;if(this.userBrowserSettings.visualActions){let S=s.mPath;if(!S)throw new Error("Found element did not have an mPath despite using visual actions");let T=S.join(" > ");p=e.locator(T),m=this.stateManager.getNodeUsingMPathSelector(T)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),m=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(p=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):p=e.locator(Nr(g));else throw new C("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=xs(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowZeroOpacityOverride:o});let y=mg(f,t);return y&&Object.keys(y).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Ie(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:y},"Updated cache")),{a11yNode:m,displayString:s.serializedElement,locator:p,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),m;try{return await p.waitFor({state:"attached",timeout:1e3}),m=await wn(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.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 C("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await Z(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;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(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,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:t,decisions:n,logger:o,signal:i,allowZeroOpacityOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await ct({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(Nr(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),m=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await wn(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=xs(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowZeroOpacityOverride:a,forceSaveNewCssSelectors:!0});let f=mg(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Ie(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"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:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"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: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&zm.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowZeroOpacityOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowZeroOpacityOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=P0(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:p,locator:m}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowZeroOpacityOverride:i}),g=p.boundingBox?.width,h=p.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=p.id,y=this.stateManager.a11yIdToNodeMap[f],S=xs(n);await this.updateCacheWithNewNodeDetails({target:n,node:y,locator:m,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:i});let T=mg(S,n);return T&&Object.keys(T).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Ie(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:T,templateMatch:d},"Updated cache after template matching resolution")),{locator:m,a11yNode:y,displayString:p.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=ev.some(a=>a===o.toLowerCase());return await Zm({targetingResult:t,options:{force:n.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return Zm({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),wc(l,t,n)){a=!0;break}await Z(500,this.abortSignal)}if(!a)throw new C("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${fc(t)} in ${o}ms.
4013
- Current tab: ${l}`);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,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new C("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await Z(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Jm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await Z(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await ei({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});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 ei({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await ct({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await ei({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await ei({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new C("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=qc(e);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:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=qc(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of dg(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=qc(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of dg(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});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:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowZeroOpacityOverride:i}=e,a=e.abortSignal??this.abortSignal,l=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let c=0,s;for(;c<t;){c++;try{return await H(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:l}),{milliseconds:this.pageLoadTimeout*c,signal:a,message:"Getting browser state took too long"})}catch(u){if(a?.throwIfAborted(),s=u instanceof Error?u.message:`${u}`,c>=t)throw u;n.warn({err:u,url:this.url()},"Error getting a11y tree, retrying...")}}throw new C("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${s}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await ct({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);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,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await Z(500,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){i=!0;break}}}async clickUsingVisualCoordinates(e,t){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:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await Z(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Jm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await Z(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await H(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let S=0;S<l.length;S++)if(c[S]===e){d=s.indexOf(S);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,y=m+h/2;return{centerX:f,centerY:y}}async scrollVertical(e){return eg({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 eg({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 createRawCDPSession(e){let t=await H(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),t}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,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await Z(500)}}throw o}async switchToPageHelper(e,t){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 C("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)}.
4014
- Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Wo(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,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Ul(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowZeroOpacityOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:nu,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await Z(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:nu,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&Fv({event:t,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,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];Wo(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}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:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await $o({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new C("UserInfrastructureError",`The page with URL ${Je(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await $o({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,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:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return T0.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:t,error:n}=await ct({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new C("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=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",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return ct({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=$n}){let i=Jb(),a={code:e,fragment:t,context:n},{result:l}=await H(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new C("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new C("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:cv,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowZeroOpacityOverride:e.allowZeroOpacityOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowZeroOpacityOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[An],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Nr(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 s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowZeroOpacityOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await H(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await wn(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:m,error:g,serializedElement:h,point:f,force:y,logs:S}=await e.evaluate(A=>{let R=window;if(!R.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return R.performTargetRedirection(A)},void 0,{timeout:1e3}),T=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:T,force:y,logs:S},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:T,force:y,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Nr(p)),hints:{clickableXY:f,force:y}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:T,force:y,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{clickableXY:f,force:y}};if(f)return t.info({point:f,serializedElement:h,duration:T,force:y,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:y}};if(y)return t.info({serializedElement:h,duration:T,force:y,logs:S},"Forcing click on original element"),{locator:e,hints:{force:y}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowZeroOpacityOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(Nb)?new $l(l.error):l.error.startsWith(Db)?new Wl(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){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*t);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,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),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:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!nu}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Ym(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!ru(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=t?.trim()||A0(e),o=y0(e),i=w0(e),a=kp[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!ru(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:b0.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),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:l,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 t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.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 t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??pg();return this.mocks[i]={matcher:t,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??5e3}get userBrowserSettings(){return xs(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import hz from"fetch-cookie";import{cloneDeep as Xw}from"lodash-es";var ou=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function O0(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function iu(r,e){let t=O0(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var SR="=",cu=";",xg=",";var yR=8192;var da={};a_(da,{getKeyPairs:()=>dF,parseKeyPairsIntoRecord:()=>pF,parsePairKeyValue:()=>ER,serializeKeyPairs:()=>uF});Pe();var cF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function uF(r){return r.reduce(function(e,t){var n=""+e+(e!==""?xg:"")+t;return n.length>yR?e:n},"")}function dF(r){return r.getAllEntries().map(function(e){var t=cF(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=cu+o.metadata.toString()),i})}function ER(r){var e=r.split(cu);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(SR);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Sg(e.join(cu))),{key:o,value:i,metadata:a}}}}}function pF(r){return typeof r!="string"||r.length===0?{}:r.split(xg).map(function(e){return ER(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Pe();var uu;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(uu||(uu={}));var mF=",",gF=["OTEL_SDK_DISABLED"];function hF(r){return gF.indexOf(r)>-1}var fF=["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 SF(r){return fF.indexOf(r)>-1}var yF=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function EF(r){return yF.indexOf(r)>-1}var _g=1/0,Ig=128,TF=128,bF=128,Pg={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:Ge.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:_g,OTEL_ATTRIBUTE_COUNT_LIMIT:Ig,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:_g,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Ig,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:_g,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Ig,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:TF,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:bF,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:uu.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 vF(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function RF(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function AF(r,e,t,n){n===void 0&&(n=mF);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var wF={ALL:Ge.ALL,VERBOSE:Ge.VERBOSE,DEBUG:Ge.DEBUG,INFO:Ge.INFO,WARN:Ge.WARN,ERROR:Ge.ERROR,NONE:Ge.NONE};function CF(r,e,t){var n=t[r];if(typeof n=="string"){var o=wF[n.toUpperCase()];o!=null&&(e[r]=o)}}function TR(r){var e={};for(var t in Pg){var n=t;switch(n){case"OTEL_LOG_LEVEL":CF(n,e,r);break;default:if(hF(n))vF(n,e,r);else if(SF(n))RF(n,e,r);else if(EF(n))AF(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Ct(){var r=TR(process.env);return Object.assign({},Pg,r)}function bR(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function du(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=bR(r.charCodeAt(n)),i=bR(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var vR="1.25.1";var xF="deployment.environment";var _F="process.runtime.name";var IF="service.name";var PF="service.instance.id";var MF="telemetry.sdk.name",OF="telemetry.sdk.language",LF="telemetry.sdk.version";var RR=xF;var AR=_F;var pu=IF;var wR=PF;var Ns=MF,Ds=OF,ks=LF;var NF="nodejs";var CR=NF;var pa,mu=(pa={},pa[Ns]="opentelemetry",pa[AR]="node",pa[Ds]=CR,pa[ks]=vR,pa);var DF=9,kF=6,FF=Math.pow(10,kF),UF=Math.pow(10,DF);function xR(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*FF);return[t,n]}function _R(r){return r[0]*UF+r[1]}function Fs(r){return r[0]*1e6+r[1]/1e3}var ni;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ni||(ni={}));var IR=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var BF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zF=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},PR=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new IR}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=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,zF([this._that],BF(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var Er;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Er||(Er={}));var kt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(kt||(kt={}));var HF=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var qye=function(r){HF(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function MR(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Pe();var Tr;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Tr||(Tr={}));var OR=function(){function r(){this.kind=Tr.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var ce;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ce||(ce={}));var GF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function VF(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Mg=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=VF(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.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 t=MR(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Og=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Tr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Mg(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Mg(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Mg(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.HISTOGRAM,dataPoints:n.map(function(i){var a=GF(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ce.GAUGE||e.type===ce.UP_DOWN_COUNTER||e.type===ce.OBSERVABLE_GAUGE||e.type===ce.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Pe();var Lg=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ng=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},Dg=function(){function r(e,t,n,o){e===void 0&&(e=new jF),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.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}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.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()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.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)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var jF=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,Ng([n,this._counts.length-t],Lg(this._counts.slice(t)),!1)),o.splice.apply(o,Ng([0,t],Lg(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(Ng([],Lg(this._counts),!1))},r}();var LR=52,$F=2146435072,WF=1048575,kg=1023,gu=-kg+1,hu=kg,Us=Math.pow(2,-1022);function fu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&$F)>>20;return n-kg}function Su(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&WF)*Math.pow(2,32);return o+n}function Bs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function DR(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var qF=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),oo=function(r){qF(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var FR=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Us)return this._minNormalLowerBoundaryIndex();var t=fu(e),n=this._rightShift(Su(e)-1,LR);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new oo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new oo("overflow: "+e+" is > maximum lower boundary: "+n);return Bs(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=gu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return hu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var UR=function(){function r(e){this._scale=e,this._scaleFactor=Bs(Math.LOG2E,e),this._inverseFactor=Bs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Us)return this._minNormalLowerBoundaryIndex()-1;if(Su(e)===0){var t=fu(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new oo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Us;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new oo("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return gu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(hu+1<<this._scale)-1},r}();var BR=-10,zR=20,KF=Array.from({length:31},function(r,e){return e>10?new UR(e-10):new FR(e-10)});function Fg(r){if(r>zR||r<BR)throw new oo("expected scale >= "+BR+" && <= "+zR+", got: "+r);return KF[r+10]}var YF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yu=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),XF=20,JF=160,Ug=2,QF=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=JF),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Dg),u===void 0&&(u=new Dg),d===void 0&&(d=Fg(XF)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<Ug&&(G.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Ug),this._maxSize=Ug)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.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(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=DR(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Fg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=yu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=yu.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new yu(0,-1);var o=t-n;return new yu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var HR=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Tr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new QF(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=YF(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ce.GAUGE||e.type===ce.UP_DOWN_COUNTER||e.type===ce.OBSERVABLE_GAUGE||e.type===ce.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var ZF=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Bg=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=xR(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var GR=function(){function r(){this.kind=Tr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Bg(e)},r.prototype.merge=function(e,t){var n=Fs(t.sampleTime)>=Fs(e.sampleTime)?t:e;return new Bg(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Fs(t.sampleTime)>=Fs(e.sampleTime)?t:e;return new Bg(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.GAUGE,dataPoints:n.map(function(i){var a=ZF(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var eU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},zs=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var zg=function(){function r(e){this.monotonic=e,this.kind=Tr.SUM}return r.prototype.createAccumulation=function(e){return new zs(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new zs(t.startTime,this.monotonic,o,t.reset):new zs(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new zs(t.startTime,this.monotonic,o,!0):new zs(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.SUM,dataPoints:n.map(function(i){var a=eU(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var oi=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),an=function(){function r(){}return r.Drop=function(){return XR},r.Sum=function(){return JR},r.LastValue=function(){return QR},r.Histogram=function(){return ZR},r.ExponentialHistogram=function(){return tU},r.Default=function(){return rU},r}();var VR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new OR,e}(an);var jR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ce.COUNTER:case ce.OBSERVABLE_COUNTER:case ce.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new zg(!0),e.NON_MONOTONIC_INSTANCE=new zg(!1),e}(an);var $R=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new GR,e}(an);var WR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Og([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(an);var qR=function(r){oi(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Og(this._boundaries,this._recordMinMax)},e}(an);var KR=function(r){oi(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new HR(this._maxSize,this._recordMinMax)},e}(an);var YR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ce.COUNTER:case ce.UP_DOWN_COUNTER:case ce.OBSERVABLE_COUNTER:case ce.OBSERVABLE_UP_DOWN_COUNTER:return JR;case ce.GAUGE:case ce.OBSERVABLE_GAUGE:return QR;case ce.HISTOGRAM:return t.advice.explicitBucketBoundaries?new qR(t.advice.explicitBucketBoundaries):ZR}return G.warn("Unable to recognize instrument type: "+t.type),XR},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(an);var XR=new VR,JR=new jR,QR=new $R,ZR=new WR,tU=new KR,rU=new YR;Pe();function Eu(){return"unknown_service:"+process.argv0}var io=function(){return io=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},io.apply(this,arguments)},nU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},oU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},iU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Hg=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return G.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[pu]=Eu(),e[Ds]=mu[Ds],e[Ns]=mu[Ns],e[ks]=mu[ks],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&G.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return nU(this,void 0,void 0,function(){return oU(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]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=io(io({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=iU(a,2),s=c[0],u=c[1];return io(io(io(io({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var ii;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(ii||(ii={}));Pe();var aU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},sU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Gg=function(){return Er.CUMULATIVE},eA=function(r){switch(r){case ce.COUNTER:case ce.OBSERVABLE_COUNTER:case ce.GAUGE:case ce.HISTOGRAM:case ce.OBSERVABLE_GAUGE:return Er.DELTA;case ce.UP_DOWN_COUNTER:case ce.OBSERVABLE_UP_DOWN_COUNTER:return Er.CUMULATIVE}},tA=function(r){switch(r){case ce.COUNTER:case ce.HISTOGRAM:return Er.DELTA;case ce.GAUGE:case ce.UP_DOWN_COUNTER:case ce.OBSERVABLE_UP_DOWN_COUNTER:case ce.OBSERVABLE_COUNTER:case ce.OBSERVABLE_GAUGE:return Er.CUMULATIVE}};function lU(){var r=Ct(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Gg:e==="delta"?eA:e==="lowmemory"?tA:(G.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),Gg)}function cU(r){return r!=null?r===ii.DELTA?eA:r===ii.LOWMEMORY?tA:Gg:lU()}function uU(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return an.Default()}}var rA=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=uU(t),this._aggregationTemporalitySelector=cU(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return aU(this,void 0,void 0,function(){return sU(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Pe();Pe();var dU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nA=1e4,oA=5,iA=1e3,aA=5e3,sA=1.5;function Hs(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=dU(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):G.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function Vg(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function jg(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return G.warn("Could not parse export URL: '"+r+"'"),r}}function $g(r){return typeof r=="number"?r<=0?Wg(r,nA):r:pU()}function pU(){var r,e=Number((r=Ct().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Ct().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Wg(e,nA):e}function Wg(r,e){return G.warn("Timeout must be greater than 0",r),e}function lA(r){var e=[429,502,503,504];return e.includes(r)}function cA(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var uA=function(){function r(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 PR(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=$g(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:ni.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:ni.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:ni.SUCCESS})}).catch(function(n){t({code:ni.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{G.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return G.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Pe();import*as qg from"url";import*as bu from"http";import*as vu from"https";import*as dA from"zlib";import{Readable as gU}from"stream";var ao;(function(r){r.NONE="none",r.GZIP="gzip"})(ao||(ao={}));var mU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ma=function(r){mU(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var Tu=function(){return Tu=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},Tu.apply(this,arguments)};function Kg(r,e,t,n,o){var i=r.timeoutMillis,a=new qg.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new ma("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Tu({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?bu.request:vu.request,g=function(h,f){switch(h===void 0&&(h=oA),f===void 0&&(f=iA),s=m(p,function(S){var T="";S.on("data",function(A){return T+=A}),S.on("aborted",function(){if(u){var A=new ma("Request Timeout");o(A)}}),S.on("end",function(){if(u===!1)if(S.statusCode&&S.statusCode<299)G.debug("statusCode: "+S.statusCode,T),n(),clearTimeout(d),clearTimeout(c);else if(S.statusCode&&lA(S.statusCode)&&h>0){var A=void 0;f=sA*f,S.headers["retry-after"]?A=cA(S.headers["retry-after"]):A=Math.round(Math.random()*(aA-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var R=new ma(S.statusMessage,S.statusCode,T);o(R),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(S){if(u){var T=new ma("Request Timeout",S.code);o(T)}else o(S);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var S=new ma("Request Timeout");o(S)}clearTimeout(d),clearTimeout(c)}),r.compression){case ao.GZIP:{s.setHeader("Content-Encoding","gzip");var y=hU(e);y.on("error",o).pipe(dA.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function hU(r){var e=new gU;return e.push(r),e.push(null),e}function Yg(r){if(r.httpAgentOptions&&r.keepAlive===!1){G.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new qg.URL(r.url),t=e.protocol==="http:"?bu.Agent:vu.Agent;return new t(Tu({keepAlive:!0},r.httpAgentOptions))}catch(n){G.error("collector exporter failed to create http agent. err: "+n.message);return}}function Xg(r){if(r)return r;var e=Ct().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Ct().OTEL_EXPORTER_OTLP_COMPRESSION;return e===ao.GZIP?ao.GZIP:ao.NONE}Pe();var fU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ru=function(r){fU(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&G.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,Hs(t.headers),da.parseKeyPairsIntoRecord(Ct().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Yg(t),i.compression=Xg(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){G.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;Kg(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(uA);function mA(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function SU(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function gA(r){var e=mA(r);return SU(e)}function yU(r){var e=mA(r);return e.toString()}var EU=typeof BigInt<"u"?yU:_R;function pA(r){return r}function hA(r){if(r!==void 0)return du(r)}var TU={encodeHrTime:gA,encodeSpanContext:du,encodeOptionalSpanContext:hA};function fA(r){var e,t;if(r===void 0)return TU;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?gA:EU,encodeSpanContext:o?pA:du,encodeOptionalSpanContext:o?pA:hA}}var bU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function SA(r){return{name:r.name,version:r.version}}function ga(r){return Object.keys(r).map(function(e){return yA(e,r[e])})}function yA(r,e){return{key:r,value:EA(e)}}function EA(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(EA)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=bU(t,2),o=n[0],i=n[1];return yA(o,i)})}}:{}}function TA(r){return{attributes:ga(r.attributes),droppedAttributesCount:0}}Pe();function vA(r,e){var t=fA(e);return{resource:TA(r.resource),schemaUrl:void 0,scopeMetrics:vU(r.scopeMetrics,t)}}function vU(r,e){return Array.from(r.map(function(t){return{scope:SA(t.scope),metrics:t.metrics.map(function(n){return RU(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function RU(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=xU(r.aggregationTemporality);switch(r.dataPointType){case kt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:bA(r,e)};break;case kt.GAUGE:t.gauge={dataPoints:bA(r,e)};break;case kt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:wU(r,e)};break;case kt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:CU(r,e)};break}return t}function AU(r,e,t){var n={attributes:ga(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case tr.INT:n.asInt=r.value;break;case tr.DOUBLE:n.asDouble=r.value;break}return n}function bA(r,e){return r.dataPoints.map(function(t){return AU(t,r.descriptor.valueType,e)})}function wU(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ga(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function CU(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ga(t.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(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function xU(r){switch(r){case Er.DELTA:return 1;case Er.CUMULATIVE:return 2}}function RA(r,e){return{resourceMetrics:r.map(function(t){return vA(t,e)})}}var Jg={serializeRequest:function(r){var e=RA(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var AA="0.52.1";var wA=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ha=function(){return ha=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},ha.apply(this,arguments)},CA="v1/metrics",_U="http://localhost:4318/"+CA,IU={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+AA},PU=function(r){wA(e,r);function e(t){var n=r.call(this,t,Jg,"application/json")||this;return n.headers=ha(ha(ha(ha({},n.headers),IU),da.parseKeyPairsIntoRecord(Ct().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Hs(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Ct().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?jg(Ct().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Ct().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?Vg(Ct().OTEL_EXPORTER_OTLP_ENDPOINT,CA):_U},e}(Ru),xA=function(r){wA(e,r);function e(t){return r.call(this,new PU(t),t)||this}return e}(rA);var fa;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(fa||(fa={}));var sn;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(sn||(sn={}));Pe();var MU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),_A=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},IA=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},OU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},LU=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},NU=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function PA(r){return r!=null}function Au(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function MA(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var Qg=function(r){MU(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function so(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new Qg("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function OA(r){return _A(this,void 0,void 0,function(){var e=this;return IA(this,function(t){return[2,Promise.all(r.map(function(n){return _A(e,void 0,void 0,function(){var o,i;return IA(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 LA(r){return r.status==="rejected"}function Zg(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,LU([],OU(e(n)),!1))}),t}function NA(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=NU(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function DA(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function kA(r,e){return r.toLowerCase()===e.toLowerCase()}Pe();var br;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(br||(br={}));var eh=function(){function r(){this.kind=br.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();Pe();var be;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(be||(be={}));function ln(r,e,t){var n,o,i,a;return kU(r)||G.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:tr.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function FA(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function UA(r,e){return kA(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var DU=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function kU(r){return r.match(DU)!=null}var FU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function UU(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var wu=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=UU(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.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 t=DA(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Cu=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=br.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new wu(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new wu(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new wu(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.HISTOGRAM,dataPoints:n.map(function(i){var a=FU(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===be.GAUGE||e.type===be.UP_DOWN_COUNTER||e.type===be.OBSERVABLE_GAUGE||e.type===be.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Pe();var th=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},rh=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},nh=function(){function r(e,t,n,o){e===void 0&&(e=new BU),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.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}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.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()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.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)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var BU=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,rh([n,this._counts.length-t],th(this._counts.slice(t)),!1)),o.splice.apply(o,rh([0,t],th(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(rh([],th(this._counts),!1))},r}();var BA=52,zU=2146435072,HU=1048575,oh=1023,xu=-oh+1,_u=oh,Gs=Math.pow(2,-1022);function Iu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&zU)>>20;return n-oh}function Pu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&HU)*Math.pow(2,32);return o+n}function Vs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function HA(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var GU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),lo=function(r){GU(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var VA=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Gs)return this._minNormalLowerBoundaryIndex();var t=Iu(e),n=this._rightShift(Pu(e)-1,BA);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new lo("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new lo("overflow: "+e+" is > maximum lower boundary: "+n);return Vs(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=xu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return _u>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var jA=function(){function r(e){this._scale=e,this._scaleFactor=Vs(Math.LOG2E,e),this._inverseFactor=Vs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Gs)return this._minNormalLowerBoundaryIndex()-1;if(Pu(e)===0){var t=Iu(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new lo("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Gs;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new lo("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return xu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(_u+1<<this._scale)-1},r}();var $A=-10,WA=20,VU=Array.from({length:31},function(r,e){return e>10?new jA(e-10):new VA(e-10)});function ih(r){if(r>WA||r<$A)throw new lo("expected scale >= "+$A+" && <= "+WA+", got: "+r);return VU[r+10]}var jU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Mu=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),$U=20,WU=160,ah=2,qA=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=WU),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new nh),u===void 0&&(u=new nh),d===void 0&&(d=ih($U)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<ah&&(G.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+ah),this._maxSize=ah)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.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(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=HA(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=ih(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Mu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Mu.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Mu(0,-1);var o=t-n;return new Mu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var sh=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=br.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new qA(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=jU(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===be.GAUGE||e.type===be.UP_DOWN_COUNTER||e.type===be.OBSERVABLE_GAUGE||e.type===be.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();Pe();var qU=yg("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function KA(r){return r.setValue(qU,!0)}Pe();function YA(){return function(r){G.error(KU(r))}}function KU(r){return typeof r=="string"?r:JSON.stringify(YU(r))}function YU(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var XU=YA();function Ou(r){try{XU(r)}catch{}}var XA="1.30.1";var JU="process.runtime.name";var QU="service.name";var ZU="telemetry.sdk.name",eB="telemetry.sdk.language",tB="telemetry.sdk.version";var JA=JU;var QA=QU;var js=ZU,$s=eB,Ws=tB;var rB="nodejs";var ZA=rB;var Sa,ai=(Sa={},Sa[js]="opentelemetry",Sa[JA]="node",Sa[$s]=ZA,Sa[Ws]=XA,Sa);function qs(r){r.unref()}var cB=9,uB=6,dB=Math.pow(10,uB),Jbe=Math.pow(10,cB);function si(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*dB);return[t,n]}function ya(r){return r[0]*1e6+r[1]/1e3}var Ks;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Ks||(Ks={}));Pe();function ew(r,e){return new Promise(function(t){ua.with(KA(ua.active()),function(){r.export(e,function(n){t(n)})})})}var tw={_export:ew};var pB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Lu=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=si(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var lh=function(){function r(){this.kind=br.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Lu(e)},r.prototype.merge=function(e,t){var n=ya(t.sampleTime)>=ya(e.sampleTime)?t:e;return new Lu(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ya(t.sampleTime)>=ya(e.sampleTime)?t:e;return new Lu(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.GAUGE,dataPoints:n.map(function(i){var a=pB(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var mB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ea=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Nu=function(){function r(e){this.monotonic=e,this.kind=br.SUM}return r.prototype.createAccumulation=function(e){return new Ea(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ea(t.startTime,this.monotonic,o,t.reset):new Ea(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Ea(t.startTime,this.monotonic,o,!0):new Ea(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.SUM,dataPoints:n.map(function(i){var a=mB(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var li=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),_n=function(){function r(){}return r.Drop=function(){return rw},r.Sum=function(){return nw},r.LastValue=function(){return ow},r.Histogram=function(){return iw},r.ExponentialHistogram=function(){return bB},r.Default=function(){return vB},r}();var gB=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new eh,e}(_n);var hB=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case be.COUNTER:case be.OBSERVABLE_COUNTER:case be.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Nu(!0),e.NON_MONOTONIC_INSTANCE=new Nu(!1),e}(_n);var fB=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new lh,e}(_n);var SB=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Cu([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(_n);var yB=function(r){li(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Cu(this._boundaries,this._recordMinMax)},e}(_n);var EB=function(r){li(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new sh(this._maxSize,this._recordMinMax)},e}(_n);var TB=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case be.COUNTER:case be.UP_DOWN_COUNTER:case be.OBSERVABLE_COUNTER:case be.OBSERVABLE_UP_DOWN_COUNTER:return nw;case be.GAUGE:case be.OBSERVABLE_GAUGE:return ow;case be.HISTOGRAM:return t.advice.explicitBucketBoundaries?new yB(t.advice.explicitBucketBoundaries):iw}return G.warn("Unable to recognize instrument type: "+t.type),rw},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(_n);var rw=new gB,nw=new hB,ow=new fB,iw=new SB,bB=new EB,vB=new TB;var aw=function(r){return _n.Default()},sw=function(r){return fa.CUMULATIVE};var ch=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},uh=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},lw=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},RB=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},cw=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:aw,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:sw,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return ch(this,void 0,void 0,function(){var t,n,o,i,a,l;return uh(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(RB([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],lw(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=lw.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(Zg(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(Zg(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return ch(this,void 0,void 0,function(){return uh(this,function(t){switch(t.label){case 0:return this._shutdown?(G.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,so(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return ch(this,void 0,void 0,function(){return uh(this,function(t){switch(t.label){case 0:return this._shutdown?(G.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,so(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Pe();var AB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Du=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ku=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},wB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},CB=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},dh=function(r){AB(e,r);function e(t){var n,o,i,a,l=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return Du(this,void 0,void 0,function(){var t;return ku(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,so(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof Qg?(G.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Ou(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Du(this,void 0,void 0,function(){var o,i,a,l,c,s;return ku(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&&(s=G).error.apply(s,CB(["PeriodicExportingMetricReader: metrics collection errors"],wB(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return l=u.sent(),G.debug("Error while resolving async portion of resource: ",l),Ou(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,tw._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Ks.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),qs(this._interval)},e.prototype.onForceFlush=function(){return Du(this,void 0,void 0,function(){return ku(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return Du(this,void 0,void 0,function(){return ku(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(cw);Pe();Pe();function Fu(){return"unknown_service:"+process.argv0}var co=function(){return co=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},co.apply(this,arguments)},xB=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},_B=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},IB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Uu=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return G.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[QA]=Fu(),e[$s]=ai[$s],e[js]=ai[js],e[Ws]=ai[Ws],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&G.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return xB(this,void 0,void 0,function(){return _B(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]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=co(co({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=IB(a,2),s=c[0],u=c[1];return co(co(co(co({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var uw=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Pe();var ci=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Bu=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=ua.active()),typeof e!="number"){G.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===tr.INT&&!Number.isInteger(e)&&(G.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,t,n,si(Date.now()))},r}();var dw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(Bu);var pw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){G.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Bu);var mw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(Bu);var gw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){G.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Bu);var zu=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var hw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(zu);var fw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(zu);var Sw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(zu);function Ys(r){return r instanceof zu}var yw=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=ln(e,be.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new mw(o,n)},r.prototype.createHistogram=function(e,t){var n=ln(e,be.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new gw(o,n)},r.prototype.createCounter=function(e,t){var n=ln(e,be.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new pw(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=ln(e,be.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new dw(o,n)},r.prototype.createObservableGauge=function(e,t){var n=ln(e,be.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new fw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=ln(e,be.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new hw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=ln(e,be.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Sw(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var Hu=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=ln(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var PB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Ew=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},MB=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return Ew(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return Ew(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var Dr=function(r){PB(e,r);function e(){return r.call(this,Au)||this}return e}(MB);var OB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Gu=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Dr,this._cumulativeMemoStorage=new Dr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Au(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=OB(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}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,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Dr,e},r}();var ph=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Tw=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Vu=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===fa.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=LB(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=ph(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new Dr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=ph(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var l=Tw(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=ph(e.keys()),l=a.next();!l.done;l=a.next()){var c=Tw(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function LB(r){return Array.from(r.entries())}var NB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),DB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},bw=function(r){NB(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Gu(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Vu(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Dr;Array.from(t.entries()).forEach(function(a){var l=DB(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(Hu);Pe();function mh(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
4012
+ ${E}
4013
+ ${x||""}`}return E}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:ig(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=ig(this.properties),e}},sg=class r{constructor(e,t,n,o){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingSummaries(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n={},o={},i={},a=c=>{let s=c.shallowClone();if(e[c.id])return s.properties["data-momentic-summary"]=e[c.id],n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s;let u=[];for(let d of c.children){let p=a(d);p&&(u.push(p),p.parent=s)}return s.children=u,n[c.id]=s,c.dataMomenticId&&(o[c.dataMomenticId]=s),c.mPathSelector&&(i[c.mPathSelector]=s),s},l=a(t);return new r(l,n,o,i)}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(i,a=!1){let l=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),s=i.children,u=!1,d=[];for(let p of s){let m=n(p,l||u);m&&(d.push(m),m.parent=c,u=!0)}if(c.children=d,l||u)return c;if(lg.includes(i.role)&&a)return c}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}pruneToSerializedCharLimit(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");let n=t.shallowClone(),o=()=>n.serialize().length,i=(a,l)=>{l.children=[];for(let c of a.children){let s=c.shallowClone();if(s.parent=l,l.children.push(s),o()>e){l.children.pop();break}if(i(c,s),o()>e){for(;s.children.length>0&&o()>e;)s.children.pop();if(o()>e){l.children.pop();break}}}};for(i(t,n);n.children.length>0&&o()>e;)n.children.pop();return new r(n,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function d0(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function p0(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(tc({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(tc({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function Cv({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:l,showZeroOpacityElements:c,filterByViewport:s,viewportDetails:u,useMPaths:d,importantProperties:p,cdpClient:m,logger:g,callId:h}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let f=(I,j={})=>{},E=r.backendDOMNodeId,S=a0.includes(r.role?.value?.toLowerCase()??"");if(!S&&E===void 0)return f("Filtering out node since it doesn't exist in the DOM"),[];let y=E?i.backendIdToNode[E]:void 0;if(!S&&!y)try{let I=await z(m.send({method:"DOM.describeNode",params:{backendNodeId:E}}),{milliseconds:750,fallback:()=>{g.debug("Timeout getting node from CDP while processing a11y tree")}});if(I&&I.node.nodeName.toLowerCase()==="slot"&&I.node.distributedNodes?.length)g.debug({redirectedDomNode:y,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:I},"Redirecting node to assigned slot");else return f("Filtering out node since it doesn't exist in the DOM",{cdpResult:I}),[]}catch(I){return f("Filtering out node since it doesn't exist in the DOM",{err:I}),[]}if(y&&e&&s&&u&&r.backendDOMNodeId&&!p0(y,u,g,h))return y.momenticIgnored=!0,[];if(y&&y.computedStyles.display==="none")return y.momenticIgnored=!0,[];if(y&&y.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&y.tagName.toLowerCase()!=="input")return y.momenticIgnored=!0,[];if(c===!1)return y.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",R=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new ag({domNode:y,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:R,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(I=>Rv.includes(I.name)||Av.includes(I.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+d0(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:l}),x=n,_=a[t],M=t;if(y?.tagName.toLowerCase()==="iframe"&&y.ownedFrameId){let I=n.childFrames.find(re=>re.frameId===y.ownedFrameId),j=o[I?.frameId??""]?.root,ue=a[I?.frameId??""];if(I&&j&&ue){r.childIds&&r.childIds.length>0&&g.debug("Replacing existing node's children with children from the iframe");let re=j;r.childIds=re.childIds,x=I,_=ue,M=I.frameId}}let K=y?.childrenBackendIds?.length??0,$=(r.childIds??[]).filter(I=>!!_.get(parseInt(I))).length;if(K>$){let I=r.childIds?.map(ue=>_.get(parseInt(ue))).filter(Boolean).map(ue=>ue?.backendDOMNodeId).filter(ue=>ue!==void 0)??[],j=0;for(let ue of y?.childrenBackendIds??[]){if(I.includes(ue)){j=(r.childIds?.findIndex(nt=>_.get(parseInt(nt))?.backendDOMNodeId===ue)??0)+1;continue}let re=i.backendIdToNode[ue];if(!re||re?.tagName.toLowerCase()!=="svg")continue;let Re=Math.floor(-1*Math.random()*1e7),He={nodeId:Re.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:ue,frameId:M,role:{type:"string",value:"graphics-symbol"}};_.set(Re,He),r.childIds||(r.childIds=[]),r.childIds.splice(j,0,Re.toString()),j++}}if(r.childIds?.length===1&&y){let I=_.get(parseInt(r.childIds[0])),j=I?.role?.value,ue=y.childrenBackendIds;if(I&&j==="StaticText"&&ue.length===1){let re=i.backendIdToNode[ue[0]];if(re?.tagName?.toLowerCase()==="span"){let Re=Math.floor(-1*Math.random()*1e7).toString(),He={nodeId:Re,parentId:r.nodeId,ignored:!1,backendDOMNodeId:re.backendNodeId,frameId:M,childIds:[I.nodeId]};I.parentId=Re,_.set(parseInt(Re),He),r.childIds=[Re]}}}for(let I of r.childIds??[]){if(!I)continue;let j=_.get(parseInt(I));if(!j)continue;let ue=await Cv({node:j,parent:w,domGraph:i,axGraph:o,frameId:M,frameContext:x,inputNodeMap:a,cdpClient:m,logger:g,callId:h,filterByViewport:s,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:l});ue.length&&(w.children=w.children.concat(ue))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let I=w.name,j=w.children[0]?.name;(I===j||!j)&&(w.children=[])}let k=[];for(let I=w.children.length-1;I>=0;I--){let j=w.children[I];if(j.role!=="StaticText"){k.push(j);continue}if(I===0||w.children[I-1].role!=="StaticText"){k.push(j);continue}w.children[I-1].name+=j.name}if(w.children=k.reverse(),!w.isInteresting(p)&&r.parentId)return y&&(y.momenticIgnored=!0),w.children;for(let I of w.children)I.parent=w;return h0(w),y&&d&&og(y,i),[w]}function xv({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:l,iconKnowledgeBase:c,startId:s=1}){r.id=s,s+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:lg.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(l[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let p=Jc(d,i),m=p?c[p.hash]:void 0,g=m?m.description:void 0;m&&(r.properties["data-momentic-description"]=g)}for(let p of r.children)s=xv({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s,useMPaths:a,domGraph:i,selectorToNodeMap:l,iconKnowledgeBase:c});return s}async function _v({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:l,importantProperties:c,viewportDetails:s,useMPaths:u,frameContext:d,iconKnowledgeBase:p}){let m=t??"root",g=r[m]?.root;if(!g)throw new Error("A11y tree has no root");let h=Zk(),f=w=>{let x=w.allNodes.filter(M=>!M.ignoredReasons?.find($=>Rv.includes($.name))),_=new Map;return x.forEach(M=>{_.set(parseInt(M.nodeId),M)}),_},E={};Object.entries(r).forEach(([w,x])=>{E[w]=f(x)});let S=await Cv({node:g,domGraph:e,parent:null,inputNodeMap:E,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:h,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:s,useMPaths:u,flagNotActionableNodes:l});if(S.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(S)}`);if(S.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let y={},A={},R={};return xv({node:S[0],a11yIdNodeMap:y,dataMomenticIdMap:A,selectorToNodeMap:R,domGraph:e,logger:n,callId:h,useMPaths:u,iconKnowledgeBase:p}),new sg(S[0],y,A,R)}function m0(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<wv&&!fr.bannedClassSubstrings.some(l=>a.includes(l))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(Iv(a,n)){i.push(a);continue}return i.length?i.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function g0(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,l])=>{let c=r[a]||a.startsWith("aria")||r0.includes(a);if((fr.relevantElementAttributes.includes(a)||Pv(a,t))&&!c){let u=m0(a,l,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&Tv.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of Tv)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&o.push(`position: ${n}`);let i;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(i="opacity: 0"),i&&o.push(i);for(let a of t?.styles??[]){let l=a.split(":"),c=l[0]?.trim(),s=l[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&s!==void 0&&u!==void 0&&(s==="*"||u===s)){let d=e.computedStyles[c],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function h0(r){let e=r.properties.class;if(typeof e=="string"&&e.includes("cm-content")){r.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){r.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),r.children.length>0&&(r.children[r.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(r.tagName==="table"){let i=[],a=r.children.find(c=>c.tagName==="thead");if(a){let c=a.children.find(s=>s.tagName==="tr");if(c){let s=c.children.filter(u=>u.tagName==="th");s.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(Qe(u.name,100,!1))}),i?.length!==s.length&&(i=void 0)}}let l=0;for(let c of r.children)if(c.tagName==="tbody")for(let s=0;s<c.children.length;s++){let u=c.children[s];if(u.tagName!=="tr")continue;if(s===0&&!i?.length){let m=u.children.filter(g=>g.tagName==="th");if(m.length){if(i=m.map(g=>Qe(g.name,100,!1)),i.length===m.length)continue;i=void 0}}l+=1,u.properties["row-index"]||(u.properties["row-index"]=l);let d=u.children.filter(m=>m.tagName==="td"||m.tagName==="th"),p=d.length===i?.length;d.forEach((m,g)=>{m.tagName!=="th"&&(m.properties["col-index"]||(m.properties["col-index"]=g+1),p&&(m.properties.col||(m.properties.col=i[g])))})}}}function f0(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function Iv(r,e){if(e&&Mv(r,e))return!0;if(fr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(fr.alwaysInterestingClassNames.includes(r))return!0;for(let t of fr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function Pv(r,e){if(e?.attributes?.includes(r))return!0;for(let t of e?.attributes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}function Mv(r,e){if(e?.classes?.includes(r))return!0;for(let t of e?.classes??[])if(t.endsWith("*")){let n=t.slice(0,-1);if(r.startsWith(n))return!0}return!1}var Qc=class r{constructor(e,t,n,o,i){this.session=e;this.logger=t;this.contextGetter=n;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:t,pageGetter:n,defaultTimeoutMs:o}){let i=t(),a=n(),l,c;for(let u=0;u<2;u++)try{l=await z(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await Z(500),c=d}if(!l)throw c;let s=new r(l,e,t,n,o);try{await z(s.registerHandlers(l),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw s.cdpFullyDead=!0,new C("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return s}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(t){this.logger.warn({err:t},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",t=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(t)},this.logger.error({payload:t},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(t)}`)}),e.on("Page.navigatedWithinDocument",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(t)}`)}),e.on("Page.lifecycleEvent",t=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(t)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await z(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new C("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await z(this.session.send(e,t),{milliseconds:n,message:o??`Chrome command ${e} timed out after ${n}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let t=e,n=this.pageGetter(),o=await z(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new C("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await z(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await z(t.detach(),{milliseconds:1e3})}catch(n){this.logger.warn({err:n},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(t){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${t}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,t){return this.session.on(e,t),this.session}off(e,t){return this.session.off(e,t),this.session}addListener(e,t){return this.session.addListener(e,t),this.session}removeListener(e,t){return this.session.removeListener(e,t),this.session}};var ia="<empty>";function S0(r){return r.includes("doubleclick.net")||r.includes("googletagmanager.com")||r.includes("googlesyndication.com")||r.includes("s.amazon-adsystem.com")||r.includes("smartadserver.com")||r.includes("omnitagjs.com")||r.includes("x.adroll.com")}function Lv(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||S0(r.url)}async function y0(r,e){let t=await r.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function aa({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),r.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),s=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(Lv(d.frame))return null;try{return await Nv({cdpClient:r,rawFrameTree:d,indices:[p],parent:n,warnings:o,logger:t})}catch(m){return o.push(`Failed to get child frame: ${m}`),null}}),u=await Promise.all(s);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function Nv({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,l=await y0(r,a),c=l.attributes??[],s=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=to(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(s=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:s,childFrames:[],parent:n,domNode:l},m=(e.childFrames??[]).map(async(g,h)=>{if(Lv(g.frame))return null;try{return await Nv({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(m)).filter(g=>g!==null),d}async function E0(r){try{return await r.owner().count()===1}catch{return!1}}async function T0(r){try{return await r.count()===1}catch{return!1}}async function rn(r,e){let t=[],n=r;for(;n.parent.type==="frame";)t.push(n.parent),n=n.parent;t.reverse();let o=e,i=[];for(let s of t){let u=!1;for(let d of[...s.locationData.attributeSelectors,ia]){let p=o.frameLocator(d===ia?"iframe":`iframe[${d}]`);if(await E0(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new C("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${s.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let s of[...r.locationData.attributeSelectors,ia]){let u=o.locator(s===ia?"iframe":`iframe[${s}]`);if(await T0(u)){a=u,i.push(s);break}}if(!a)throw new C("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let l=await a.evaluateHandle(s=>s,{timeout:1e3}),c=await l.asElement().contentFrame();if(!c)throw new C("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await l.dispose(),{frame:c,mPathSelectorTokens:i}}function Ov(r,e){let t=[...r],n=[];for(;t.length;){let o=t.shift();e(o)&&n.push(o),t.push(...o.childFrames)}return n}async function Dv({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let l=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===ia?l=l.length===1?l[0].childFrames:[]:l=l.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],s=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(s===ia?c=l:c=l.filter(u=>u.locationData.attributeSelectors.includes(s)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with mpath ${t.mPathSelectorTokens.join(" > ")}`)}if(t.frameSrcRegex){let l=new RegExp(t.frameSrcRegex),c=Ov(o,s=>!!s.src&&l.test(s.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with src regex ${t.frameSrcRegex}`),t.frameSrcRegex=void 0}if(t.frameUrlRegex){let l=new RegExp(t.frameUrlRegex),c=Ov(o,s=>!!s.url&&l.test(s.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${c.length} frames with url regex ${t.frameUrlRegex}`),t.frameUrlRegex=void 0}let a=o;for(let l=0;l<t.indices.length-1;l++)a=a[t.indices[l]]?.childFrames??[];if(n=a[t.indices[t.indices.length-1]],n)return i.push(`Found unique frame with indices ${t.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await rn(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new jr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function Zc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function cg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function kv(r){let e=cg(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let l=a.shift();l.src&&o.push(l.src),l.url&&i.push(l.url),a.push(...l.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function Fv(r){return r.type==="auto"?{type:"auto",frameId:r.handle.frameId,url:r.handle.url,src:r.handle.src??"",mPathSelectorTokens:r.mPathSelectorTokens.join(" > ")}:{type:"url",url:r.url}}async function Uv({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await b0({frameElementHandle:n,logger:e,signal:t})}catch(o){n?e.warn({err:o},"Failed to scroll iframe into view, trying with raw JS"):e.warn("Failed to scroll iframe into view - no frame element")}finally{await n?.dispose()}}async function b0({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await $o({promiseGenerator:async()=>r.evaluate(async i=>{let a=i.scrollTop;i.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),await new Promise(c=>setTimeout(c,250));let l=Date.now();for(;Date.now()-l<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(s=>setTimeout(s,250))}}),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}function Bv(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:l}of r)(!l||l.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as R0}from"crypto";function zv(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function Hv(r){let{route:e,mock:t,entry:n,debugData:o,requestId:i,requestRecorders:a,logger:l}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},s;if(t.fetchOriginalResponse){let m=await e.fetch();s={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let u=await v0(t,c,s),d={};u.headers.forEach((m,g)=>{d[g]=m});let p={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(p);try{n.response={status:p.status,statusText:u.statusText,headers:Object.entries(p.headers).map(([m,g])=>({name:m,value:g})),cookies:[],content:{mimeType:p.contentType,text:p.body},_mocked:!0},Is(o,n,i);for(let m of Object.values(a))m.onRequestComplete(i,n)}catch(m){m.message.includes("has been closed")||l.warn({err:m},"Failed to add response to HAR")}}async function v0(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function ug(r){try{await A0(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function A0(r){let{pageId:e,route:t,request:n,debugData:o,logger:i,requestRecorders:a,mocks:l}=r,c=R0(),s=await Qm(e,n);try{Is(o,s,c);for(let d of Object.values(a))d.onRequestStart(c,s)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=zv(n,l);u?await Hv({logger:i,route:t,mock:u,entry:s,debugData:o,requestId:c,requestRecorders:a}):await w0({route:t,request:n,debugData:o,logger:i,requestRecorders:a,entry:s,requestId:c})}async function w0({route:r,request:e,debugData:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let l=await e.response();if(!l||!i)return;await Zb(i,e,l),Is(t,i,a);for(let c of Object.values(o))c.onRequestComplete(a,i)}catch(l){l.message.includes("has been closed")||n.warn({err:l},"Failed to add response to HAR")}}async function C0(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function x0(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function eu(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function dg(r){let e=r.request(),t=r.status(),n=r.headers(),o=await x0(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await C0(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var ro=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:_c(t,this.requestMatcher.urlMatcher)}};function tu(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}async function Gv({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:l,properties:c}=r.target;if(l){i.error({error:l,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let s=n.parentFrame()?n.url():void 0,d=n.page().frames().map(g=>g.url());i.debug({frameUrl:s,...r},"Passive click event captured on element");let p,m;if(s)try{let g=await n.frameElement();p=await z(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:s});if(h.urlRegex)m={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),m={type:"url",url:s}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:m,frameBoundingBox:p})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as nn}from"crypto";import _0 from"js-beautify";var I0=["Dead"],ru=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:t,generator:n,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onStepRecorded(l,c)},onActionReceived:(l,c)=>{this.recordedSteps.set(c,{step:l}),t.onActionReceived?.(l,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:nn(),type:"PRESET_ACTION",command:pn(e)}}),this.nextStepOffset++,t}async recordElementAction(e){let{type:t,target:n,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,l=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=l,s;switch(e.frameConfig?e.frameBoundingBox?s={x:e.frameBoundingBox.x+n.properties.boundingBox.x,y:e.frameBoundingBox.y+n.properties.boundingBox.y,width:n.properties.boundingBox.width,height:n.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):s=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=pn(i);a={id:nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}}}};break}case"SELECT":{i="SELECT_OPTION";let h=pn(i);a={id:nn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:s}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=pn(i);a={id:nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...n.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:Pe(this.logger),boundingBox:s}}}};break}default:throw new Error(`Unknown action type: ${t}`)}let u;e.offset===void 0?(u=this.nextStepOffset,this.nextStepOffset++):u=e.offset,this.callbacks.onActionReceived?.(a,u);let d=e.target.browserState;try{d=_0.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Hb(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...Pe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=l}let m=this.recordedSteps.get(u)?.step??a,g=m?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...m,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(I0.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=pn("TYPE");i={id:nn(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=pn("PRESS");i={id:nn(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,l=this.nextStepOffset-1,c=this.recordedSteps.get(l),s=c?.step,u=s?.command;if(n){if(u?.type===i.command.type){let d=u.value,p=i.command.value;i={id:nn(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},a=l}else if(u?.type==="CLICK"&&i.command.type==="TYPE")s.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=l;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:nn(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=l}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let t=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_DOWN"&&l.deltaY?(i+=l.deltaY,c=a):l?.type==="SCROLL_UP"&&l.deltaY?(i-=l.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_DOWN":"SCROLL_UP",u=pn(s);u.deltaY=Math.abs(i);let d={id:nn(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,l=this.recordedSteps.get(a)?.step.command,c;l?.type==="SCROLL_RIGHT"&&l.deltaX?(i+=l.deltaX,c=a):l?.type==="SCROLL_LEFT"&&l.deltaX?(i-=l.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let s=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=pn(s);u.deltaX=Math.abs(i);let d={id:nn(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as pg}from"zod";var ehe=pg.object({type:pg.literal("url"),url:pg.string()});var nu=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:l,enricher:c,iconKnowledgeBase:s,userBrowserSettings:u}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=l,this.enricher=c,this.iconKnowledgeBase=s,this.userBrowserSettings=u,this.userBrowserSettings.importantStyles)for(let d of this.userBrowserSettings.importantStyles){let p=d.split(":");if(p.length!==2){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}let m=p[0]?.trim(),g=p[1]?.trim();if(m===void 0||g===void 0){this.logger.warn({style:d},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let t={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,t),t}async getAutoFrameDetailsFromHandle(e){let t=this.pageGetter(),n=cg(e),{frame:o,mPathSelectorTokens:i}=await rn(e,t),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:n,cache:a}}}async resolveAutoFrameCache(e){let t=this.pageGetter(),n=await aa({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await Dv({page:t,frameTree:n,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:t=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(Zc(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let n;return this.frameConfig.type==="url"?n=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:t}):n={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:Zc(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Uv({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await aa({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[z(n.evaluate(e,t),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),s=c.url;s==="about:blank"||s.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(rn(c,n).then(({frame:u})=>z(u.evaluate(e,t),{milliseconds:2e3})).catch(u=>(this.logger.warn({err:u,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),t=await aa({cdpClient:this.cdpClient,page:e,logger:this.logger}),n=Array.from(t.childFrames),o=[];for(;n.length>0;){let i=n.shift();n.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:t,logger:n}){return this.getDOMTree({devicePixelRatio:e??1,signal:t,logger:n??this.logger})}async getA11yTree(e){let t={},n=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,l,c=null;if(this.frameConfig?.type==="url"){if(a=await Sr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new C("ActionFailureError","Got null frame details despite active frame config");l=a.handle,c=l.frameId}else this.userBrowserSettings.autoExpandIframes?(l=await Sr({fn:()=>aa({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(l={type:"root",page:i,childFrames:[]},c=null);await Sr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:l.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let s=await Sr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await Sr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:l.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await Sr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:s,startingFrameId:c,frameContext:l,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=s,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:yn,filterByViewport:!1,flagNotActionableNodes:!1}),Math.random()<.1){let n=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:n&&n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:t,node:n}){if(n.backendNodeId===void 0)throw new Error(`Node with a11y id ${n.id} has no backend node ID: ${n.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[n.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${n.backendNodeId}`);let i=fv({node:o,domGraph:this.domGraph});return Sv(e,i)}else return this.getLocatorFromBackendId(t,n.backendNodeId)}async getLocatorFromBackendId(e,t){let n=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:t},timeout:2e3});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await yv(this.cdpClient,n.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(n.object)},"Failed to get ID attribute"),i}return e.locator(Nr(o))}getNodeUsingMPathSelector(e){let t=this.selectorToNodeMap[e];if(t)return t;let n=e.split(" > "),o="";for(let i=n.length-1;i>=0;i--){let a=n.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:t=this.abortSignalGetter(),logger:n=this.logger}){let o=Date.now(),i,a,l,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await aa({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),a=await this.getMatchingFrameByUrlWithCdp(i,e),n.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(s){if(l=s,s instanceof C&&s.reason==="UserInfrastructureError")throw s;c%3===0&&this.logger.warn({attempt:c,err:s},"Failed to resolve active frame, retrying..."),await Z(500,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Zc(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw l}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let l=i.shift(),c=l.domNode;i.push(...l.childFrames);let s=to(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!s&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[s,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:l,matchType:"regex",...await rn(l,o)});break}}else if(n.trim()===d.trim()){a.push({handle:l,matchType:"url",...await rn(l,o)});break}}}if(a.length===1){let l=a[0];return this.userBrowserSettings.autoExpandIframes||(l.handle.childFrames=[]),l}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new C("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:l,showZeroOpacityElements:c,flagNotActionableNodes:s}){let u=await _v({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:s,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:l,useMPaths:this.userBrowserSettings.visualActions});if(!u||!u.root)throw new Error("Accessibility tree appears empty");return{tree:u}}async addMomenticIds({rootPage:e,childFrames:t,frameFilter:n,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),l=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let s=async()=>{try{let{frame:u}=await rn(c,e);i=await this.addMomenticIdsHelper(u,i)}catch(u){c.url!=="about:blank"&&o.warn({err:u},"Error adding momentic IDs to child frame, continuing...")}};l.push(s())}await Promise.all(l)}async addMomenticIdsHelper(e,t){if(this.userBrowserSettings.visualActions)return t;let n=this.logger;return await dt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){n.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??t}getPageDomain(e){try{let t=new URL(e);if(!t.hostname)return null;let n=t.hostname.split("."),o=n.length>2?n.slice(-2).join("."):t.hostname;return`${t.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:t,handle:n}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:n.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${n.frameId} with url ${n.url}, allowing it to be fetched: ${o}`;return t?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let t=e.attributes??[];if(to(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=to(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:t,childFrames:n,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let l=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(m){i.warn({err:m},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,s;for(let m=0;m<3;m++)try{s=await Sr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(g){c=g,i.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!s)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=s,!this.userBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),p=[];for(;d.length>0;){let m=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:m,warnings:l});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;l.push(`Got error when determining whether to filter frame ${m.frameId} with url ${m.url}, allowing it to be fetched: ${h}`)}d.push(...m.childFrames);let g=async()=>{try{let h=await Sr({fn:()=>this.getRawA11yTreeForFrame({frameId:m.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${m.frameId}`,logObject:o,signal:a,logger:i});u[m.frameId]=h}catch(h){i.warn({err:h,url:m.url,src:m.src},`Error getting raw a11y tree for child frame ${m.frameId}, continuing...`)}};p.push(g())}return await Promise.all(p),l.length>0&&this.logger.warn({warnings:l},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await Sr({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await Sr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await Sr({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:t,timeoutMsg:`Fetching the document tree took over ${t}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:n,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:t,logger:n}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(l){await Z(500,t),i++,a=l}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new C("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return hv({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=kv(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(n);o?.srcRegex&&(t.frameSrcRegex=o.srcRegex),o?.urlRegex&&(t.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:n},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function mg(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var fg=la(Sg(),"momentic","chromium"),X0=la(Sg(),"video"),iu=process.env.TWO_CAPTCHA_KEY,Yv=q0(Kv);Yv.use(K0({provider:{id:"2captcha",token:iu},visualFeedback:!0}));var yr=class r{static USER_AGENT=W0["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:t,enricher:n,browser:o,context:i,page:a,baseUrl:l,logger:c,userBrowserSettings:s,viewport:u,properties:d,clientCallbacks:p,iconKnowledgeBase:m}){if(dE(s),this.storage=e,this.flagStore=t,this.enricher=n,this.browser=o,this.context=i,this.page=a,this.baseUrl=l,this.logger=c,this.userControlledBrowserSettings=s,this.viewport=u,this.properties=d,this.clientCallbacks=p,d.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=m}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let n={[Kc]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:Ub.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(n)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];t&&await this.page.reload();let i=l=>this.handleNewPageEvent(l);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&G0()==="darwin"&&D0("system_profiler SPDisplaysDataType").toString().includes("Retina")?(T.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await Qc.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new nu({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}),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 t=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:t}})}catch{}})()})}))}static async init({baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,contextArgs:l,recordVideo:c,iconKnowledgeBase:s,callbacks:u}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let d;switch(a.browserType){case"Google Chrome":d="chrome";break;case"Chrome for Testing":d=void 0;break;case"Chromium":d="chromium";break;default:d="chromium";break}let p={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:d},m={...l??{},geolocation:l?.geolocation||zn,locale:l?.locale||Un,timezoneId:l?.timezoneId||Bn,colorScheme:l?.colorScheme,httpCredentials:a.basicAuthorization?{username:a.basicAuthorization.username??"",password:a.basicAuthorization.password??""}:void 0,javaScriptEnabled:a.disableJavaScript?!1:void 0,ignoreHTTPSErrors:a.ignoreHttpsErrors??!1,userAgent:a.userAgent??r.USER_AGENT,viewport:l?.viewport??Mt},g=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],h=null,f,E,S={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(d==="chrome"||d==="chromium")&&(S.isNewHeadless=!0,p.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),a.disableGpu&&g.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let y=a.localChromeExtensionPaths?.map(R=>R.startsWith("~")?la(Sg(),R.slice(1)):R);if(y?.length){if(d===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let _ of y){let M=la(_,"manifest.json");if(!ou(M))throw new C("UserConfigurationError",`Chrome extension path ${M} does not exist.`)}if(Sn)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let R=la(fg,`momentic-session-${Date.now()}`);if(!ou(R))try{k0(R,{recursive:!0})}catch(_){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${fg} folder: ${_}`)}let w=[...g],x=y.map(_=>$0(_)).join(",");w.push(`--disable-extensions-except=${x}`),m?.deviceScaleFactor&&w.push(`--force-device-scale-factor=${m.deviceScaleFactor}`,`--device-scale-factor=${m.deviceScaleFactor}`),m.viewport&&w.push(`--window-size=${m.viewport.width},${m.viewport.height}`),f=await Kv.launchPersistentContext(la(fg,`momentic-session-${Date.now()}`),{...p,...m,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:w,baseURL:e}),t.debug({sharedContextOptions:m,sharedBrowserOptions:p,userBrowserSettings:a,chromeArgs:w,flags:o.getAllFlags(),properties:S,baseUrl:e},"Browser initialization context args (persistent)"),E=f.pages()[0]}else{h=await Yv.launch({...p,args:g});let R={...m,baseURL:e,recordVideo:c?{dir:X0}:void 0};f=await h.newContext(R),t.debug({contextArgs:R,sharedBrowserOptions:p,chromeArgs:g,userBrowserSettings:a,flags:o.getAllFlags(),properties:S,baseUrl:e},"Browser initialization context args (standard)"),E=await f.newPage()}Sn&&await f.route("**",tu);let A=new r({browser:h,context:f,page:E,baseUrl:e,logger:t,storage:n,flagStore:o,enricher:i,userBrowserSettings:a,viewport:m.viewport||Mt,properties:S,clientCallbacks:u,iconKnowledgeBase:s});return await A.initialize({grantPermissions:!0,runInitScripts:!1}),A}static async fromExistingContext({context:e,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,logger:a}){let l=e.pages()[0];if(!l)throw new Error("No page found in existing context");let c=l.viewportSize(),s=l?.url(),u=new r({browser:e.browser(),context:e,page:l,baseUrl:s,logger:a,storage:t,flagStore:n,enricher:o,userBrowserSettings:i,viewport:c,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await u.initialize({grantPermissions:!1,runInitScripts:!0}),u}async handleAvailableTabsChangeHelper(){try{let e=await ng(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}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,t){let n=gg(),o=`${e}-${n}`,i=Date.now(),a=!1,l=async()=>{try{await z(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=l().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 t=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()||!Wo(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()=>t())}handleNewPageEvent(e){let t=e.url();if(this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let n=e.video();n&&this.videos.push(n)}try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=gg(),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);e.on("console",a=>{Yb(e,o,this.debugData,a,this.logger)});let i=async()=>{await Qb(t,this.debugData,e),await e.route("**/*",async(a,l)=>{await ug({pageId:t,route:a,request:l,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",Bv(this.customHeaders,this.logger)),Sn&&await e.route("**/*",tu),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let t=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),n=Ev({domGraph:t,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(n.forEach(l=>{this.iconKnowledgeBase[l.hash]=l}),!n.length)return;let o=Pe(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:H0()};for(let l of["runId","testId"])o[l]&&(i[l]=o[l]);let a={metadata:i,newSvgs:n};this.clientCallbacks.onSvgsCollected(a)}handleFrameNavigationEvent(e){let t=e.url(),n=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${t.slice(0,50)}-${n}`;if(!t||t==="about:blank"||!Wo(t)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(l){this.logger.warn({err:l},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}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(t){this.logger.warn({err:t},"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){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();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 z(eg(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{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.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,n?.throwIfAborted();try{if(await dt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(l){if(i++,i>=3){t.warn({err:l},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await Z(500),a%2===0&&t.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),dt({root:e,fn:()=>{let t=window;if(!t?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return t.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,t=[],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")}),t.push(()=>{for(let[o,i]of n)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of t)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:t=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:t});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(t<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await Z(250),this.screenshot({...e,retries:t-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:t,saveToDiskPath:n,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let l=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(l.data,"base64"),s=await Wv.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(s.bitmap.width!==u||s.bitmap.height!==d)&&(c=await s.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&U0(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:3e3});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 E=await Wv.fromBuffer(c),S=E.bitmap.width,y=E.bitmap.height;m=Math.max(0,Math.min(m,S-1)),g=Math.max(0,Math.min(g,y-1)),h=Math.max(1,Math.min(h,S-m)),f=Math.max(1,Math.min(f,y-g)),c=await E.crop({x:m,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${g}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){CT(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();t||(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(s){if(a=s,this.abortSignal?.throwIfAborted(),this.logger.warn({err:s},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await Z(500),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:1e3})}if(!i)throw new C("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 l=this.url();if(Gb.has(l))throw new C("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(t)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElement(e){try{return await dt({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;return n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(t){this.logger.warn({err:t},"Failed to get active element");return}}async directTypeHelper(e,t={},n=!1){let o=await this.getActivePageOrFrame();await av({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await Z(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(t.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(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)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:t.delay??Tf}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(t){this.logger.warn({err:t},"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(l=>setTimeout(l,250))}},void 0,{timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:t}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(t.locator),!0}catch(t){return this.logger.debug({err:t,id:e},"Failed to highlight target"),!1}}async highlight(e){return Yc({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let t=new URL(e).origin;if(t==="null")return;this.originsVisited.add(t)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),t=Object.values(this.pageLoadPromises),n=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;t.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:n,outstandingPromises:t},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(t),t=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:1e3}),this.originsVisited.delete(o);let t=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 Kb(i,this.logger),o!==t&&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 t=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);t=t.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(l){this.logger.warn({err:l,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 qb(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let t=0,n=null;for(;t<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await Wb(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new C("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return ng(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowNotActionableNodesOverride:a,logger:l=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let c=await this.fetchHtmlAttributes({locator:n,logger:l,startingBoundingBox:i,allowNotActionableNodesOverride:a}),s=!1;for(let u of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let d=c?.[u];if(d&&!t[u]){s=!0;break}if(d&&JSON.stringify(d)!==JSON.stringify(t[u])){s=!0;break}}c&&(o||s)&&(t.generatedSelectors=c.generatedSelectors,t.serializedHtml=c.serializedHtml,t.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,t.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof $r)throw c;l.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:l,boundingBox:i})}catch(c){l.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!Gm.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:3e3})),!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:l=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-l)<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 s=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(s),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({locator:e,requirements:t}){let n={};if(t?.boundingBox){let o=await e.boundingBox({timeout:3e3});if(!o||!o.width||!o.height)throw new C("ActionFailureError","Element does not have a bounding box as required");n.boundingBox=o??void 0}if(t?.text){let o=await e.innerText({timeout:3e3});n.text=o?.trim()}if(t?.attributes&&t.attributes.length>0){let o={};for(let i of t.attributes){let a=i.trim().toLowerCase();if(!(!a||fr.bannedAiRequiredCacheAttributes.includes(a)))try{let l=await e.getAttribute(a,{timeout:3e3});l!==null&&(o[i]=l)}catch(l){this.logger.warn({err:l,attr:i},"Failed to fetch required attribute, continuing...")}}n.attributes=o}return n}async getAdditionalElementDetails({mainLocator:e,additionalElement:t,root:n,logger:o}){let i=this.stateManager.a11yIdToNodeMap[t.id];if(!i)return;let a=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:n,node:i});if(e.contentFrame!==a.contentFrame)return;let l=await this.fetchHtmlAttributes({locator:a,logger:o});if(!l?.generatedSelectors||l.generatedSelectors.length===0)return;let c={selectors:l.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,l=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let s=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!s)continue;l.push(s)}catch(s){this.logger.warn({err:s,additionalElement:c},"Failed to fetch additional element details, continuing...")}return l}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:l}){t&&(o.requirements=await this.getElementRequiredValues({locator:i,requirements:t})),n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:l}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:l}){if(e<0)throw new C("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new C("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,u,d,p,m;if(this.userBrowserSettings.autoExpandIframes&&!s&&c.parentFrame){let S=c.parentFrame,{cache:y,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(S);d=y,p=A,u=A.frame,m="auto iframe"}else c.parentFrame&&s?(p=s,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:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Pe(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:m,frameConfig:Fv(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:g,logger:i,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:l,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{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:l}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let m,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){m=f,await Z(500,a)}if(!g)throw m}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let s=Date.now(),u=0,d=0,p;for(;Date.now()-s<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let m=u===2||Date.now()-s>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,logger:m?i:yn,allowNotActionableNodesOverride:l,signal:a});break}catch(g){if(g instanceof ts)break;if(g instanceof $r){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 Z(500,a)}a?.throwIfAborted(),m&&i.info({err:g},`Could not resolve target using primary cache only (x${u})`),await Z(500,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:l}),t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=Pe(i),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){let l=sa(t),c=[],s=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),u;if(t.generatedSelectors||t.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a})}catch(p){u=p,p instanceof jr&&c.push(...p.decisions)}if(d)return{...d,pageState:void 0,decisions:[...c,...d.decisions]};n||(c.push({type:"CSS_SELECTOR",matched:!1,reason:u?.message,selectors:sa(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw u;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:s,target:t,decisions:c,logger:o,signal:i,allowNotActionableNodesOverride:a});if(d)return d}throw new jr(`Could not find any relevant node given target: ${JSON.stringify(l)}`,c)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o}){if(!t.nodeOnlySerializedHtml)throw new ts("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements},{css:l,hybrid:c}=await dt({fn:S=>window.evaluatePrimaryCaches(S),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a},hybridParams:i&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),s,u,d=[];if(i==="prefer"&&c?.result){s=c.result;let S={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};d.push(S),u="HYBRID_SELECTOR"}else if(l?.result){s=l.result;let S=`${s.workingSelectors.length} CSS selectors matched the following element: ${s.serializedElement}`,y=s.workingSelectors.slice(0,5);d.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:S,selectors:y}),n.debug({reason:S,workingSelectors:y},"Resolved with CSS selectors"),u="CSS_SELECTOR"}else throw d.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),c&&d.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new jr("Cache evaluation failed",d);let p,m,g,h=!1;if(this.userBrowserSettings.visualActions){let S=s.mPath;if(!S)throw new Error("Found element did not have an mPath despite using visual actions");let y=S.join(" > ");p=e.locator(y),m=this.stateManager.getNodeUsingMPathSelector(y)}else if(s.dataMomenticId!==void 0)g=parseInt(s.dataMomenticId),m=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in s?(p=e.locator(s.workingSelectors[0]),h=s.workingSelectors.length<5):p=e.locator(Nr(g));else throw new C("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&t.hybridSelector&&(c?.logs.length===1?n.warn({hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):c?.result?l?.result&&c?.result&&c.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(c.result.mPath)?n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==c.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):n.warn({originalCache:t,hybridResult:c,cssResult:l,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=sa(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:n,startingBoundingBox:s.boundingBox,forceSaveNewCssSelectors:h,allowNotActionableNodesOverride:o});let E=hg(f,t);return E&&Object.keys(E).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Pe(n),t.cacheResolutionUpdateSource=u,n.debug({diffs:E},"Updated cache")),{a11yNode:m,displayString:s.serializedElement,locator:p,decisions:d}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,l=await this.getActivePageOrFrame(),c=Date.now(),s=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),s++;let p=l.locator(n),m;try{return await p.waitFor({state:"attached",timeout:1e3}),m=await An(p,o)??"",d.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${n} matched an element on the page.`}),t?.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 C("ActionFailureError",`CSS selector '${n}' failed to resolve after ${s} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await Z(500,i)}}throw u}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:t,y:n,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let l=await a.locator.boundingBox({timeout:3e3});if(!l){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:s,width:u,height:d}=l;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(!t||!n||!c||!s){this.logger.debug({oldX:t,oldY:n,newX:c,newY:s,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(s-n)>100){this.logger.debug({newX:c,newY:s,oldX:t,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:t,decisions:n,logger:o,signal:i,allowNotActionableNodesOverride:a}){if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let s="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:s})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let s=await dt({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(.05*t.nodeOnlySerializedHtml.length);if(s&&s.closestDistance&&s.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${s.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:s.closestDistance,closestElement:s.closestNodeSerialized})}else{if(s?.error)throw new Error(s.error);if(s?.dataMomenticId||s?.mPathSelector){let d=s.dataMomenticId?parseInt(s.dataMomenticId):void 0,p,m;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],m=e.locator(Nr(d));else if(s.mPathSelector)p=this.stateManager.getNodeUsingMPathSelector(s.mPathSelector),m=e.locator(s.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=s.closestNodeSerialized??await An(m,o)??"unknown element";o.warn({result:s,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=sa(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:m,logger:o,startingBoundingBox:s.boundingBox,allowNotActionableNodesOverride:a,forceSaveNewCssSelectors:!0});let f=hg(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=Pe(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:s},"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:s.logs,distance:s.closestDistance,closestElement:g,savedElement:t.nodeOnlySerializedHtml}),{locator:m,a11yNode:p,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(s)}`)}}catch(s){o.info({err:s},"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: ${s}`})}let l=t.screenshotUrl,c=t.role??"";if(l&&Gm.includes(c))try{let s=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:l,signal:i,allowNotActionableNodesOverride:a});return{...s,decisions:[...n,...s.decisions],pageState:void 0}}catch(s){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${s}`,elementImageUrl:l}),o.warn({err:s},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:t,oldTarget:n,signal:o,allowNotActionableNodesOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let l=await this.screenshot({retries:0}),s=await(await fetch(t)).arrayBuffer(),u=Y0(),d=await this.enricher.runTemplateMatching({id:u,searchImageBase64String:Buffer.from(s).toString("base64"),pageImageBase64String:l.toString("base64")},{signal:o}),{target:p,locator:m}=await this.getTargetFromPositionPercentages({percentX:d.x,percentY:d.y,allowNotActionableNodesOverride:i}),g=p.boundingBox?.width,h=p.boundingBox?.height;if(!g||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=p.id,E=this.stateManager.a11yIdToNodeMap[f],S=sa(n);await this.updateCacheWithNewNodeDetails({target:n,node:E,locator:m,forceSaveNewCssSelectors:!0,allowNotActionableNodesOverride:i});let y=hg(S,n);return y&&Object.keys(y).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Pe(this.logger),n.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:u,diffs:y,templateMatch:d},"Updated cache after template matching resolution")),{locator:m,a11yNode:E,displayString:p.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:t}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:1e3})??"",i=iv.some(a=>a===o.toLowerCase());return await tg({targetingResult:t,options:{force:n.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return tg({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,l=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),l=this.url(),_c(l,t,n)){a=!0;break}await Z(500,this.abortSignal)}if(!a)throw new C("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${Ec(t)} in ${o}ms.
4014
+ Current tab: ${l}`);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,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:3e3});if(!o)throw new C("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,l=n.steps??5;await this.page.mouse.move(i,a,{steps:l}),await Z(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(Zm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await Z(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await ei({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:3e3});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 ei({func:t=>t.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let t=await this.getActivePageOrFrame();await dt({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await ei({func:t=>t.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,t,n=!1){await this.highlight(e.locator),await ei({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new C("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:3e3})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Xc(e);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:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=Xc(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of mg(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Xc(e);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of mg(e))await this.page.keyboard.up(n)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let n=0,o=2;for(;n<o;){n++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});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:t=2,logger:n=this.logger,skipWaitForPageLoad:o,allowNotActionableNodesOverride:i}=e,a=e.abortSignal??this.abortSignal,l=!i,c=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:a});let s=0,u;for(;s<t;){s++;try{return await z(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:c,flagNotActionableNodes:l}),{milliseconds:this.pageLoadTimeout*s,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),u=d instanceof Error?d.message:`${d}`,s>=t)throw d;n.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new C("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${u}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await dt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},l=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",l);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let s=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",s);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,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",l),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",s),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),l,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},s=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await Z(250,this.abortSignal),l)try{let d=await this.screenshot(c);if(!d.equals(l)){l=d,s=!1;continue}s=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{l=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<250)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:s}},"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,t){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:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,t,n){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await Z(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(Zm);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,t+i.top,{steps:n}),await Z(250),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),n=await z(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],i=o.layout,a=o.nodes,l=a.nodeName||[],c=a.backendNodeId||[],s=i.nodeIndex,u=i.bounds,d=-1;for(let S=0;S<l.length;S++)if(c[S]===e){d=s.indexOf(S);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,E=m+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return rg({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 rg({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 createRawCDPSession(e){let t=await z(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),t}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,t){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(t??this.pageLoadTimeout)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t}),this.handleAvailableTabsChange()}async switchToPage(e,t){let n=!0,o,i=Date.now();for(;n||t?.retry&&Date.now()-i<this.smartWaitingTimeout;){n=!1;try{await this.switchToPageHelper(e,t);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await Z(500)}}throw o}async switchToPageHelper(e,t){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 C("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)}.
4015
+ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!Wo(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,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Gl(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let l of Object.values(this.stateManager.a11yIdToNodeMap))if(l.role==="image"&&l.name.toLowerCase().includes("captcha")){if(!l.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,l.backendNodeId);break}if(!e){let l=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!l.captchas||!l.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:iu,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let l=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},l),new Error(l)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await Z(2500);let l=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:iu,taskId:o})});if(!l.ok){let s=`Captcha solution API returned error response: ${l.statusText}`;throw this.logger.error({text:await l.text()},s),new Error(s)}let c=await l.json();if(c.errorId){let s=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(s),new Error(s)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&Gv({event:t,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,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(l=>l.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let l;try{l=(await this.getOpenPages()).map(s=>s.url),o=0}catch(s){this.logger.debug({err:s},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let s=l.length-1;s>=n.length;s--){let u=l[s];Wo(u,this.logger)&&u!==c&&this.logger.info({lastActivePages:n,currentUrl:c,newOpenPages:l},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(s)});break}n=l};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(l){this.logger.error({err:l},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(t)})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}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:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await $o({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let l=a;if(l.name==="AbortError")throw new C("UserInfrastructureError",`The page with URL ${Qe(i,50)} did not load within the configured timeout (${o}ms): ${l}`);if(!l.message.includes("detached"))throw l}try{await $o({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,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:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return B0.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:t,error:n}=await dt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new C("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=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",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=2e3){let i=await this.getActivePageOrFrame();return dt({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=Vn}){let i=rv(),a={code:e,fragment:t,context:n},{result:l}=await z(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new C("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return l}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new C("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:l}=await this.getViewportOffsetDetails(e),c=Math.round(a),s=Math.round(l),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+s,m=d+c;return this.getDomNodeFromPixelPosition(p,m)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:gv,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[Rn],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let l=e.locator(Nr(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 s=await this.fetchHtmlAttributes({locator:l,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...s};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:l}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await z(this.performTargetRedirectionHelper(e,t,n),{milliseconds:3e3})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now(),i=await An(e,t);if(n===void 0&&(n=await e.boundingBox({timeout:3e3})??void 0),!n){t.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:l,width:c,height:s}=n,u=this.getViewport();if(a<0||l<0||!u||a+c>u.width||l+s>u.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let d=await this.getActivePageOrFrame(),{dataMomenticId:p,mPathSelector:m,error:g,serializedElement:h,point:f,force:E,logs:S}=await e.evaluate(A=>{let R=window;if(!R.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return R.performTargetRedirection(A)},void 0,{timeout:1e3}),y=Date.now()-o;if(g){t.warn({error:g,serializedElement:h,duration:y,force:E,logs:S},"Got error from target redirection with bounding box");return}else{if(p)return t.info({newDataMomenticId:p,serializedElement:h,duration:y,force:E,logs:S},"Redirected target to new element with bounding box with data-momentic-id"),{locator:d.locator(Nr(p)),hints:{clickableXY:f,force:E}};if(m)return t.info({newMPathSelector:m,serializedElement:h,duration:y,force:E,logs:S},"Redirected target to new element with bounding box with mPath"),{locator:d.locator(m),hints:{clickableXY:f,force:E}};if(f)return t.info({point:f,serializedElement:h,duration:y,force:E,logs:S},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:E}};if(E)return t.info({serializedElement:h,duration:y,force:E,logs:S},"Forcing click on original element"),{locator:e,hints:{force:E}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,l=await e.evaluate((c,s)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,s):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in l&&l.error)throw l.error.startsWith(Bb)?new Yl(l.error):l.error.startsWith(zb)?new Xl(l.error):new Error(l.error);return l.warnings.length&&t.warn(l,"Got warnings while generating HTML attributes for target"),l.attributes}async moveMouseFromPositionPercentages(e,t){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*t);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,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),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:1e3})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),l=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:l,x:n,y:o}}),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!iu}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Jm(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!ou(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=t?.trim()||V0(e),o=F0(e),i=j0(e),a=Bp[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!ou(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:z0.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(s){this.logger.error({err:s},"Error handling file chooser"),this.logToUserConsole(this.page,"error",s.message)}});let l=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:s,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=s;let p=atob(s),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:l,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 t={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.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 t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??gg();return this.mocks[i]={matcher:t,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??5e3}get userBrowserSettings(){return sa(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import Pz from"fetch-cookie";import{cloneDeep as uC}from"lodash-es";var au=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function J0(r){if(!r||r.length===0)return{};let e={};for(let t of r){let n=t.indexOf(":");if(n>-1){let o=t.slice(0,n).trim(),i=t.slice(n+1).trim();o&&(e[o]=i);continue}e[t]=!0}return e}function su(r,e){let t=J0(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var vR="=",du=";",Ig=",";var RR=8192;var pa={};T_(pa,{getKeyPairs:()=>PF,parseKeyPairsIntoRecord:()=>MF,parsePairKeyValue:()=>AR,serializeKeyPairs:()=>IF});Me();var _F=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function IF(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Ig:"")+t;return n.length>RR?e:n},"")}function PF(r){return r.getAllEntries().map(function(e){var t=_F(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=du+o.metadata.toString()),i})}function AR(r){var e=r.split(du);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(vR);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Eg(e.join(du))),{key:o,value:i,metadata:a}}}}}function MF(r){return typeof r!="string"||r.length===0?{}:r.split(Ig).map(function(e){return AR(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}Me();var pu;(function(r){r.AlwaysOff="always_off",r.AlwaysOn="always_on",r.ParentBasedAlwaysOff="parentbased_always_off",r.ParentBasedAlwaysOn="parentbased_always_on",r.ParentBasedTraceIdRatio="parentbased_traceidratio",r.TraceIdRatio="traceidratio"})(pu||(pu={}));var OF=",",LF=["OTEL_SDK_DISABLED"];function NF(r){return LF.indexOf(r)>-1}var DF=["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 kF(r){return DF.indexOf(r)>-1}var FF=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function UF(r){return FF.indexOf(r)>-1}var Pg=1/0,Mg=128,BF=128,zF=128,Og={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:Ve.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Pg,OTEL_ATTRIBUTE_COUNT_LIMIT:Mg,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Pg,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Mg,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Pg,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Mg,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:BF,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:zF,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:pu.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 HF(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function GF(r,e,t,n,o){if(n===void 0&&(n=-1/0),o===void 0&&(o=1/0),typeof t[r]<"u"){var i=Number(t[r]);isNaN(i)||(i<n?e[r]=n:i>o?e[r]=o:e[r]=i)}}function VF(r,e,t,n){n===void 0&&(n=OF);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var jF={ALL:Ve.ALL,VERBOSE:Ve.VERBOSE,DEBUG:Ve.DEBUG,INFO:Ve.INFO,WARN:Ve.WARN,ERROR:Ve.ERROR,NONE:Ve.NONE};function $F(r,e,t){var n=t[r];if(typeof n=="string"){var o=jF[n.toUpperCase()];o!=null&&(e[r]=o)}}function wR(r){var e={};for(var t in Og){var n=t;switch(n){case"OTEL_LOG_LEVEL":$F(n,e,r);break;default:if(NF(n))HF(n,e,r);else if(kF(n))GF(n,e,r);else if(UF(n))VF(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function Ct(){var r=wR(process.env);return Object.assign({},Og,r)}function CR(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function mu(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=CR(r.charCodeAt(n)),i=CR(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var xR="1.25.1";var WF="deployment.environment";var qF="process.runtime.name";var KF="service.name";var YF="service.instance.id";var XF="telemetry.sdk.name",JF="telemetry.sdk.language",QF="telemetry.sdk.version";var _R=WF;var IR=qF;var gu=KF;var PR=YF;var Fs=XF,Us=JF,Bs=QF;var ZF="nodejs";var MR=ZF;var ma,hu=(ma={},ma[Fs]="opentelemetry",ma[IR]="node",ma[Us]=MR,ma[Bs]=xR,ma);var eU=9,tU=6,rU=Math.pow(10,tU),nU=Math.pow(10,eU);function OR(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*rU);return[t,n]}function LR(r){return r[0]*nU+r[1]}function zs(r){return r[0]*1e6+r[1]/1e3}var ni;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ni||(ni={}));var NR=function(){function r(){var e=this;this._promise=new Promise(function(t,n){e._resolve=t,e._reject=n})}return Object.defineProperty(r.prototype,"promise",{get:function(){return this._promise},enumerable:!1,configurable:!0}),r.prototype.resolve=function(e){this._resolve(e)},r.prototype.reject=function(e){this._reject(e)},r}();var oU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},iU=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},DR=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new NR}return Object.defineProperty(r.prototype,"isCalled",{get:function(){return this._isCalled},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"promise",{get:function(){return this._deferred.promise},enumerable:!1,configurable:!0}),r.prototype.call=function(){for(var e,t=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,iU([this._that],oU(n),!1))).then(function(i){return t._deferred.resolve(i)},function(i){return t._deferred.reject(i)})}catch(i){this._deferred.reject(i)}}return this._deferred.promise},r}();var Er;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Er||(Er={}));var kt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(kt||(kt={}));var aU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}();var dEe=function(r){aU(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function kR(r,e){for(var t=0,n=r.length-1;n-t>1;){var o=Math.trunc((n+t)/2);r[o]<=e?t=o:n=o-1}return r[n]<=e?n:r[t]<=e?t:-1}Me();var Tr;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(Tr||(Tr={}));var FR=function(){function r(){this.kind=Tr.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();var ce;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ce||(ce={}));var sU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function lU(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var Lg=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=lU(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.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 t=kR(this._boundaries,e);this._current.buckets.counts[t+1]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Ng=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=Tr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Lg(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new Lg(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new Lg(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.HISTOGRAM,dataPoints:n.map(function(i){var a=sU(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ce.GAUGE||e.type===ce.UP_DOWN_COUNTER||e.type===ce.OBSERVABLE_GAUGE||e.type===ce.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Me();var Dg=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},kg=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},Fg=function(){function r(e,t,n,o){e===void 0&&(e=new cU),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.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}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.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()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.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)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var cU=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,kg([n,this._counts.length-t],Dg(this._counts.slice(t)),!1)),o.splice.apply(o,kg([0,t],Dg(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(kg([],Dg(this._counts),!1))},r}();var UR=52,uU=2146435072,dU=1048575,Ug=1023,fu=-Ug+1,Su=Ug,Hs=Math.pow(2,-1022);function yu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&uU)>>20;return n-Ug}function Eu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&dU)*Math.pow(2,32);return o+n}function Gs(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function zR(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var pU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),no=function(r){pU(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var GR=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Hs)return this._minNormalLowerBoundaryIndex();var t=yu(e),n=this._rightShift(Eu(e)-1,UR);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new no("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new no("overflow: "+e+" is > maximum lower boundary: "+n);return Gs(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=fu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Su>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var VR=function(){function r(e){this._scale=e,this._scaleFactor=Gs(Math.LOG2E,e),this._inverseFactor=Gs(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Hs)return this._minNormalLowerBoundaryIndex()-1;if(Eu(e)===0){var t=yu(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new no("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Hs;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new no("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return fu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Su+1<<this._scale)-1},r}();var jR=-10,$R=20,mU=Array.from({length:31},function(r,e){return e>10?new VR(e-10):new GR(e-10)});function Bg(r){if(r>$R||r<jR)throw new no("expected scale >= "+jR+" && <= "+$R+", got: "+r);return mU[r+10]}var gU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Tu=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),hU=20,fU=160,zg=2,SU=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=fU),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new Fg),u===void 0&&(u=new Fg),d===void 0&&(d=Bg(hU)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<zg&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+zg),this._maxSize=zg)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.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(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=zR(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=Bg(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Tu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Tu.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Tu(0,-1);var o=t-n;return new Tu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var WR=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=Tr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new SU(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=gU(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ce.GAUGE||e.type===ce.UP_DOWN_COUNTER||e.type===ce.OBSERVABLE_GAUGE||e.type===ce.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();var yU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Hg=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=OR(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var qR=function(){function r(){this.kind=Tr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Hg(e)},r.prototype.merge=function(e,t){var n=zs(t.sampleTime)>=zs(e.sampleTime)?t:e;return new Hg(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=zs(t.sampleTime)>=zs(e.sampleTime)?t:e;return new Hg(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.GAUGE,dataPoints:n.map(function(i){var a=yU(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var EU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Vs=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var Gg=function(){function r(e){this.monotonic=e,this.kind=Tr.SUM}return r.prototype.createAccumulation=function(e){return new Vs(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Vs(t.startTime,this.monotonic,o,t.reset):new Vs(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Vs(t.startTime,this.monotonic,o,!0):new Vs(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:kt.SUM,dataPoints:n.map(function(i){var a=EU(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var oi=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),an=function(){function r(){}return r.Drop=function(){return tA},r.Sum=function(){return rA},r.LastValue=function(){return nA},r.Histogram=function(){return oA},r.ExponentialHistogram=function(){return TU},r.Default=function(){return bU},r}();var KR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new FR,e}(an);var YR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ce.COUNTER:case ce.OBSERVABLE_COUNTER:case ce.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Gg(!0),e.NON_MONOTONIC_INSTANCE=new Gg(!1),e}(an);var XR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new qR,e}(an);var JR=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new Ng([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(an);var QR=function(r){oi(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new Ng(this._boundaries,this._recordMinMax)},e}(an);var ZR=function(r){oi(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new WR(this._maxSize,this._recordMinMax)},e}(an);var eA=function(r){oi(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ce.COUNTER:case ce.UP_DOWN_COUNTER:case ce.OBSERVABLE_COUNTER:case ce.OBSERVABLE_UP_DOWN_COUNTER:return rA;case ce.GAUGE:case ce.OBSERVABLE_GAUGE:return nA;case ce.HISTOGRAM:return t.advice.explicitBucketBoundaries?new QR(t.advice.explicitBucketBoundaries):oA}return H.warn("Unable to recognize instrument type: "+t.type),tA},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(an);var tA=new KR,rA=new YR,nA=new XR,oA=new JR,TU=new ZR,bU=new eA;Me();function bu(){return"unknown_service:"+process.argv0}var oo=function(){return oo=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},oo.apply(this,arguments)},vU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},RU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},AU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Vg=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return H.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[gu]=bu(),e[Us]=hu[Us],e[Fs]=hu[Fs],e[Bs]=hu[Bs],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return vU(this,void 0,void 0,function(){return RU(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]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=oo(oo({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=AU(a,2),s=c[0],u=c[1];return oo(oo(oo(oo({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var ii;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(ii||(ii={}));Me();var wU=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},CU=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},jg=function(){return Er.CUMULATIVE},iA=function(r){switch(r){case ce.COUNTER:case ce.OBSERVABLE_COUNTER:case ce.GAUGE:case ce.HISTOGRAM:case ce.OBSERVABLE_GAUGE:return Er.DELTA;case ce.UP_DOWN_COUNTER:case ce.OBSERVABLE_UP_DOWN_COUNTER:return Er.CUMULATIVE}},aA=function(r){switch(r){case ce.COUNTER:case ce.HISTOGRAM:return Er.DELTA;case ce.GAUGE:case ce.UP_DOWN_COUNTER:case ce.OBSERVABLE_UP_DOWN_COUNTER:case ce.OBSERVABLE_COUNTER:case ce.OBSERVABLE_GAUGE:return Er.CUMULATIVE}};function xU(){var r=Ct(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?jg:e==="delta"?iA:e==="lowmemory"?aA:(H.warn("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '"+r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE+"', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead."),jg)}function _U(r){return r!=null?r===ii.DELTA?iA:r===ii.LOWMEMORY?aA:jg:xU()}function IU(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return an.Default()}}var sA=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=IU(t),this._aggregationTemporalitySelector=_U(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return wU(this,void 0,void 0,function(){return CU(this,function(e){switch(e.label){case 0:return[4,this._otlpExporter.shutdown()];case 1:return e.sent(),[2]}})})},r.prototype.forceFlush=function(){return Promise.resolve()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r}();Me();Me();var PU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},lA=1e4,cA=5,uA=1e3,dA=5e3,pA=1.5;function js(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=PU(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):H.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function $g(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function Wg(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return H.warn("Could not parse export URL: '"+r+"'"),r}}function qg(r){return typeof r=="number"?r<=0?Kg(r,lA):r:MU()}function MU(){var r,e=Number((r=Ct().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:Ct().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Kg(e,lA):e}function Kg(r,e){return H.warn("Timeout must be greater than 0",r),e}function mA(r){var e=[429,502,503,504];return e.includes(r)}function gA(r){if(r==null)return-1;var e=Number.parseInt(r,10);if(Number.isInteger(e))return e>0?e*1e3:-1;var t=new Date(r).getTime()-Date.now();return t>=0?t:0}var hA=function(){function r(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 DR(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=qg(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:ni.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:ni.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:ni.SUCCESS})}).catch(function(n){t({code:ni.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{H.debug("items to be sent",e),t.send(e,n,o)}catch(i){o(i)}})},r.prototype.shutdown=function(){return this._shutdownOnce.call()},r.prototype.forceFlush=function(){return Promise.all(this._sendingPromises).then(function(){})},r.prototype._shutdown=function(){return H.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();Me();import*as Yg from"url";import*as Ru from"http";import*as Au from"https";import*as fA from"zlib";import{Readable as LU}from"stream";var io;(function(r){r.NONE="none",r.GZIP="gzip"})(io||(io={}));var OU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ga=function(r){OU(e,r);function e(t,n,o){var i=r.call(this,t)||this;return i.name="OTLPExporterError",i.data=o,i.code=n,i}return e}(Error);var vu=function(){return vu=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},vu.apply(this,arguments)};function Xg(r,e,t,n,o){var i=r.timeoutMillis,a=new Yg.URL(r.url),l=Number(process.versions.node.split(".")[0]),c,s,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,s.destroyed){var h=new ga("Request Timeout");o(h)}else l>=14?s.destroy():s.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:vu({"Content-Type":t},r.headers),agent:r.agent},m=a.protocol==="http:"?Ru.request:Au.request,g=function(h,f){switch(h===void 0&&(h=cA),f===void 0&&(f=uA),s=m(p,function(S){var y="";S.on("data",function(A){return y+=A}),S.on("aborted",function(){if(u){var A=new ga("Request Timeout");o(A)}}),S.on("end",function(){if(u===!1)if(S.statusCode&&S.statusCode<299)H.debug("statusCode: "+S.statusCode,y),n(),clearTimeout(d),clearTimeout(c);else if(S.statusCode&&mA(S.statusCode)&&h>0){var A=void 0;f=pA*f,S.headers["retry-after"]?A=gA(S.headers["retry-after"]):A=Math.round(Math.random()*(dA-f)+f),c=setTimeout(function(){g(h-1,f)},A)}else{var R=new ga(S.statusMessage,S.statusCode,y);o(R),clearTimeout(d),clearTimeout(c)}})}),s.on("error",function(S){if(u){var y=new ga("Request Timeout",S.code);o(y)}else o(S);clearTimeout(d),clearTimeout(c)}),s.on("abort",function(){if(u){var S=new ga("Request Timeout");o(S)}clearTimeout(d),clearTimeout(c)}),r.compression){case io.GZIP:{s.setHeader("Content-Encoding","gzip");var E=NU(e);E.on("error",o).pipe(fA.createGzip()).on("error",o).pipe(s);break}default:s.end(Buffer.from(e));break}};g()}function NU(r){var e=new LU;return e.push(r),e.push(null),e}function Jg(r){if(r.httpAgentOptions&&r.keepAlive===!1){H.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Yg.URL(r.url),t=e.protocol==="http:"?Ru.Agent:Au.Agent;return new t(vu({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function Qg(r){if(r)return r;var e=Ct().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||Ct().OTEL_EXPORTER_OTLP_COMPRESSION;return e===io.GZIP?io.GZIP:io.NONE}Me();var DU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),wu=function(r){DU(e,r);function e(t,n,o){t===void 0&&(t={});var i=r.call(this,t)||this;return i.DEFAULT_HEADERS={},i._contentType=o,t.metadata&&H.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,js(t.headers),pa.parseKeyPairsIntoRecord(Ct().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Jg(t),i.compression=Qg(t.compression),i._serializer=n,i}return e.prototype.onInit=function(t){},e.prototype.send=function(t,n,o){var i=this;if(this._shutdownOnce.isCalled){H.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,s){var u;Xg(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,s)}).then(n,o);this._sendingPromises.push(a);var l=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(l,l)},e.prototype.onShutdown=function(){},e}(hA);function yA(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function kU(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function EA(r){var e=yA(r);return kU(e)}function FU(r){var e=yA(r);return e.toString()}var UU=typeof BigInt<"u"?FU:LR;function SA(r){return r}function TA(r){if(r!==void 0)return mu(r)}var BU={encodeHrTime:EA,encodeSpanContext:mu,encodeOptionalSpanContext:TA};function bA(r){var e,t;if(r===void 0)return BU;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?EA:UU,encodeSpanContext:o?SA:mu,encodeOptionalSpanContext:o?SA:TA}}var zU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function vA(r){return{name:r.name,version:r.version}}function ha(r){return Object.keys(r).map(function(e){return RA(e,r[e])})}function RA(r,e){return{key:r,value:AA(e)}}function AA(r){var e=typeof r;return e==="string"?{stringValue:r}:e==="number"?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:e==="boolean"?{boolValue:r}:r instanceof Uint8Array?{bytesValue:r}:Array.isArray(r)?{arrayValue:{values:r.map(AA)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=zU(t,2),o=n[0],i=n[1];return RA(o,i)})}}:{}}function wA(r){return{attributes:ha(r.attributes),droppedAttributesCount:0}}Me();function xA(r,e){var t=bA(e);return{resource:wA(r.resource),schemaUrl:void 0,scopeMetrics:HU(r.scopeMetrics,t)}}function HU(r,e){return Array.from(r.map(function(t){return{scope:vA(t.scope),metrics:t.metrics.map(function(n){return GU(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function GU(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=WU(r.aggregationTemporality);switch(r.dataPointType){case kt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:CA(r,e)};break;case kt.GAUGE:t.gauge={dataPoints:CA(r,e)};break;case kt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:jU(r,e)};break;case kt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:$U(r,e)};break}return t}function VU(r,e,t){var n={attributes:ha(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case tr.INT:n.asInt=r.value;break;case tr.DOUBLE:n.asDouble=r.value;break}return n}function CA(r,e){return r.dataPoints.map(function(t){return VU(t,r.descriptor.valueType,e)})}function jU(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ha(t.attributes),bucketCounts:n.buckets.counts,explicitBounds:n.buckets.boundaries,count:n.count,sum:n.sum,min:n.min,max:n.max,startTimeUnixNano:e.encodeHrTime(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function $U(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ha(t.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(t.startTime),timeUnixNano:e.encodeHrTime(t.endTime)}})}function WU(r){switch(r){case Er.DELTA:return 1;case Er.CUMULATIVE:return 2}}function _A(r,e){return{resourceMetrics:r.map(function(t){return xA(t,e)})}}var Zg={serializeRequest:function(r){var e=_A(r,{useLongBits:!1}),t=new TextEncoder;return t.encode(JSON.stringify(e))},deserializeResponse:function(r){var e=new TextDecoder;return JSON.parse(e.decode(r))}};var IA="0.52.1";var PA=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),fa=function(){return fa=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},fa.apply(this,arguments)},MA="v1/metrics",qU="http://localhost:4318/"+MA,KU={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+IA},YU=function(r){PA(e,r);function e(t){var n=r.call(this,t,Zg,"application/json")||this;return n.headers=fa(fa(fa(fa({},n.headers),KU),pa.parseKeyPairsIntoRecord(Ct().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),js(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:Ct().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?Wg(Ct().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):Ct().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?$g(Ct().OTEL_EXPORTER_OTLP_ENDPOINT,MA):qU},e}(wu),OA=function(r){PA(e,r);function e(t){return r.call(this,new YU(t),t)||this}return e}(sA);var Sa;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Sa||(Sa={}));var sn;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(sn||(sn={}));Me();var XU=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),LA=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},NA=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},JU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},QU=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},ZU=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function DA(r){return r!=null}function Cu(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function kA(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var eh=function(r){XU(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function ao(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new eh("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function FA(r){return LA(this,void 0,void 0,function(){var e=this;return NA(this,function(t){return[2,Promise.all(r.map(function(n){return LA(e,void 0,void 0,function(){var o,i;return NA(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 UA(r){return r.status==="rejected"}function th(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,QU([],JU(e(n)),!1))}),t}function BA(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=ZU(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(l){t={error:l}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function zA(r,e){for(var t=0,n=r.length-1,o=r.length;n>=t;){var i=t+Math.trunc((n-t)/2);r[i]<e?t=i+1:(o=i,n=i-1)}return o}function HA(r,e){return r.toLowerCase()===e.toLowerCase()}Me();var br;(function(r){r[r.DROP=0]="DROP",r[r.SUM=1]="SUM",r[r.LAST_VALUE=2]="LAST_VALUE",r[r.HISTOGRAM=3]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"})(br||(br={}));var rh=function(){function r(){this.kind=br.DROP}return r.prototype.createAccumulation=function(){},r.prototype.merge=function(e,t){},r.prototype.diff=function(e,t){},r.prototype.toMetricData=function(e,t,n,o){},r}();Me();var ge;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ge||(ge={}));function ln(r,e,t){var n,o,i,a;return tB(r)||H.warn('Invalid metric name: "'+r+'". The metric name should be a ASCII string with a length no greater than 255 characters.'),{name:r,type:e,description:(n=t?.description)!==null&&n!==void 0?n:"",unit:(o=t?.unit)!==null&&o!==void 0?o:"",valueType:(i=t?.valueType)!==null&&i!==void 0?i:tr.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function GA(r,e){var t,n;return{name:(t=r.name)!==null&&t!==void 0?t:e.name,description:(n=r.description)!==null&&n!==void 0?n:e.description,type:e.type,unit:e.unit,valueType:e.valueType,advice:e.advice}}function VA(r,e){return HA(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var eB=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function tB(r){return r.match(eB)!=null}var rB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function nB(r){var e=r.map(function(){return 0});return e.push(0),{buckets:{boundaries:r,counts:e},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}var xu=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=nB(t)),this.startTime=e,this._boundaries=t,this._recordMinMax=n,this._current=o}return r.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 t=zA(this._boundaries,e);this._current.buckets.counts[t]+=1}},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var _u=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=br.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new xu(e,this._boundaries,this._recordMinMax)},r.prototype.merge=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=i[c]+a[c];var s=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(s=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(s=n.min,u=n.max):o.hasMinMax&&(s=o.min,u=o.max)),new xu(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:s,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,l=new Array(i.length),c=0;c<i.length;c++)l[c]=a[c]-i[c];return new xu(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:l},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.HISTOGRAM,dataPoints:n.map(function(i){var a=rB(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ge.GAUGE||e.type===ge.UP_DOWN_COUNTER||e.type===ge.OBSERVABLE_GAUGE||e.type===ge.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,buckets:s.buckets,count:s.count}}})}},r}();Me();var nh=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},oh=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},ih=function(){function r(e,t,n,o){e===void 0&&(e=new oB),t===void 0&&(t=0),n===void 0&&(n=0),o===void 0&&(o=0),this.backing=e,this.indexBase=t,this.indexStart=n,this.indexEnd=o}return Object.defineProperty(r.prototype,"offset",{get:function(){return this.indexStart},enumerable:!1,configurable:!0}),Object.defineProperty(r.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}),r.prototype.counts=function(){var e=this;return Array.from({length:this.length},function(t,n){return e.at(n)})},r.prototype.at=function(e){var t=this.indexBase-this.indexStart;return e<t&&(e+=this.backing.length),e-=t,this.backing.countAt(e)},r.prototype.incrementBucket=function(e,t){this.backing.increment(e,t)},r.prototype.decrementBucket=function(e,t){this.backing.decrement(e,t)},r.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()},r.prototype.downscale=function(e){this._rotate();for(var t=1+this.indexEnd-this.indexStart,n=1<<e,o=0,i=0,a=this.indexStart;a<=this.indexEnd;){var l=a%n;l<0&&(l+=n);for(var c=l;c<n&&o<t;c++)this._relocateBucket(i,o),o++,a++;i++}this.indexStart>>=e,this.indexEnd>>=e,this.indexBase=this.indexStart},r.prototype.clone=function(){return new r(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)},r.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)},r.prototype._relocateBucket=function(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))},r}();var oB=function(){function r(e){e===void 0&&(e=[0]),this._counts=e}return Object.defineProperty(r.prototype,"length",{get:function(){return this._counts.length},enumerable:!1,configurable:!0}),r.prototype.countAt=function(e){return this._counts[e]},r.prototype.growTo=function(e,t,n){var o=new Array(e).fill(0);o.splice.apply(o,oh([n,this._counts.length-t],nh(this._counts.slice(t)),!1)),o.splice.apply(o,oh([0,t],nh(this._counts.slice(0,t)),!1)),this._counts=o},r.prototype.reverse=function(e,t){for(var n=Math.floor((e+t)/2)-e,o=0;o<n;o++){var i=this._counts[e+o];this._counts[e+o]=this._counts[t-o-1],this._counts[t-o-1]=i}},r.prototype.emptyBucket=function(e){var t=this._counts[e];return this._counts[e]=0,t},r.prototype.increment=function(e,t){this._counts[e]+=t},r.prototype.decrement=function(e,t){this._counts[e]>=t?this._counts[e]-=t:this._counts[e]=0},r.prototype.clone=function(){return new r(oh([],nh(this._counts),!1))},r}();var jA=52,iB=2146435072,aB=1048575,ah=1023,Iu=-ah+1,Pu=ah,$s=Math.pow(2,-1022);function Mu(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&iB)>>20;return n-ah}function Ou(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&aB)*Math.pow(2,32);return o+n}function Ws(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function WA(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var sB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),so=function(r){sB(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var KA=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<$s)return this._minNormalLowerBoundaryIndex();var t=Mu(e),n=this._rightShift(Ou(e)-1,jA);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new so("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new so("overflow: "+e+" is > maximum lower boundary: "+n);return Ws(1,e<<this._shift)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._shift===0?0:-this._shift},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){var e=Iu>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Pu>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var YA=function(){function r(e){this._scale=e,this._scaleFactor=Ws(Math.LOG2E,e),this._inverseFactor=Ws(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=$s)return this._minNormalLowerBoundaryIndex()-1;if(Ou(e)===0){var t=Mu(e);return(t<<this._scale)-1}var n=Math.floor(Math.log(e)*this._scaleFactor),o=this._maxNormalLowerBoundaryIndex();return n>=o?o:n},r.prototype.lowerBoundary=function(e){var t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1<<this._scale))/this._scaleFactor);throw new so("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return $s;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new so("overflow: "+e+" is < minimum lower boundary: "+n)}return Math.exp(e*this._inverseFactor)},Object.defineProperty(r.prototype,"scale",{get:function(){return this._scale},enumerable:!1,configurable:!0}),r.prototype._minNormalLowerBoundaryIndex=function(){return Iu<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Pu+1<<this._scale)-1},r}();var XA=-10,JA=20,lB=Array.from({length:31},function(r,e){return e>10?new YA(e-10):new KA(e-10)});function sh(r){if(r>JA||r<XA)throw new so("expected scale >= "+XA+" && <= "+JA+", got: "+r);return lB[r+10]}var cB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Lu=function(){function r(e,t){this.low=e,this.high=t}return r.combine=function(e,t){return new r(Math.min(e.low,t.low),Math.max(e.high,t.high))},r}(),uB=20,dB=160,lh=2,QA=function(){function r(e,t,n,o,i,a,l,c,s,u,d){e===void 0&&(e=e),t===void 0&&(t=dB),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),l===void 0&&(l=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),s===void 0&&(s=new ih),u===void 0&&(u=new ih),d===void 0&&(d=sh(uB)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=l,this._max=c,this._positive=s,this._negative=u,this._mapping=d,this._maxSize<lh&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+lh),this._maxSize=lh)}return r.prototype.record=function(e){this.updateByIncrement(e,1)},r.prototype.setStartTime=function(e){this.startTime=e},r.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(r.prototype,"sum",{get:function(){return this._sum},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"zeroCount",{get:function(){return this._zeroCount},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"scale",{get:function(){return this._count===this._zeroCount?0:this._mapping.scale},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"positive",{get:function(){return this._positive},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"negative",{get:function(){return this._negative},enumerable:!1,configurable:!0}),r.prototype.updateByIncrement=function(e,t){if(!Number.isNaN(e)){if(e>this._max&&(this._max=e),e<this._min&&(this._min=e),this._count+=t,e===0){this._zeroCount+=t;return}this._sum+=e*t,e>0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)}},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)},r.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 t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)},r.prototype.clone=function(){return new r(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)},r.prototype._updateBuckets=function(e,t,n){var o=this._mapping.mapToIndex(t),i=!1,a=0,l=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,l=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,l=e.indexStart,a=o),i){var c=this._changeScale(a,l);this._downscale(c),o=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,o,n)},r.prototype._incrementIndexBy=function(e,t,n){if(n!==0){if(e.length===0&&(e.indexStart=e.indexEnd=e.indexBase=t),t<e.indexStart){var o=e.indexEnd-t;o>=e.backing.length&&this._grow(e,o+1),e.indexStart=t}else if(t>e.indexEnd){var o=t-e.indexStart;o>=e.backing.length&&this._grow(e,o+1),e.indexEnd=t}var i=t-e.indexBase;i<0&&(i+=e.backing.length),e.incrementBucket(i,n)}},r.prototype._grow=function(e,t){var n=e.backing.length,o=e.indexBase-e.indexStart,i=n-o,a=WA(t);a>this._maxSize&&(a=this._maxSize);var l=a-o;e.backing.growTo(a,i,l)},r.prototype._changeScale=function(e,t){for(var n=0;e-t>=this._maxSize;)e>>=1,t>>=1,n++;return n},r.prototype._downscale=function(e){if(e!==0){if(e<0)throw new Error("impossible change of scale: "+this.scale);var t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=sh(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Lu.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Lu.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(n.high,n.low),t-this._changeScale(o.high,o.low))},r.prototype._highLowAtScale=function(e,t,n){if(e.length===0)return new Lu(0,-1);var o=t-n;return new Lu(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++)this._incrementIndexBy(e,i+l>>a,n.at(l))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,l=0;l<n.length;l++){var c=i+l>>a,s=c-e.indexBase;s<0&&(s+=e.backing.length),e.decrementBucket(s,n.at(l))}e.trim()},r}();var ch=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=br.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new QA(e,this._maxSize,this._recordMinMax)},r.prototype.merge=function(e,t){var n=t.clone();return n.merge(e),n},r.prototype.diff=function(e,t){var n=t.clone();return n.diff(e),n},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=cB(i,2),l=a[0],c=a[1],s=c.toPointValue(),u=e.type===ge.GAUGE||e.type===ge.UP_DOWN_COUNTER||e.type===ge.OBSERVABLE_GAUGE||e.type===ge.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:l,startTime:c.startTime,endTime:o,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:u?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}},r}();Me();var pB=Tg("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function ZA(r){return r.setValue(pB,!0)}Me();function ew(){return function(r){H.error(mB(r))}}function mB(r){return typeof r=="string"?r:JSON.stringify(gB(r))}function gB(r){for(var e={},t=r;t!==null;)Object.getOwnPropertyNames(t).forEach(function(n){if(!e[n]){var o=t[n];o&&(e[n]=String(o))}}),t=Object.getPrototypeOf(t);return e}var hB=ew();function Nu(r){try{hB(r)}catch{}}var tw="1.30.1";var fB="process.runtime.name";var SB="service.name";var yB="telemetry.sdk.name",EB="telemetry.sdk.language",TB="telemetry.sdk.version";var rw=fB;var nw=SB;var qs=yB,Ks=EB,Ys=TB;var bB="nodejs";var ow=bB;var ya,ai=(ya={},ya[qs]="opentelemetry",ya[rw]="node",ya[Ks]=ow,ya[Ys]=tw,ya);function Xs(r){r.unref()}var _B=9,IB=6,PB=Math.pow(10,IB),hve=Math.pow(10,_B);function si(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*PB);return[t,n]}function Ea(r){return r[0]*1e6+r[1]/1e3}var Js;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(Js||(Js={}));Me();function iw(r,e){return new Promise(function(t){da.with(ZA(da.active()),function(){r.export(e,function(n){t(n)})})})}var aw={_export:iw};var MB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Du=function(){function r(e,t,n){t===void 0&&(t=0),n===void 0&&(n=[0,0]),this.startTime=e,this._current=t,this.sampleTime=n}return r.prototype.record=function(e){this._current=e,this.sampleTime=si(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var uh=function(){function r(){this.kind=br.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Du(e)},r.prototype.merge=function(e,t){var n=Ea(t.sampleTime)>=Ea(e.sampleTime)?t:e;return new Du(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Ea(t.sampleTime)>=Ea(e.sampleTime)?t:e;return new Du(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.GAUGE,dataPoints:n.map(function(i){var a=MB(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var OB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ta=function(){function r(e,t,n,o){n===void 0&&(n=0),o===void 0&&(o=!1),this.startTime=e,this.monotonic=t,this._current=n,this.reset=o}return r.prototype.record=function(e){this.monotonic&&e<0||(this._current+=e)},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var ku=function(){function r(e){this.monotonic=e,this.kind=br.SUM}return r.prototype.createAccumulation=function(e){return new Ta(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ta(t.startTime,this.monotonic,o,t.reset):new Ta(e.startTime,this.monotonic,n+o)},r.prototype.diff=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return this.monotonic&&n>o?new Ta(t.startTime,this.monotonic,o,!0):new Ta(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:sn.SUM,dataPoints:n.map(function(i){var a=OB(i,2),l=a[0],c=a[1];return{attributes:l,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var li=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),vr=function(){function r(){}return r.Drop=function(){return mw},r.Sum=function(){return gw},r.LastValue=function(){return hw},r.Histogram=function(){return fw},r.ExponentialHistogram=function(){return LB},r.Default=function(){return NB},r}();var sw=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new rh,e}(vr);var lw=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ge.COUNTER:case ge.OBSERVABLE_COUNTER:case ge.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ku(!0),e.NON_MONOTONIC_INSTANCE=new ku(!1),e}(vr);var cw=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new uh,e}(vr);var uw=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){return e.DEFAULT_INSTANCE},e.DEFAULT_INSTANCE=new _u([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(vr);var Fu=function(r){li(e,r);function e(t,n){n===void 0&&(n=!0);var o=r.call(this)||this;if(o._recordMinMax=n,t==null)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");t=t.concat(),t=t.sort(function(l,c){return l-c});var i=t.lastIndexOf(-1/0),a=t.indexOf(1/0);return a===-1&&(a=void 0),o._boundaries=t.slice(i+1,a),o}return e.prototype.createAggregator=function(t){return new _u(this._boundaries,this._recordMinMax)},e}(vr);var dw=function(r){li(e,r);function e(t,n){t===void 0&&(t=160),n===void 0&&(n=!0);var o=r.call(this)||this;return o._maxSize=t,o._recordMinMax=n,o}return e.prototype.createAggregator=function(t){return new ch(this._maxSize,this._recordMinMax)},e}(vr);var pw=function(r){li(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ge.COUNTER:case ge.UP_DOWN_COUNTER:case ge.OBSERVABLE_COUNTER:case ge.OBSERVABLE_UP_DOWN_COUNTER:return gw;case ge.GAUGE:case ge.OBSERVABLE_GAUGE:return hw;case ge.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Fu(t.advice.explicitBucketBoundaries):fw}return H.warn("Unable to recognize instrument type: "+t.type),mw},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(vr);var mw=new sw,gw=new lw,hw=new cw,fw=new uw,LB=new dw,NB=new pw;var Sw=function(r){return vr.Default()},yw=function(r){return Sa.CUMULATIVE};var dh=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},ph=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Ew=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},DB=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},Tw=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:Sw,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:yw,this._metricProducers=(o=e?.metricProducers)!==null&&o!==void 0?o:[],this._cardinalitySelector=e?.cardinalitySelector}return r.prototype.setMetricProducer=function(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()},r.prototype.selectAggregation=function(e){return this._aggregationSelector(e)},r.prototype.selectAggregationTemporality=function(e){return this._aggregationTemporalitySelector(e)},r.prototype.selectCardinalityLimit=function(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3},r.prototype.onInitialized=function(){},r.prototype.collect=function(e){return dh(this,void 0,void 0,function(){var t,n,o,i,a,l;return ph(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(DB([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],Ew(this._metricProducers.map(function(s){return s.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=Ew.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(th(o,function(s){return s.errors})),a=n.resourceMetrics.resource,l=n.resourceMetrics.scopeMetrics.concat(th(o,function(s){return s.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:l},errors:i}]}})})},r.prototype.shutdown=function(e){return dh(this,void 0,void 0,function(){return ph(this,function(t){switch(t.label){case 0:return this._shutdown?(H.error("Cannot call shutdown twice."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onShutdown()];case 1:return t.sent(),[3,4];case 2:return[4,ao(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return dh(this,void 0,void 0,function(){return ph(this,function(t){switch(t.label){case 0:return this._shutdown?(H.warn("Cannot forceFlush on already shutdown MetricReader."),[2]):e?.timeoutMillis!=null?[3,2]:[4,this.onForceFlush()];case 1:return t.sent(),[2];case 2:return[4,ao(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var kB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Uu=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Bu=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},FB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},UB=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},mh=function(r){kB(e,r);function e(t){var n,o,i,a,l=r.call(this,{aggregationSelector:(n=t.exporter.selectAggregation)===null||n===void 0?void 0:n.bind(t.exporter),aggregationTemporalitySelector:(o=t.exporter.selectAggregationTemporality)===null||o===void 0?void 0:o.bind(t.exporter),metricProducers:t.metricProducers})||this;if(t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(t.exportTimeoutMillis!==void 0&&t.exportIntervalMillis!==void 0&&t.exportIntervalMillis<t.exportTimeoutMillis)throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis");return l._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,l._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,l._exporter=t.exporter,l}return e.prototype._runOnce=function(){return Uu(this,void 0,void 0,function(){var t;return Bu(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,ao(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof eh?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(Nu(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return Uu(this,void 0,void 0,function(){var o,i,a,l,c,s;return Bu(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&&(s=H).error.apply(s,UB(["PeriodicExportingMetricReader: metrics collection errors"],FB(a),!1)),!i.resource.asyncAttributesPending)return[3,5];u.label=2;case 2:return u.trys.push([2,4,,5]),[4,(n=(t=i.resource).waitForAsyncAttributes)===null||n===void 0?void 0:n.call(t)];case 3:return u.sent(),[3,5];case 4:return l=u.sent(),H.debug("Error while resolving async portion of resource: ",l),Nu(l),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,aw._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==Js.SUCCESS)throw new Error("PeriodicExportingMetricReader: metrics export failed (error "+c.error+")");return[2]}})})},e.prototype.onInitialized=function(){var t=this;this._interval=setInterval(function(){t._runOnce()},this._exportInterval),Xs(this._interval)},e.prototype.onForceFlush=function(){return Uu(this,void 0,void 0,function(){return Bu(this,function(t){switch(t.label){case 0:return[4,this._runOnce()];case 1:return t.sent(),[4,this._exporter.forceFlush()];case 2:return t.sent(),[2]}})})},e.prototype.onShutdown=function(){return Uu(this,void 0,void 0,function(){return Bu(this,function(t){switch(t.label){case 0:return this._interval&&clearInterval(this._interval),[4,this.onForceFlush()];case 1:return t.sent(),[4,this._exporter.shutdown()];case 2:return t.sent(),[2]}})})},e}(Tw);Me();Me();function zu(){return"unknown_service:"+process.argv0}var lo=function(){return lo=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=e[o])}return r},lo.apply(this,arguments)},BB=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},zB=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},HB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Hu=function(){function r(e,t){var n=this,o;this._attributes=e,this.asyncAttributesPending=t!=null,this._syncAttributes=(o=this._attributes)!==null&&o!==void 0?o:{},this._asyncAttributesPromise=t?.then(function(i){return n._attributes=Object.assign({},n._attributes,i),n.asyncAttributesPending=!1,i},function(i){return H.debug("a resource's async attributes promise rejected: %s",i),n.asyncAttributesPending=!1,{}})}return r.empty=function(){return r.EMPTY},r.default=function(){var e;return new r((e={},e[nw]=zu(),e[Ks]=ai[Ks],e[qs]=ai[qs],e[Ys]=ai[Ys],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&H.error("Accessing resource attributes before async attributes settled"),(e=this._attributes)!==null&&e!==void 0?e:{}},enumerable:!1,configurable:!0}),r.prototype.waitForAsyncAttributes=function(){return BB(this,void 0,void 0,function(){return zB(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]}})})},r.prototype.merge=function(e){var t=this,n;if(!e)return this;var o=lo(lo({},this._syncAttributes),(n=e._syncAttributes)!==null&&n!==void 0?n:e.attributes);if(!this._asyncAttributesPromise&&!e._asyncAttributesPromise)return new r(o);var i=Promise.all([this._asyncAttributesPromise,e._asyncAttributesPromise]).then(function(a){var l,c=HB(a,2),s=c[0],u=c[1];return lo(lo(lo(lo({},t._syncAttributes),s),(l=e._syncAttributes)!==null&&l!==void 0?l:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var bw=function(){function r(){this._registeredViews=[]}return r.prototype.addView=function(e){this._registeredViews.push(e)},r.prototype.findViews=function(e,t){var n=this,o=this._registeredViews.filter(function(i){return n._matchInstrument(i.instrumentSelector,e)&&n._matchMeter(i.meterSelector,t)});return o},r.prototype._matchInstrument=function(e,t){return(e.getType()===void 0||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)},r.prototype._matchMeter=function(e,t){return e.getNameFilter().match(t.name)&&(t.version===void 0||e.getVersionFilter().match(t.version))&&(t.schemaUrl===void 0||e.getSchemaUrlFilter().match(t.schemaUrl))},r}();Me();var ci=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Gu=function(){function r(e,t){this._writableMetricStorage=e,this._descriptor=t}return r.prototype._record=function(e,t,n){if(t===void 0&&(t={}),n===void 0&&(n=da.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===tr.INT&&!Number.isInteger(e)&&(H.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,t,n,si(Date.now()))},r}();var vw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){this._record(t,n,o)},e}(Gu);var Rw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n,o){if(t<0){H.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Gu);var Aw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){this._record(t,n,o)},e}(Gu);var ww=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n,o){if(t<0){H.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(Gu);var Vu=function(){function r(e,t,n){this._observableRegistry=n,this._descriptor=e,this._metricStorages=t}return r.prototype.addCallback=function(e){this._observableRegistry.addCallback(e,this)},r.prototype.removeCallback=function(e){this._observableRegistry.removeCallback(e,this)},r}();var Cw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Vu);var xw=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Vu);var _w=function(r){ci(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Vu);function Qs(r){return r instanceof Vu}var Iw=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=ln(e,ge.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new Aw(o,n)},r.prototype.createHistogram=function(e,t){var n=ln(e,ge.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new ww(o,n)},r.prototype.createCounter=function(e,t){var n=ln(e,ge.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Rw(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=ln(e,ge.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new vw(o,n)},r.prototype.createObservableGauge=function(e,t){var n=ln(e,ge.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new xw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=ln(e,ge.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Cw(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=ln(e,ge.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new _w(n,o,this._meterSharedState.observableRegistry)},r.prototype.addBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)},r.prototype.removeBatchObservableCallback=function(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)},r}();var ju=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=ln(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var GB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Pw=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},VB=function(){function r(e){this._hash=e,this._valueMap=new Map,this._keyMap=new Map}return r.prototype.get=function(e,t){return t??(t=this._hash(e)),this._valueMap.get(t)},r.prototype.getOrDefault=function(e,t){var n=this._hash(e);if(this._valueMap.has(n))return this._valueMap.get(n);var o=t();return this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,o),o},r.prototype.set=function(e,t,n){n??(n=this._hash(e)),this._keyMap.has(n)||this._keyMap.set(n,e),this._valueMap.set(n,t)},r.prototype.has=function(e,t){return t??(t=this._hash(e)),this._valueMap.has(t)},r.prototype.keys=function(){var e,t;return Pw(this,function(n){switch(n.label){case 0:e=this._keyMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},r.prototype.entries=function(){var e,t;return Pw(this,function(n){switch(n.label){case 0:e=this._valueMap.entries(),t=e.next(),n.label=1;case 1:return t.done===!0?[3,3]:[4,[this._keyMap.get(t.value[0]),t.value[1],t.value[0]]];case 2:return n.sent(),t=e.next(),[3,1];case 3:return[2]}})},Object.defineProperty(r.prototype,"size",{get:function(){return this._valueMap.size},enumerable:!1,configurable:!0}),r}();var Dr=function(r){GB(e,r);function e(){return r.call(this,Cu)||this}return e}(VB);var jB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},$u=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Dr,this._cumulativeMemoStorage=new Dr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Cu(this._overflowAttributes)}return r.prototype.record=function(e,t,n,o){var i=this,a=this._activeCollectionStorage.get(t);if(!a){if(this._activeCollectionStorage.size>=this._cardinalityLimit){var l=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});l?.record(e);return}a=this._aggregator.createAccumulation(o),this._activeCollectionStorage.set(t,a)}a?.record(e)},r.prototype.batchCumulate=function(e,t){var n=this;Array.from(e.entries()).forEach(function(o){var i=jB(o,3),a=i[0],l=i[1],c=i[2],s=n._aggregator.createAccumulation(t);s?.record(l);var u=s;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,s)}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,s)}if(n._activeCollectionStorage.has(a,c)){var p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,u)}n._cumulativeMemoStorage.set(a,s,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Dr,e},r}();var gh=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Mw=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Wu=function(){function r(e,t){var n=this;this._aggregator=e,this._unreportedAccumulations=new Map,this._reportHistory=new Map,t.forEach(function(o){n._unreportedAccumulations.set(o,[])})}return r.prototype.buildMetrics=function(e,t,n,o){this._stashAccumulations(n);var i=this._getMergedUnreportedAccumulations(e),a=i,l;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),s=c.collectionTime;l=c.aggregationTemporality,l===Sa.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,s)}else l=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:l});var u=$B(a);if(u.length!==0)return this._aggregator.toMetricData(t,l,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=gh(o),a=i.next();!a.done;a=i.next()){var l=a.value,c=this._unreportedAccumulations.get(l);c===void 0&&(c=[],this._unreportedAccumulations.set(l,c)),c.push(e)}}catch(s){t={error:s}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}},r.prototype._getMergedUnreportedAccumulations=function(e){var t,n,o=new Dr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=gh(i),l=a.next();!l.done;l=a.next()){var c=l.value;o=r.merge(o,c,this._aggregator)}}catch(s){t={error:s}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return o},r.merge=function(e,t,n){for(var o=e,i=t.entries(),a=i.next();a.done!==!0;){var l=Mw(a.value,3),c=l[0],s=l[1],u=l[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,s);o.set(c,p,u)}else o.set(c,s,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=gh(e.keys()),l=a.next();!l.done;l=a.next()){var c=Mw(l.value,2),s=c[0],u=c[1],d=t.get(s,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{l&&!l.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function $B(r){return Array.from(r.entries())}var WB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),qB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ow=function(r){WB(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new $u(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Wu(n,i),l}return e.prototype.record=function(t,n){var o=this,i=new Dr;Array.from(t.entries()).forEach(function(a){var l=qB(a,2),c=l[0],s=l[1];i.set(o._attributesProcessor.process(c),s)}),this._deltaMetricStorage.batchCumulate(i,n)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(ju);Me();function hh(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
4015
4016
  `),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
4016
4017
  `),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
4017
4018
  `),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
4018
- `),t}function kB(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function FB(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function UB(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function BB(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
4019
+ `),t}function KB(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function YB(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function XB(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function JB(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
4019
4020
  - OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
4020
- - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function gh(r,e){return r.valueType!==e.valueType?kB(r,e):r.unit!==e.unit?FB(r,e):r.type!==e.type?UB(r,e):r.description!==e.description?BB(r,e):""}var hh=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},vw=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=hh(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=hh(u.values()),p=d.next();!p.done;p=d.next()){var s=p.value;a=a.concat(s)}}catch(m){o={error:m}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=hh(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();UA(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),G.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
4021
+ - OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function fh(r,e){return r.valueType!==e.valueType?KB(r,e):r.unit!==e.unit?YB(r,e):r.type!==e.type?XB(r,e):r.description!==e.description?JB(r,e):""}var Sh=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Lw=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var l=Sh(this._sharedRegistry.values()),c=l.next();!c.done;c=l.next()){var s=c.value;a=a.concat(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=Sh(u.values()),p=d.next();!p.done;p=d.next()){var s=p.value;a=a.concat(s)}}catch(m){o={error:m}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=Sh(t),l=a.next();!l.done;l=a.next()){var c=l.value,s=c.getInstrumentDescriptor();VA(s,e)?(s.description!==e.description&&(e.description.length>s.description.length&&c.updateDescription(e.description),H.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
4021
4022
  `,`Details:
4022
- `,mh(s,e),`The longer description will be used.
4023
- To resolve the conflict:`,gh(s,e))),i=c):G.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
4023
+ `,hh(s,e),`The longer description will be used.
4024
+ To resolve the conflict:`,fh(s,e))),i=c):H.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
4024
4025
  `,`Details:
4025
- `,mh(s,e),`To resolve the conflict:
4026
- `,gh(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var Rw=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();Pe();Pe();var Aw=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Dr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){G.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===tr.INT&&!Number.isInteger(e)&&(G.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(t,e)},r}();var ww=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ys(e)){var o=this._buffer.get(e);if(o==null&&(o=new Dr,this._buffer.set(e,o)),typeof t!="number"){G.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===tr.INT&&!Number.isInteger(t)&&(G.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var fh=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Sh=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Cw=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},xw=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},_w=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(Ys));if(n.size===0){G.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(Ys)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return fh(this,void 0,void 0,function(){var n,o,i,a;return Sh(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,OA(xw(xw([],Cw(n),!1),Cw(o),!1))];case 1:return i=l.sent(),a=i.filter(LA).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return fh(n,void 0,void 0,function(){var l,c;return Sh(this,function(s){switch(s.label){case 0:return l=new Aw(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=so(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return fh(n,void 0,void 0,function(){var l,c;return Sh(this,function(s){switch(s.label){case 0:return l=new ww,c=Promise.resolve(i(l)),t!=null&&(c=so(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&NA(n.instruments,t)})},r}();var zB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),Iw=function(r){zB(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new Gu(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Vu(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(Hu);var Pw=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ju=function(){function r(){}return r.Noop=function(){return GB},r}();var HB=function(r){Pw(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(ju);var jRe=function(r){Pw(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(ju);var GB=new HB;var VB=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},jB=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},$B=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Mw=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new vw,this.observableRegistry=new _w,this.meter=new yw(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,Iw);return t.length===1?t[0]:new Rw(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,bw);return t},r.prototype.collect=function(e,t,n){return VB(this,void 0,void 0,function(){var o,i,a;return jB(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(PA),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=FA(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,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),l=a.map(function(c){var s=$B(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,m,ju.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var WB=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Ow=function(){function r(e){this.resource=e,this.viewRegistry=new uw,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=MA(e),n=this.meterSharedStates.get(t);return n==null&&(n=new Mw(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=WB(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var $u=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Wu=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},qB=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},KB=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},Lw=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return $u(this,void 0,void 0,function(){var t,n,o,i,a=this;return Wu(this,function(l){switch(l.label){case 0:return t=si(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return $u(a,void 0,void 0,function(){var s;return Wu(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,KB([],qB(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return $u(this,void 0,void 0,function(){return Wu(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return $u(this,void 0,void 0,function(){return Wu(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var Nw=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Dw=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},kw=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function YB(r,e){var t=e??Uu.empty();return r?Uu.default().merge(t):t}var yh=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new Ow(YB((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=kw(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=kw(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 r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(G.warn("A shutdown MeterProvider cannot provide a Meter"),Rg()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new Lw(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return Nw(this,void 0,void 0,function(){return Dw(this,function(t){switch(t.label){case 0:return this._shutdown?(G.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 t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return Nw(this,void 0,void 0,function(){return Dw(this,function(t){switch(t.label){case 0:return this._shutdown?(G.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 t.sent(),[2]}})})},r}();var yAe=process.env.APP||"unknown";Pe();import{v4 as XB}from"uuid";function JB(){return new xA({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:ii.DELTA})}var qu=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;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 t=typeof process<"u"?"production":"unknown",n=new Hg({[pu]:e.serviceName,[RR]:t,[wR]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:XB()}),o=JB(),i=new dh({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new yh({resource:n,readers:[i]}),lu.setGlobalMeterProvider(this.provider),this.meter=lu.getMeter("momentic-serverless")}increment(e,t,n){try{let o=iu(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=iu(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var vr=new ou;function Fw(r){r.disabled||(vr=new qu(r))}import{CookieJar as fz}from"tough-cookie";async function uo(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}var ui=3.1783027;function QB(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function In(r){return Math.ceil(Eh(r)/ui)}function Eh(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
4027
- `,""),t=t.replaceAll(" ","");let n=QB(t);return t.length-n+ui*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Eh(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*ui:e+=85*ui:e+=Eh(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var Bw={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},zw={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},Uw=/<(\S+) id="(\d+)".*?>/g,ZB=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Hw=["h1","h2","section","footer","nav","aside","form","label","dialog"],ez=[...Hw,"span","div","h3"],tz=["table","select","form","ul","ol","menu","pre","code","dialog"],rz=["table","form","dialog","nav","section","ul","select"];function Ku(r){return nz(r)}function nz({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,l=[],c=r.split(`
4026
+ `,hh(s,e),`To resolve the conflict:
4027
+ `,fh(s,e))}}catch(u){n={error:u}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var Nw=function(){function r(e){this._backingStorages=e}return r.prototype.record=function(e,t,n,o){this._backingStorages.forEach(function(i){i.record(e,t,n,o)})},r}();Me();Me();var Dw=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Dr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){H.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===tr.INT&&!Number.isInteger(e)&&(H.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(t,e)},r}();var kw=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Qs(e)){var o=this._buffer.get(e);if(o==null&&(o=new Dr,this._buffer.set(e,o)),typeof t!="number"){H.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===tr.INT&&!Number.isInteger(t)&&(H.warn("INT value type cannot accept a floating-point value for "+e._descriptor.name+", ignoring the fractional digits."),t=Math.trunc(t),!Number.isInteger(t))||o.set(n,t)}},r}();var yh=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Eh=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Fw=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Uw=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},Bw=function(){function r(){this._callbacks=[],this._batchCallbacks=[]}return r.prototype.addCallback=function(e,t){var n=this._findCallback(e,t);n>=0||this._callbacks.push({callback:e,instrument:t})},r.prototype.removeCallback=function(e,t){var n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)},r.prototype.addBatchCallback=function(e,t){var n=new Set(t.filter(Qs));if(n.size===0){H.error("BatchObservableCallback is not associated with valid instruments",t);return}var o=this._findBatchCallback(e,n);o>=0||this._batchCallbacks.push({callback:e,instruments:n})},r.prototype.removeBatchCallback=function(e,t){var n=new Set(t.filter(Qs)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return yh(this,void 0,void 0,function(){var n,o,i,a;return Eh(this,function(l){switch(l.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,FA(Uw(Uw([],Fw(n),!1),Fw(o),!1))];case 1:return i=l.sent(),a=i.filter(UA).map(function(c){return c.reason}),[2,a]}})})},r.prototype._observeCallbacks=function(e,t){var n=this;return this._callbacks.map(function(o){var i=o.callback,a=o.instrument;return yh(n,void 0,void 0,function(){var l,c;return Eh(this,function(s){switch(s.label){case 0:return l=new Dw(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(l)),t!=null&&(c=ao(c,t)),[4,c];case 1:return s.sent(),a._metricStorages.forEach(function(u){u.record(l._buffer,e)}),[2]}})})})},r.prototype._observeBatchCallbacks=function(e,t){var n=this;return this._batchCallbacks.map(function(o){var i=o.callback,a=o.instruments;return yh(n,void 0,void 0,function(){var l,c;return Eh(this,function(s){switch(s.label){case 0:return l=new kw,c=Promise.resolve(i(l)),t!=null&&(c=ao(c,t)),[4,c];case 1:return s.sent(),a.forEach(function(u){var d=l._buffer.get(u);d!=null&&u._metricStorages.forEach(function(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&BA(n.instruments,t)})},r}();var QB=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),zw=function(r){QB(e,r);function e(t,n,o,i,a){var l=r.call(this,t)||this;return l._attributesProcessor=o,l._aggregationCardinalityLimit=a,l._deltaMetricStorage=new $u(n,l._aggregationCardinalityLimit),l._temporalMetricStorage=new Wu(n,i),l}return e.prototype.record=function(t,n,o,i){n=this._attributesProcessor.process(n,o),this._deltaMetricStorage.record(t,n,o,i)},e.prototype.collect=function(t,n){var o=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,o,n)},e}(ju);var Hw=function(){var r=function(e,t){return r=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])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),ba=function(){function r(){}return r.Noop=function(){return ez},r}();var ZB=function(r){Hw(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(ba);var Gw=function(r){Hw(e,r);function e(t){var n=r.call(this)||this;return n._allowedAttributeNames=t,n}return e.prototype.process=function(t,n){var o=this,i={};return Object.keys(t).filter(function(a){return o._allowedAttributeNames.includes(a)}).forEach(function(a){return i[a]=t[a]}),i},e}(ba);var ez=new ZB;var tz=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},rz=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},nz=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Vw=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new Lw,this.observableRegistry=new Bw,this.meter=new Iw(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,zw);return t.length===1?t[0]:new Nw(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,Ow);return t},r.prototype.collect=function(e,t,n){return tz(this,void 0,void 0,function(){var o,i,a;return rz(this,function(l){switch(l.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=l.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(DA),a.length===0?[2,{errors:o}]:[2,{scopeMetrics:{scope:this._instrumentationScope,metrics:a},errors:o}])}})})},r.prototype._registerMetricStorage=function(e,t){var n=this,o=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope),i=o.map(function(c){var s=GA(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(s);if(u!=null)return u;var d=c.aggregation.createAggregator(s),p=new t(s,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),l=a.map(function(c){var s=nz(c,2),u=s[0],d=s[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var m=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,m,ba.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(l)}return i},r}();var oz=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},jw=function(){function r(e){this.resource=e,this.viewRegistry=new bw,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=kA(e),n=this.meterSharedStates.get(t);return n==null&&(n=new Vw(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=oz(this.metricCollectors),a=i.next();!a.done;a=i.next()){var l=a.value;o.push([l,l.selectAggregation(e)])}}catch(c){t={error:c}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return o},r}();var qu=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},Ku=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},iz=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),o,i=[],a;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(l){a={error:l}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},az=function(r,e,t){if(t||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 r.concat(i||Array.prototype.slice.call(e))},$w=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return qu(this,void 0,void 0,function(){var t,n,o,i,a=this;return Ku(this,function(l){switch(l.label){case 0:return t=si(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return qu(a,void 0,void 0,function(){var s;return Ku(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return s=u.sent(),s?.scopeMetrics!=null&&n.push(s.scopeMetrics),s?.errors!=null&&o.push.apply(o,az([],iz(s.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return l.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return qu(this,void 0,void 0,function(){return Ku(this,function(t){switch(t.label){case 0:return[4,this._metricReader.forceFlush(e)];case 1:return t.sent(),[2]}})})},r.prototype.shutdown=function(e){return qu(this,void 0,void 0,function(){return Ku(this,function(t){switch(t.label){case 0:return[4,this._metricReader.shutdown(e)];case 1:return t.sent(),[2]}})})},r.prototype.selectAggregationTemporality=function(e){return this._metricReader.selectAggregationTemporality(e)},r.prototype.selectAggregation=function(e){return this._metricReader.selectAggregation(e)},r.prototype.selectCardinalityLimit=function(e){var t,n,o;return(o=(n=(t=this._metricReader).selectCardinalityLimit)===null||n===void 0?void 0:n.call(t,e))!==null&&o!==void 0?o:2e3},r}();var Ww=function(r,e,t,n){function o(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function l(u){try{s(n.next(u))}catch(d){a(d)}}function c(u){try{s(n.throw(u))}catch(d){a(d)}}function s(u){u.done?i(u.value):o(u.value).then(l,c)}s((n=n.apply(r,e||[])).next())})},qw=function(r,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,o,i,a;return a={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function l(s){return function(u){return c([s,u])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=s[0]&2?o.return:s[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,s[1])).done)return i;switch(o=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,o=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=e.call(r,t)}catch(u){s=[6,u],o=0}finally{n=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},Kw=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")};function sz(r,e){var t=e??Hu.empty();return r?Hu.default().merge(t):t}var Th=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new jw(sz((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var l=Kw(e.views),c=l.next();!c.done;c=l.next()){var s=c.value;this._sharedState.viewRegistry.addView(s)}}catch(m){t={error:m}}finally{try{c&&!c.done&&(n=l.return)&&n.call(l)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=Kw(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 r.prototype.getMeter=function(e,t,n){return t===void 0&&(t=""),n===void 0&&(n={}),this._shutdown?(H.warn("A shutdown MeterProvider cannot provide a Meter"),wg()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new $w(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return Ww(this,void 0,void 0,function(){return qw(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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 t.sent(),[2]}})})},r.prototype.forceFlush=function(e){return Ww(this,void 0,void 0,function(){return qw(this,function(t){switch(t.label){case 0:return this._shutdown?(H.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 t.sent(),[2]}})})},r}();var lz=/[\^$\\.+?()[\]{}|]/g,Yu=function(){function r(e){e==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(e)))}return r.prototype.match=function(e){return this._matchAll?!0:this._regexp.test(e)},r.escapePattern=function(e){return"^"+e.replace(lz,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var va=function(){function r(e){this._matchAll=e===void 0,this._pattern=e}return r.prototype.match=function(e){return!!(this._matchAll||e===this._pattern)},r}();var Yw=function(){function r(e){var t;this._nameFilter=new Yu((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new va(e?.unit)}return r.prototype.getType=function(){return this._type},r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getUnitFilter=function(){return this._unitFilter},r}();var Xw=function(){function r(e){this._nameFilter=new va(e?.name),this._versionFilter=new va(e?.version),this._schemaUrlFilter=new va(e?.schemaUrl)}return r.prototype.getNameFilter=function(){return this._nameFilter},r.prototype.getVersionFilter=function(){return this._versionFilter},r.prototype.getSchemaUrlFilter=function(){return this._schemaUrlFilter},r}();function cz(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var bh=function(){function r(e){var t;if(cz(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Yu.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 Gw(e.attributeKeys):this.attributesProcessor=ba.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:vr.Default(),this.instrumentSelector=new Yw({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Xw({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var YAe=process.env.APP||"unknown";Me();import{v4 as uz}from"uuid";function dz(){return new OA({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:ii.DELTA})}var pz=[new bh({instrumentName:"test_operation_duration_ms",instrumentType:ge.HISTOGRAM,aggregation:new Fu([100,500,1e3,5e3,1e4,2e4])})],Xu=class{globalAttributes;provider;meter;counterCache=new Map;histogramCache=new Map;observableGaugeCache=new Map;gaugeValues=new Map;getCounter(e){let t=this.counterCache.get(e);if(t)return t;let n=this.meter.createCounter(e);return this.counterCache.set(e,n),n}getHistogram(e){let t=this.histogramCache.get(e);if(t)return t;let n=this.meter.createHistogram(e);return this.histogramCache.set(e,n),n}ensureObservableGauge(e){let t=this.observableGaugeCache.get(e);if(t)return t;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 t=typeof process<"u"?"production":"unknown",n=new Vg({[gu]:e.serviceName,[_R]:t,[PR]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:uz()}),o=dz(),i=new mh({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Th({resource:n,readers:[i],views:pz}),uu.setGlobalMeterProvider(this.provider),this.meter=uu.getMeter("momentic-serverless")}increment(e,t,n){try{let o=su(n,this.globalAttributes);this.getCounter(e).add(typeof t=="number"?t:1,o)}catch{}}gauge(e,t){try{this.ensureObservableGauge(e),this.gaugeValues.set(e,t)}catch{}}distribution(e,t,n){try{let o=su(n,this.globalAttributes);this.getHistogram(e).record(t,o)}catch{}}async flush(){try{await this.provider.forceFlush()}catch{}}async recordDuration({fn:e,name:t,tags:n}){let o=Date.now();try{return await Promise.resolve(e())}finally{this.distribution(t,Date.now()-o,n)}}};var Rr=new au;function Jw(r){r.disabled||(Rr=new Xu(r))}import{CookieJar as Mz}from"tough-cookie";async function co(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(),tree:t}}var ui=3.1783027;function mz(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function xn(r){return Math.ceil(vh(r)/ui)}function vh(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
4028
+ `,""),t=t.replaceAll(" ","");let n=mz(t);return t.length-n+ui*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=vh(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*ui:e+=85*ui:e+=vh(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var Zw={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},eC={minChunkTokenCount:5e3,acceptableChunkTokenCount:15e3,maxChunkTokenCount:5e4,maxLineLength:500},Qw=/<(\S+) id="(\d+)".*?>/g,gz=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,tC=["h1","h2","section","footer","nav","aside","form","label","dialog"],hz=[...tC,"span","div","h3"],fz=["table","select","form","ul","ol","menu","pre","code","dialog"],Sz=["table","form","dialog","nav","section","ul","select"];function Ju(r){return yz(r)}function yz({serializedTree:r,options:e,logger:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,l=[],c=r.split(`
4028
4029
  `),s=0,u=[],d=0,p=[],m=[],g=!1;for(;s<c.length;){g&&(l.push({ids:p,content:u.join(`
4029
- `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=In(h);d+=f,h.length>a&&(h=h.slice(0,a));let T=Array.from(h.matchAll(Uw)).map(M=>M&&M.length>=3?{tagName:M[1],id:M[2]}:void 0).filter(M=>!!M),R=Array.from(h.matchAll(ZB)).map(M=>M&&(M[2]||M[4])).filter(M=>!!M);R.reverse();let w=h.replace(/ id="[0-9]+"/g,"");u.push(w);for(let M of T)p.push(M.id),m.push(M);for(let M of R){let q=m[m.length-1];q&&q.tagName===M&&m.pop()}let x=m.some(M=>tz.includes(M.tagName)),_=c[s+1]??"",P=In(_),$=Array.from(_.matchAll(Uw)).map(M=>M&&M.length>2?M[1]:void 0).filter(M=>!!M),U=$.some(M=>Hw.includes(M)),L=$.some(M=>ez.includes(M));d+P>=i&&(g=!0),d>=n&&(U&&!x||R.some(M=>rz.includes(M)))&&(g=!0),d>=o&&L&&!x&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
4030
- `),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var oz=9e5,Yu=3e5,iz=5e3;async function di(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,flagStore:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=In(u);if(d>oz)try{let p=Ku({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await sz({...r,tokenLimit:Yu-1e4,chunks:p.chunks}),u=s.serialize();let m=In(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"),s=s.pruneToSerializedCharLimit(Yu*ui),u=s.serialize(),i.info("Filtered page using naive truncation")}if(d>Yu)try{if(o){let p=Ku({serializedTree:u,options:zw,logger:i});s=await H(az({...r,chunks:p.chunks}),{milliseconds:12e3}),u=s.serialize();let m=In(u);i.info({oldTokens:d,newTokens:m},"Filtered page using AI chunk ranking"),d=m}else{let p=Ku({serializedTree:u,options:Bw,logger:i});s=await H(lz({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=In(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"),s=s.pruneToSerializedCharLimit(Yu*ui),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>iz&&r.type==="locator"&&l.isBooleanFlagEnabled("ai_page_summary"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:Ie(i),abortSignal:c});i.info(p,"Got AI summaries"),s=s.pruneUsingRelevantIds(new Set(p.relevantIds.map(g=>g.toString()))),u=s.serialize();let m=In(u);i.info({newTokens:m,oldTokens:d},"Filtered page using AI summary"),d=m}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function az({type:r,chunks:e,description:t,fixtures:n,tree:o}){let{generator:i,signal:a,logger:l}=n,c=await i.rankChunksWithAi({chunks:e,description:t,type:r,softTokenLimit:4e4,hardTokenLimit:8e4},{abortSignal:a,logger:l,loggerTags:Ie(l)}),s=[];return e.forEach((d,p)=>{c.indices.includes(p)&&(s=s.concat(d.ids))}),o.pruneUsingRelevantIds(new Set(s))}async function sz(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:Ie(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((m,g)=>m+g.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function lz(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:Ie(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function bh(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return en({action:async()=>cz(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function cz(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowZeroOpacityOverride:u}=r,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,y=r.description,S=r.useMemory&&!t;n&&(y=await er({orgId:p,s:y,context:n,localTools:g,signal:f,logger:s})),a&&(y=dz(y,a));let{serializedTree:T,tree:A}=await uo(m,{allowZeroOpacityOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),R,w=Date.now(),x;for(;!R&&Date.now()-w<3e3;){f.throwIfAborted();try{R=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(se){x=se}}if(!R)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${x?.message}`);let _=T,P=!1,$=`data:image/jpeg;base64,${R.toString("base64")}`;_=await di({type:"locator",description:y,screenshot:$,serializedTree:T,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:s,flagStore:e.flagStore}}),_!==T&&(P=!0);let U=await h.getElementLocation({browserState:_,goal:y,screenshot:$,source:a,memory:S?l:void 0},{disableCache:t,abortSignal:f,loggerTags:Ie(s),useMemory:S});s.debug({usedRag:P,result:U},"Got locator result");let L=U.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:L,pageState:_,ragUsed:P,thoughts:U.thoughts}),!L)throw new zi(`Could not find any relevant element: ${U.thoughts}`,U.updatedMemory?{type:"GCS_TRACES",traces:U.updatedMemory}:void 0);let{resolution:M,target:q,frameConfig:we}=await m.createTargetFromA11yId({id:U.id,requirements:U.requirements,additionalElements:U.additionalElements,description:y,targetSource:"AI",logger:s});if(M.a11yNode?.properties?.hidden&&M.a11yNode?.properties?.hidden!=="false")throw new C("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: ${M.displayString}`);return S&&(U.updatedMemory?q.memory={type:"GCS_TRACES",traces:U.updatedMemory}:l&&(q.memory=l)),{thoughts:U.thoughts,target:q,resolution:M,frameConfig:we,screenshot:$}}var uz=["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:"],Gw="<select> element:",Vw="text input or contenteditable element:",jw="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:",$w="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:",Th=[Gw,Vw,jw,$w,...uz];function Ww(r,e){if(r===e)return!0;for(let t of Th){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Th.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Th.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function dz(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${Gw} ${r}`;case"TYPE":return`${Vw} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${jw}
4031
- ${r}`;case"ELEMENT_CHECK":return`${$w}
4032
- ${r}`;default:return r}}var pz=15;async function Xu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=pz}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=bT(c),u=0,d=Date.now(),p,m,g;try{await en({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,logger:t})}catch(f){t.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 Z(s,n.abortSignal),h=Date.now();try{if(p=await en({action:async()=>{let y=await qw(l,t,n.abortSignal);return m&&m.serializedTree===y.serializedTree&&m.screenshotBuff.equals(y.screenshotBuff)?p:(m=y,Kw({command:r,state:y,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),p?.updatedMemory&&(pc(r,p.updatedMemory),t.info({updatedMemory:p.updatedMemory,command:r},"Wrote new memory to assertion command")),p?.success)break;throw p?.thoughts?new C("AssertionFailureError",p.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await en({action:async()=>Kw({command:r,state:await qw(l,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function qw(r,e,t){let[n,o]=await Promise.all([uo(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function Kw({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,y=f.toString("base64"),S=u.url(),T=r.contextChoice??"MULTIMODAL",A=g;T!=="VISION_ONLY"&&(A=await di({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:y,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,flagStore:t.flagStore}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let R={goal:r.assertion,url:S,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:y,contextChoice:T,source:c},x=await(T==="VISION_ONLY"?(_,P)=>d.getVisualAssertionResult(_,P):(_,P)=>d.getAssertionResult(_,P))(R,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:Ie(s)});return(x.result||i)&&x.relevantElements&&(m.relevantElementsSerialized=x.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await mz(x.relevantElements,u,s)),{success:x.result,thoughts:x.thoughts,afterScreenshotOverride:f,updatedMemory:o?x.updatedMemory:void 0}}async function mz(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await H(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var gz=3e4;async function Yw({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??gz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(qi(r.url)&&(l=r.url),t&&Ki(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let s=await H((async()=>{try{return await n(l,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!s)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var po=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,flagStore:o,storage:i,orgId:a,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:s,options:u}){this.orgId=a,this.options=u,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=i,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=s,this.localCodeEvalTools=l,this.generator=t,this.logger=n,this.flagStore=o}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:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:l=this.logger}){let[c,s]=await Promise.all([uo(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await di({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:l,flagStore:this.flagStore}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Ie(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([uo(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 di({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,flagStore:this.flagStore}}),m={url:c,browserState:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Ie(a)},langfuseSessionId:l})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return uo(this.browser,e)}async locateElement(e){return await bh({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return en({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:t?{type:"url",url:t}: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,flagStore:this.flagStore,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:t,command:n,targetNames:o,descriptions:i,caches:a,action:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...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(),s>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:l,options:c,retriesWithAI:s-1});throw new C("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await en({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:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Np(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&Za(i)){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Dp(i)&&t.warn({err:i},"Invalid backend node id error, retrying element targeting command"),i instanceof $r&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:l}=o;if(t.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,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()-s<500&&await Z(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,y=!1,S=Xw(e.cache);if((!S||s)&&!kd(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),y=!0,S=void 0),S&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&S.targetSource==="HEURISTIC_HEALED"&&(y=!0,S=void 0),S?.inputDescription&&!Ww(o.elementDescriptor,S.inputDescription)&&(g.warn({old:S.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),y=!0,S=void 0);let T=R=>!!R&&df(R),A=!0;if(!T(S)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:y,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),y&&await Z(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let R;try{R=await bh({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowZeroOpacityOverride:l.allowZeroOpacityOverride,logger:g},this.getControllerFixtures(t))}catch(_){if(_ instanceof zi&&_.updatedLocatorMemory){let P={id:-1,...i,memory:_.updatedLocatorMemory};dc({cmd:c,key:d,newTarget:P,logger:g})}throw new C("ActionFailureError",_.message)}R.frameConfig&&this.browser.setActiveFrameConfig(R.frameConfig);let w=l.disableGlobalLocatorRedirect?{locator:R.resolution.locator}:await this.attemptLocatorRedirect(R.resolution.locator,g),x=await a(w);return dc({cmd:c,key:d,newTarget:R.target,logger:g}),p&&(n.heal({healType:"AI"}),R.target.targetSource="AI_HEALED",R.target.targetUpdateTime=new Date().toUTCString(),R.target.targetUpdateLoggerTags=Ie(g)),{result:x,elementInteractedDisplayString:R.resolution.displayString,thoughts:R.thoughts}}try{let R=await this.browser.resolveTarget(t,S,{allowZeroOpacityOverride:l.allowZeroOpacityOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(R.locator);let w=l.disableGlobalLocatorRedirect?{locator:R.locator}:await this.attemptLocatorRedirect(R.locator,g),x=await a(w);if(vr.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`]),dc({cmd:c,key:d,newTarget:S,logger:g}),A){let _=R.decisions.filter(P=>P.matched);if(_.length!==1)g.warn({decisions:R.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let P=_[0].type;n.heal({healType:P})}}return{result:x,elementInteractedDisplayString:R.displayString}}catch(R){this.throwIfClosed(),vr.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`]);let w=!1;if((R instanceof $r||Np(R)||Za(R)||Dp(R)||qS(R)||KS(R))&&(w=!0),R instanceof C&&!w)throw g.error({err:R},"Failed to execute action with cached target (fatal)"),R;if(f>0&&o){g.info({err:R},"Failed to execute action with cached target, retrying with AI");let x;return S.memory&&cl(S.memory)&&(x=S.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",R.message,{errOptions:{cause:R}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return As(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await Z(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&Ef(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await yb({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{sb(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>qm(e)}}async resolveCommandTemplateStrings(e,t){return Fc({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let l=n.condition;return l?.assertion.trim()?Xu({command:l,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 C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Xu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=aE(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:Ie(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let y=f.message;throw y.includes("MaxGenerationLengthExceededError")?new C("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."):y.includes("AIProviderError")&&y.includes("time")?new C("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:f}}):f}}case"NAVIGATE":if(!qi(n.url)&&!Ki(n.url,this.browser.baseUrl))throw new C("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":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;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 g,h;if(n.target&&Hr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:S,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=S,h=T}let f=this.browser.getViewport()?.height??Mt.height,y=this.browser.getViewport()?.width??Mt.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??y));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??y);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await Z(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Hr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:T=>this.browser.click(T,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:y,data:f};return Cc(g,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(Hr(n.fromTarget)&&Hr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Hr(n.fromTarget)||Hr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,y)=>this.browser.dragAndDrop(f.locator,y.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Hr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let y,S,T;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:R,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async x=>x.locator,options:{disableCache:i,targetName:"target",...n}});y=R,S=A,T=w}return await this.browser.mouseDrag(g,h,f,y,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:T}}case"SELECT_OPTION":{if(!Dn(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:S=>this.browser.selectOption(S,h,n.force),options:{...n,targetName:"target",disableCache:i,source:Lo(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:y}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);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 u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=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:g},"Executed JavaScript in browser")):g=await eo({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 h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Hr(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 g=this.browser.url(),h,f,y=Xw(n.target);if(y){let{elementInteractedDisplayString:T,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:y,cache:n.cache?.target,action:R=>this.browser.typeIntoTarget(n.value,R,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:Lo(n)}});h=T,f=A}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Cc(g,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"HOVER":{if(Hr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Dn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Dn(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:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Cc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;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 g=new fz,h=hz(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await pb({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:RS(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Yw({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return db({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await Bb({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await eo({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=Bl.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??Gr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(cb(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let y={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 Xu({command:y,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{y.cache?.memory&&pc(n,y.cache?.memory.traces)}}let f=await lb({command:n,tracer:t,timeoutMs:g,targetingWrapper:y=>this.wrapElementTargetingCommand(y),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await en({action:async()=>Bc({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:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new no(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await cg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await H(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new no(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Jc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Jc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new no(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new no(n.requestMatcher),async(h,f)=>{let y=await eo({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),S=kS.parse(y);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(g=>{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:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:Ie(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new Zc({signal:t.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:Ie(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Ie(this.logger)})}};import{z as Rr}from"zod";var pxe=Rr.object({useSelector:Rr.boolean().optional(),disableCache:Rr.boolean().optional(),iframeUrl:Rr.string().optional(),retriesWithAI:Rr.number().optional(),targetName:Rr.union([Rr.literal("target"),Rr.literal("fromTarget"),Rr.literal("toTarget")]),source:Tl.optional(),disableGlobalLocatorRedirect:Rr.boolean().optional(),allowZeroOpacityOverride:Rr.boolean().optional(),targetHealingInProgress:Rr.boolean().optional(),memory:Ei.optional()});import{cloneDeep as Sz}from"lodash-es";var yz={showOverlay:!1},Ju=class{sessions=new Map;sessionCountByIp=new Map;latestSessionId;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:t,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:t,cleanup:n,clientIp:o,browserBehavior:Sz(yz),socket:a}),this.latestSessionId=i,i}removeSession(e,t){(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){t.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){t.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}getLatestSession(){if(this.latestSessionId)return this.getSession(this.latestSessionId)}};function Jw(r,e,t,n){let o=Date.now(),i=Date.now(),a,l,c,s,u=!1,d=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let y=c;c=void 0;let S=h.url(),T=f.toEditorDisplayCopy();JSON.stringify(T)===JSON.stringify(a)&&S===s&&o>i||(r.emit("browserState",{logsPerPage:y?.logsPerPage,harPages:y?.harPages,harEntries:y?.harEntries,viewport:h.getViewport(),url:S,iframeSrcUrls:l??[],context:T,isInPageLoad:h.isInPageLoad}),o=Date.now()),s=S,a=T}catch(y){if(!r.connected)return;let S=y instanceof Error?y.message:`${y}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:y,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let h=n.getSession(e),f=h?.controller?.browser;if(!f||f.closed){t.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(l)||f.logsPerPage.some(y=>y.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).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 y=await f.getAllFrameUrls(),S=f.retrieveAndClearDebugData();m(y,S)&&(l=y,c=S,i=Date.now())}catch(y){t.warn({err:y},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,g]}}var Ez=4;async function Qw({socket:r,logger:e,storageFactory:t,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:l,authorization:c,flagStoreFactory:s,settingsFactory:u,getOrgId:d,branchGetter:p,globalE2eStateManager:m}){let g=r.id,h=r.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let f=await d({type:"e2e",testId:h}),y=await p?.();e=e.child({testId:h,orgId:f,sessionId:g,branch:y});let S=await a(f,e),T=await l(f,e),A=await s(f),R=await u(f,e),w=await t(f),{testMetadata:x,baseUrl:_,envName:P,browserConfig:Y,aiSettings:$,environmentVariables:U,localCodeEvalTools:L}=await pi({testId:h,orgId:f,logger:e,storage:w,authorization:c,flagStore:A,settings:R}),M=m.getSession(g);if(M)return e.info("Associating connection with existing session (likely reconnect)"),await M.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:g,orgId:f,testId:h};let q=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:q,event:"connect",args:r.handshake.query},"Websocket event (connect)"),q&&m.getCurrentConnectionsByIp(q)>=Ez)throw e.error({clientIp:q,sessions:m.getCurrentSessionsByIp(),...r.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.");m.reserveCapacityByIp(q);try{await Tz({socket:r,baseUrl:_,envName:P,testMetadata:x,orgId:f,sessionId:g,logger:e,environmentVariables:U,clientIp:q,devicePixelRatio:i,storage:w,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:L,generator:S,enricher:T,browserConfig:Y,aiSettings:$,flagStore:A,globalE2eStateManager:m})}catch(we){throw e.warn({err:we},"Error setting up socket session, possibly due to client closing the connection"),m.releaseCapacityByIp(q),we}return{type:"e2e",sessionId:g,testId:h,orgId:f}}async function Tz({socket:r,baseUrl:e,envName:t,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:l,storage:c,uploadedFileStorage:s,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:g,aiSettings:h,clientIp:f,enricher:y,flagStore:S,globalE2eStateManager:T}){let A={viewport:o.advanced?.viewport??Mt,locale:o.advanced?.locale??zn,timezoneId:o.advanced?.timezone??Hn,geolocation:o.advanced?.geolocation??Gn,colorScheme:o.advanced?.colorScheme};n&&(A.deviceScaleFactor=n);let R=o.id,w=await jc({settings:g,orgId:i,baseUrl:e,envName:t,testName:o.name,localTools:d,envVariables:m,logger:l,customHeaders:void 0});l=l.child({orgId:i,sessionId:a,testId:R});let x=S.isBooleanFlagEnabled("icon_knowledge_base")?await c.fetchIconKnowledgeBase(l):null,_=await yr.init({baseUrl:e,userBrowserSettings:w,enricher:y,storage:c,flagStore:S,logger:l,contextArgs:A,iconKnowledgeBase:x,callbacks:{onTabsChange:(L,M)=>{r.emit("tabs",{tabs:L,activeTab:M})},onScreencastFrame:(L,M)=>{let q=r;yn&&(q=r.compress(!0)),q.emit("screenshot",{buffer:L},()=>{M()})},onSvgsCollected:L=>{r.emit("newIconDetected",{numIcons:L.newSvgs.length}),c.saveNewIcons(L,l)}}});await _.navigate({url:e,initialNavigation:!0});let P=new po({browser:_,generator:p,logger:l,flagStore:S,orgId:i,options:{scratchPadId:void 0,slowMoMs:w.slowMoMs,autoFollowNewTabs:w.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??S.isBooleanFlagEnabled("rag_v2")},storage:c,localCodeEvalTools:d,uploadedFileStorage:s,visualDiffScreenshotStorage:u}),Y=Jw(r,a,l,T),$=async()=>{Y.timers.forEach(L=>clearInterval(L))},U=new qt({baseUrl:e,testName:o.name,currentUrl:P.browser.url(),variablesFromEnvironment:m,envName:t});if(!r.connected)throw await _.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:yr.USER_AGENT,viewport:P.browser.getViewport(),sessionId:a}),T.registerSession({controller:P,context:U,sessionId:a,cleanup:$,clientIp:f,socket:r})}async function pi({testId:r,orgId:e,logger:t,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(r,t);if(!a)throw new Error(`Test metadata could not found for test ${r}`);let l;o?.type==="API_KEY"&&(l=new Yr({httpClient:new Rt({...o,logger:t}),fakerSeed:void 0}));let c=a.envs?.find(h=>h.default),s;c&&(s=await n.fetchEnvironment(c.name,t));let u=s&&"browser"in s?s.browser:void 0,d={...i.browser,...u,...a.advanced},p=a.baseUrl||s?.variables?.[ft];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...s?.variables};await Promise.all((a.parameters??[]).map(async h=>{let f=await er({orgId:e,s:h.defaultValue,context:qt.dummyContext(a.name,s?.name,m),logger:t,localTools:l});m[h.name]=f}));let g={...i.ai,...a.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:s?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:g}}var vh=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}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 mo({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},mo=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,t]of Object.entries(this.stepFrequenciesByType))vr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,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 vh({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},Qu=class{constructor(e,t,n,o,i){this.socket=e;this.storage=t;this.orgId=n;this.testId=o;this.stepsBeforeRun=i}children=[];async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new mo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new mo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new mo({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var Rh={currentlyExecutingRequests:{}},vz=r=>async(e,t)=>{let{testId:n,orgId:o}=r.metadata,i=await r.flagStoreFactory(o),a=await r.settingsFactory(o,r.logger),l=await r.storageFactory(o),c,s=await pi({testId:n,orgId:o,logger:r.logger,storage:l,authorization:r.authorization,flagStore:i,settings:a}),u=`${n}|${s.baseUrl}`;try{let d=Rh.currentlyExecutingRequests[u]??0;Rh.currentlyExecutingRequests[u]=d+1,c=await Rz({...r,...e,...s,done:t})}finally{r.logger.info({result:c,sessionId:r.metadata.sessionId},"Test execution complete"),Rh.currentlyExecutingRequests[u]--}},Rz=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:l,aiSettings:c,browserConfig:s,metadata:u,logger:d,envName:p,testName:m,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:y,globalE2eStateManager:S})=>{let{testId:T,sessionId:A,orgId:R}=u,w=A,x=S.getSession(A);if(!x)throw new Error("No active session found");let{controller:_,context:P}=x;_.setOpen(),d=d.child({testId:T,orgId:R,sessionId:A,runId:w}),d.info({steps:e.map(re=>`${re.type}${"command"in re?` - ${re.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:t,context:P,flags:_.flagStore.getAllFlags()},"Socket execution parameters");let Y=g??{},$=async()=>{o&&(await _.browser.reset({newUrl:t}),P.reset({baseUrl:t,currentUrl:_.browser.url(),variablesFromEnvironment:Y,envName:p,testName:m}))},U=await l(R),L=await y(R),M=async()=>{try{await L.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:T,stepLists:{steps:e},logger:d})}catch(re){d.error({err:re},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await hs({promiseGenerator:async()=>Promise.all([$(),M()]),signal:_.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),_.setOpen()}catch(re){if(r.emit("finished"),re.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${re}`)}let q=bz(e),we={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},se={orgId:R,runId:w,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:s}},ze={controller:_,context:P,storage:U,codeEvalTools:h,usageTracker:new Di,logger:d},Qe={test:{},step:{onDynamicAIActionStatusUpdateEvent:re=>{r.emit("dynamicCommandStatusUpdate",re)},onDynamicAIActionEvaluatingEvent:re=>{r.emit("dynamicCommandEvaluating",re)},onDynamicCommandGenerated:re=>{r.emit("dynamicCommandGenerated",re)},onDynamicCommandExecuted:re=>{r.emit("dynamicCommandExecuted",re)}}},ir=new Qu(r,U,R,T,q),dt=await Vc({fixtures:ze,options:we,callbacks:Qe,inputs:se,testParams:{tracer:ir}});return dt?.status==="PASSED"?await mc({logger:d,cacheStorage:L,orgId:R,testId:T,originalSteps:{steps:q},updatedSteps:{steps:e}}):dt?.status==="FAILED"&&await gc({logger:d,cacheStorage:L,orgId:R,testId:T,originalSteps:{steps:q},updatedSteps:{steps:e}}),await ir.finish(),f?.(dt),dt.status};var Zw={event:"execute",createHandler:vz};import{cloneDeep as Az}from"lodash-es";var wz=r=>async({command:e},t)=>{let{logger:n,generatorFactory:o,metadata:i}=r,a=Az(e),l=VE(a);if(l.category!=="NO_DESCRIPTION_PROVIDED"){if(l.category!=="NONE"){t?.({result:l});return}"cache"in a&&(a.cache=void 0);try{let s=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});t?.({result:s})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),t?.({result:void 0})}}},eC={event:"lintStep",createHandler:wz};var Cz=({metadata:r,logger:e,storageFactory:t,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=r;return async(a,l)=>{let{description:c,command:s,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 t(i),f=Uo.parse(u.advanced??{}),y={},S;if(c){if("useSelector"in s&&s.useSelector)try{let T=await m.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);S=T.resolution.locator,y={target:T.target,thoughts:T.thoughts}}catch(T){e.warn({err:T},"Failed resolving target with selector"),l({err:`Failed locating element: ${T.message}`,decisions:T instanceof jr?T.decisions:void 0});return}else try{let T=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Lo(s),iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,memory:"cache"in s&&s.cache&&"target"in s.cache&&cl(s.cache.target.memory)?s.cache.target.memory:void 0,logger:e});y={target:T.target,thoughts:T.thoughts},S=T.resolution.locator}catch(T){(async()=>{try{let A=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:T,html:A.slice(0,1e5)},"Failed locating element with AI")}catch(A){e.warn({err:A},"Failed grabbing HTML after trying to locate element with AI")}})(),l({err:`${T.message}`});return}if(s.type==="SELECT_OPTION"&&S)try{y.options=await m.browser.getSelectOptions(S)}catch(T){e.warn({err:T},"Failed getting select options"),l({err:`Failed getting select options: ${T.message}`});return}e.info({result:y},"Locate handler result")}if(d)try{let{buffer:T,width:A,height:R}=await m.screenshotWithDimensions({clearHighlights:!0,locator:S}),w=await h.uploadScreenshot(T);y.screenshot={data:w,width:A,height:R},e.info({width:A,height:R},"Captured screenshot during locate")}catch(T){e.error({err:T},"Error capturing screenshot during locate"),l({err:`Error taking screenshot: ${T.message}`});return}if(l({result:y}),S)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(S),m.browser.highlight(S)])}catch(T){e.warn({err:T},"Error highlighting element, continuing...")}}},tC={event:"locate",createHandler:Cz};var xz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({event:o,percentX:i,percentY:a})=>{let l=t.getSession(n);if(!l)throw new Error("No active session found");let c=l.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(s){e.error({err:s},"Error performing click during cloud recording in control mode")}}},rC={event:"mouseClickEvent",createHandler:xz};var _z=({metadata:r,generatorFactory:e,logger:t,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c,parentStepIdChain:s,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,t);p.setOpen(),d.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(y){t.warn({err:y},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(y,S)=>{S.type!=="PRESET_ACTION"||S.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:y,stepId:c,parentStepIdChain:s,command:S.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:s,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:t,testId:l,orgId:a,callbacks:{onActionReceived:y=>f("clickReceived",y),onStepRecorded:y=>f("descriptionGenerated",y)}},abortController:g,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:s,attribute:u})}},nC={event:"recordTargetClick",createHandler:_z};var Iz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.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(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key down socket event error");return}throw l}}},oC={event:"keyDownEvent",createHandler:Iz};var Pz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.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(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key up socket event error");return}throw l}}},iC={event:"keyUpEvent",createHandler:Pz};var Mz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r,o,i=0,a=(s,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},l,c=0;return async s=>{let u=t.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(s.event==="scroll"){let g=await m.scrollFromPositionPercentages(s.percentX,s.percentY,l?.x??0,l?.y??0),h=u.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}p.showOverlay&&a(m,s);try{let g=await m.moveMouseFromPositionPercentages(s.percentX,s.percentY);c=0,l=g}catch(g){c++,c%5===0&&e.warn({err:g,mouseErrors:c},"Error in socket mouse move handler")}}},aC={event:"mouseMoveEvent",createHandler:Mz};var Oz=({metadata:r,generatorFactory:e,socket:t,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c})=>{let s=o.getSession(i);if(!s)throw new Error("No active session found");let{controller:u,browserBehavior:d}=s,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,g=await u.startRecordMode({params:{generator:p,logger:n,testId:l,orgId:a,callbacks:{onActionReceived:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})},onStepRecorded:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:g}}},sC={event:"recordingStart",createHandler:Oz};var Lz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{let o=t.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}},lC={event:"recordingStop",createHandler:Lz};var Nz=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:l})=>async(c,s)=>{let{testId:u,sessionId:d,orgId:p}=e;t.info({testId:u,sessionId:d},"Refresh event received");let m=await i(p),g=await a(p,t),h=await n(p),{baseUrl:f}=await pi({testId:u,orgId:p,logger:t,storage:h,authorization:o,flagStore:m,settings:g}),y=l.getSession(d);if(!y){r.emit("error",{message:"No session to refresh"});return}let{controller:S}=y;S.setOpen(),await S.browser.refresh();let T=S.browser.getViewport();t.info({baseUrl:f,viewport:T},`Session refreshed for test ${u} at ${f}`),s()},cC={event:"refresh",createHandler:Nz};var Dz=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:l})=>async()=>{let{testId:c,sessionId:s,orgId:u}=e;t.info({testId:c,sessionId:s},"Reset event received");let d=await i(u),p=await a(u,t),m=await n(u),{baseUrl:g,envName:h,testName:f,environmentVariables:y}=await pi({testId:c,orgId:u,logger:t,storage:m,authorization:o,flagStore:d,settings:p}),S=l.getSession(s);if(!S){r.emit("error",{message:"No session to reset"});return}let{controller:T,context:A}=S;await T.browser.reset({newUrl:g});let R=T.browser.baseUrl;A.reset({baseUrl:R,currentUrl:T.browser.url(),variablesFromEnvironment:y,envName:h,testName:f});let w=T.browser.getViewport(),x=yr.USER_AGENT;t.info({baseUrl:g,viewport:w},`Session reset for test ${c} at ${R}`),r.emit("session",{url:R,userAgent:x,viewport:w,sessionId:s})},uC={event:"reset",createHandler:Dz};var kz=({metadata:r,globalE2eStateManager:e})=>{let{sessionId:t}=r;return async({url:n})=>{let o=e.getSession(t);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},dC={event:"switchTab",createHandler:kz};async function pC(r){return Qw(r)}var mC=[JT,Zw,tC,uC,cC,KT,dC,eC,nC,sC,lC,aC,rC,oC,iC,XT,YT];var gC=r=>{let{logger:e}=r,t=new Fz(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await pC({...r,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}mC.forEach(i=>Uz(i,{...r,socket:n,metadata:o,logger:e}))}),t},Uz=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event},`Websocket event (${r.event})`);let i=a=>{e.logger.error({event:r.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=t.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(r.event,n)};import{Router as Vz}from"express";import{Router as zz}from"express";import Js from"fs";import Xs from"path";import{v4 as Hz}from"uuid";import Gz from"yaml";import{hostname as Bz}from"os";var Ah="2.17.5",ht=tc({app:"desktop-server",hostname:Bz(),disableConsoleLogs:!0}).child({cliVersion:Ah});var Ta=zz();async function wh(r){return(await Mc(r,ht)).map(n=>{let o=r.modules[n.moduleId];if(!o){E.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)}Ta.get("/",ge(async(r,e)=>{let t=ae(),n=W(t),o=await wh(n);e.status(200).json(o)}));Ta.post("/",ge(async(r,e)=>{let t;try{t=ny.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}try{Vn(t.name)}catch(l){e.status(400).json({error:`Invalid module name: ${l}`});return}let n=ae(),o=W(n).modules;if(Object.values(o).find(l=>l.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=Xs.join(n.rootDir,t.folderPath??"");if(!Js.existsSync(i)||!Js.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Pc({...t,folder:i,project:n});e.status(201).json(a)}));Ta.get("/:moduleId",ge(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=W(ae()),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await fr(n,t,E);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ta.post("/:moduleId/duplicate",ge(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ry.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Vn(t.name)}catch(h){e.status(400).json({error:h.message});return}let n=ae(),o=W(n),i=o.modules[r.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let a=await fr(i,o,E),l=Xs.join(n.rootDir,Xs.dirname(i.relativePath));if(!Js.existsSync(l)||!Js.statSync(l).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${l}' does not exist.`});return}let c=xe(t.name),s=Xs.join(l,`${c}.module.yaml`),u=Hz(),{stepsToSave:d}=await ke({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:At()}}),p={fileType:he.MODULE,schemaVersion:oe,moduleId:u,name:t.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=Gz.stringify(p);Js.writeFileSync(s,m,"utf-8");let g={relativeFilePath:Xs.relative(n.rootDir,s)};e.status(201).json(g)}));Ta.patch("/:moduleId/metadata",ge(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=oy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ae(),o=W(n);IT({moduleId:r.params.moduleId,content:t,momenticFiles:o,logger:E,project:n}),e.status(201).json({message:"ok"})}));var hC=Ta;var fC=Vz();fC.get("/",ge(async(r,e)=>{let t=ae(),n=W(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(s=>{s.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),l=await wh(n),c={labels:i,tests:a,modules:l};e.status(200).json(c)}));var SC=fC;import{Router as jz}from"express";var Ch=jz();Ch.get("/",ge((r,e)=>{let t=Lc(ae(),ht);e.status(200).json(t)}));Ch.get("/names",ge((r,e)=>{let n=ae().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var yC=Ch;import{Router as $z}from"express";var EC=$z();EC.get("/",ge((r,e)=>{e.status(200).json({userId:Ji(),orgId:At()})}));var TC=EC;import{StreamableHTTPServerTransport as FH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as UH}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as BH}from"crypto";import{Router as zH}from"express";import{McpServer as DH}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as kH}from"@modelcontextprotocol/sdk/server/sse.js";import{tool as Wz}from"ai";import{z as qz}from"zod";var Zu=r=>({builder:(t,n)=>Wz({description:r.schema.description,inputSchema:qz.object(r.schema.inputSchema),execute:async o=>{try{await r.handle(t,o,n)}catch(i){n.addError(String(i))}return n.serialize()}}),tool:r});var ed=class{results=[];isError;addResult(e){this.results.push(e)}addError(e){this.results.push(`Error: ${e}`),this.isError=!0}getResult(){return this.results.join(`
4030
+ `),tokenLength:d}),u=[],d=0,p=m.length?[m[m.length-1].id]:[],g=!1);let h=c[s],f=xn(h);d+=f,h.length>a&&(h=h.slice(0,a));let y=Array.from(h.matchAll(Qw)).map(I=>I&&I.length>=3?{tagName:I[1],id:I[2]}:void 0).filter(I=>!!I),R=Array.from(h.matchAll(gz)).map(I=>I&&(I[2]||I[4])).filter(I=>!!I);R.reverse();let w=h.replace(/ id="[0-9]+"/g,"");u.push(w);for(let I of y)p.push(I.id),m.push(I);for(let I of R){let j=m[m.length-1];j&&j.tagName===I&&m.pop()}let x=m.some(I=>fz.includes(I.tagName)),_=c[s+1]??"",M=xn(_),$=Array.from(_.matchAll(Qw)).map(I=>I&&I.length>2?I[1]:void 0).filter(I=>!!I),k=$.some(I=>tC.includes(I)),Y=$.some(I=>hz.includes(I));d+M>=i&&(g=!0),d>=n&&(k&&!x||R.some(I=>Sz.includes(I)))&&(g=!0),d>=o&&Y&&!x&&(g=!0),s++}return u.length&&l.push({ids:p,content:u.join(`
4031
+ `),tokenLength:d}),l.forEach((h,f)=>{t.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${l.length})`)}),{chunks:l}}var Ez=9e5,Qu=3e5,Tz=5e3;async function di(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:l,signal:c}=t,s=r.tree,u=r.serializedTree,d=xn(u);if(d>Ez)try{let p=Ju({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});s=await vz({...r,tokenLimit:Qu-1e4,chunks:p.chunks}),u=s.serialize();let m=xn(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"),s=s.pruneToSerializedCharLimit(Qu*ui),u=s.serialize(),i.info("Filtered page using naive truncation")}if(d>Qu)try{if(o){let p=Ju({serializedTree:u,options:eC,logger:i});s=await z(bz({...r,chunks:p.chunks}),{milliseconds:12e3}),u=s.serialize();let m=xn(u);i.info({oldTokens:d,newTokens:m},"Filtered page using AI chunk ranking"),d=m}else{let p=Ju({serializedTree:u,options:Zw,logger:i});s=await z(Rz({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=s.serialize();let m=xn(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"),s=s.pruneToSerializedCharLimit(Qu*ui),u=s.serialize(),i.info("Filtered page using naive truncation")}if(o&&d>Tz&&r.type==="locator"&&(l==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||l==="org_01HMJTX4GT1KG94KZRCT8MZ6YB"))try{let p=await a.getPageSummary({browserContext:u,currentStep:r.description,screenshot:n,type:r.type},{logger:i,loggerTags:Pe(i),abortSignal:c});i.info(p,"Got AI summaries");let m=new Set;for(let h of p.relevantSections){let f=Math.min(h.startId,h.endId),E=Math.max(h.startId,h.endId);for(let S=f;S<=E;S++)m.add(S.toString())}s=s.pruneUsingRelevantIds(m),u=s.serialize();let g=xn(u);i.info({newTokens:g,oldTokens:d},"Filtered page using AI summary"),d=g}catch(p){i.warn({err:p},"Error filtering page using AI summary, continuing...")}return u}async function bz({type:r,chunks:e,description:t,fixtures:n,tree:o}){let{generator:i,signal:a,logger:l}=n,c=await i.rankChunksWithAi({chunks:e,description:t,type:r,softTokenLimit:4e4,hardTokenLimit:8e4},{abortSignal:a,logger:l,loggerTags:Pe(l)}),s=[];return e.forEach((d,p)=>{c.indices.includes(p)&&(s=s.concat(d.ids))}),o.pruneUsingRelevantIds(new Set(s))}async function vz(r){let{description:e,fixtures:t,tree:n}=r,{generator:o,logger:i,signal:a}=t;if(!e.trim())throw new Error("Empty description passed to page filtering");let l=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:Pe(i),abortSignal:a});i.info({keywordsResult:l},"Got keywords for page filtering");for(let c of l.keywords){let s=r.chunks.filter(m=>m.content.toLowerCase().includes(c.toLowerCase()));if(!s.length||s.reduce((m,g)=>m+g.tokenLength,0)>r.tokenLimit&&s.length>1)continue;let d=s.flatMap(m=>m.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function Rz(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:l,signal:c}=t,s=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:l,loggerTags:Pe(l)});if(s.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(s.ids.map(d=>`${d}`)))}async function Ah(r,e){if(!r.description)throw new C("UserConfigurationError","Cannot locate element with empty description");return en({action:async()=>Az(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function Az(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:l,aiPageFiltering:c,logger:s,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:p,browser:m,localCodeEvalTools:g,generator:h,abortSignal:f}=e,E=r.description,S=r.useMemory&&!t;n&&(E=await er({orgId:p,s:E,context:n,localTools:g,signal:f,logger:s})),a&&(E=Cz(E,a));let{serializedTree:y,tree:A}=await co(m,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:s}),R,w=Date.now(),x;for(;!R&&Date.now()-w<3e3;){f.throwIfAborted();try{R=await m.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(re){x=re}}if(!R)throw new C("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${x?.message}`);let _=y,M=!1,$=`data:image/jpeg;base64,${R.toString("base64")}`;_=await di({type:"locator",description:E,screenshot:$,serializedTree:y,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:s,orgId:p}}),_!==y&&(M=!0);let k=await h.getElementLocation({browserState:_,goal:E,screenshot:$,source:a,memory:S?l:void 0},{disableCache:t,abortSignal:f,loggerTags:Pe(s),useMemory:S});s.debug({usedRag:M,result:k},"Got locator result");let Y=k.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:Y,pageState:_,ragUsed:M,thoughts:k.thoughts}),!Y)throw new Bi(`Could not find any relevant element: ${k.thoughts}`,k.updatedMemory?{type:"GCS_TRACES",traces:k.updatedMemory}:void 0);let{resolution:I,target:j,frameConfig:ue}=await m.createTargetFromA11yId({id:k.id,requirements:k.requirements,additionalElements:k.additionalElements,description:E,targetSource:"AI",logger:s});if(I.a11yNode?.properties?.hidden&&I.a11yNode?.properties?.hidden!=="false")throw new C("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: ${I.displayString}`);return S&&(k.updatedMemory?j.memory={type:"GCS_TRACES",traces:k.updatedMemory}:l&&(j.memory=l)),{thoughts:k.thoughts,target:j,resolution:I,frameConfig:ue,screenshot:$}}var wz=["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:"],rC="<select> element:",nC="text input or contenteditable element:",oC="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:",iC="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:",Rh=[rC,nC,oC,iC,...wz];function aC(r,e){if(r===e)return!0;for(let t of Rh){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Rh.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Rh.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function Cz(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${rC} ${r}`;case"TYPE":return`${nC} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${oC}
4032
+ ${r}`;case"ELEMENT_CHECK":return`${iC}
4033
+ ${r}`;default:return r}}var xz=15;async function Zu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=xz}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:l}=n,c=r.timeout?r.timeout*1e3:l.smartWaitingTimeout,s=wT(c),u=0,d=Date.now(),p,m,g;try{await en({action:()=>l.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:l,logger:t})}catch(f){t.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 Z(s,n.abortSignal),h=Date.now();try{if(p=await en({action:async()=>{let E=await sC(l,t,n.abortSignal);return m&&m.serializedTree===E.serializedTree&&m.screenshotBuff.equals(E.screenshotBuff)?p:(m=E,lC({command:r,state:E,fixtures:n,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:u,aiPageFiltering:e,logger:t,source:o}))},frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l}),p?.updatedMemory&&hc(r,p.updatedMemory,t),p?.success)break;throw p?.thoughts?new C("AssertionFailureError",p.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),t.info({err:f},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!p?.success)try{p=await en({action:async()=>lC({command:r,state:await sC(l,t,n.abortSignal),fixtures:n,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:u,aiPageFiltering:e,logger:t}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,logger:t,browser:l})}catch(f){n.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!p?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:l.url()}}async function sC(r,e,t){let[n,o]=await Promise.all([co(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function lC({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:l,source:c,logger:s}){let{browser:u,generator:d,abortSignal:p}=t,m={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),S=u.url(),y=r.contextChoice??"MULTIMODAL",A=g;y!=="VISION_ONLY"&&(A=await di({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:s,orgId:t.orgId}}),A!==g&&(m.ragUsed=!0),m.pageState=A);let R={goal:r.assertion,url:S,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:y,source:c},x=await(y==="VISION_ONLY"?(_,M)=>d.getVisualAssertionResult(_,M):(_,M)=>d.getAssertionResult(_,M))(R,{useConsensus:n,attemptNumber:l,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:s,loggerTags:Pe(s)});return(x.result||i)&&x.relevantElements&&(m.relevantElementsSerialized=x.relevantElements.map(_=>u.getSerializedFormFromA11yId(_)).filter(_=>!!_),await _z(x.relevantElements,u,s)),{success:x.result,thoughts:x.thoughts,afterScreenshotOverride:f,updatedMemory:o?x.updatedMemory:void 0}}async function _z(r,e,t){let n=Date.now();for(let o of r){if(Date.now()-n>2e3){t.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await z(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){t.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var Iz=3e4;async function cC({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Iz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let l;if(qi(r.url)&&(l=r.url),t&&Ki(r.url,t)&&(l=new URL(r.url,t).toString()),!l)throw new C("ActionFailureError",`Invalid URL: ${r.url}`);let s=await z((async()=>{try{return await n(l,{headers:a,method:"POST",body:JSON.stringify({query:r.query,variables:r.variables?JSON.parse(r.variables):void 0}),signal:i.signal})}catch(d){e.error({err:d},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!s)throw new C("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!s.ok){let d,p=await s.text();try{d=JSON.parse(p)}catch{throw new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${d.errors[0].message}`):new C("ActionFailureError",`GraphQL request failed with status ${s.status}: ${p}`)}let u={};return s.headers.forEach((d,p)=>{u[p]=d}),{status:s.status,headers:u,json:await s.json()}}var uo=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,flagStore:o,storage:i,orgId:a,localCodeEvalTools:l,uploadedFileStorage:c,visualDiffScreenshotStorage:s,options:u}){this.orgId=a,this.options=u,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=i,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=s,this.localCodeEvalTools=l,this.generator=t,this.logger=n,this.flagStore=o}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:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:l=this.logger}){let[c,s]=await Promise.all([co(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:l}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${s.toString("base64")}`,d=await di({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:l,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Pe(l)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:l}){let c=this.browser.url(),[s,u]=await Promise.all([co(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 di({type:"ai-action",description:e,screenshot:d,serializedTree:s.serializedTree,tree:s.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:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(m,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Pe(a)},langfuseSessionId:l})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return co(this.browser,e)}async locateElement(e){return await Ah({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return en({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:t?{type:"url",url:t}: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,flagStore:this.flagStore,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:t,command:n,targetNames:o,descriptions:i,caches:a,action:l,options:c,retriesWithAI:s=1}){let u=[];for(let d=0;d<i.length;d++){let p=i[d],m=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(m)}try{let d=await l(...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(),s>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:l,options:c,retriesWithAI:s-1});throw new C("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await en({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:t})}catch(i){if(n=i,this.browser.userBrowserSettings.visualActions&&Fp(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&rs(i)){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Up(i)&&t.warn({err:i},"Invalid backend node id error, retrying element targeting command"),i instanceof $r&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:l}=o;if(t.type!=="description")throw new C("ActionFailureError","Cannot use selector with non-description target");let c,s=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){s=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:l,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()-s<500&&await Z(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:l,command:c}=e,{disableCache:s,useSelector:u,targetName:d,targetHealingInProgress:p,source:m}=l,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=l.retriesWithAI??1,E=!1,S=uC(e.cache);if((!S||s)&&!Bd(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);s&&(g.info("Cache explicitly disabled for this step"),E=!0,S=void 0),S&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&S.targetSource==="HEURISTIC_HEALED"&&(E=!0,S=void 0),S?.inputDescription&&!aC(o.elementDescriptor,S.inputDescription)&&(g.warn({old:S.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,S=void 0);let y=R=>!!R&&ml(R),A=!0;if(!y(S)){A=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:l.memory,useMemory:h},"Prompting AI for an updated element location"),E&&await Z(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let R;try{R=await Ah({description:o.elementDescriptor,disableCache:!!l.disableCache,iframeUrl:l.iframeUrl,source:m,useMemory:h,memory:h?l.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(_){if(_ instanceof Bi&&_.updatedLocatorMemory){let M={id:-1,...i,memory:_.updatedLocatorMemory};Ho({cmd:c,key:d,newTarget:M,logger:g})}throw new C("ActionFailureError",_.message)}R.frameConfig&&this.browser.setActiveFrameConfig(R.frameConfig);let w=l.disableGlobalLocatorRedirect?{locator:R.resolution.locator}:await this.attemptLocatorRedirect(R.resolution.locator,g),x=await a(w);return Ho({cmd:c,key:d,newTarget:R.target,logger:g}),p&&(n.heal({healType:"AI"}),R.target.targetSource="AI_HEALED",R.target.targetUpdateTime=new Date().toUTCString(),R.target.targetUpdateLoggerTags=Pe(g)),{result:x,elementInteractedDisplayString:R.resolution.displayString,thoughts:R.thoughts}}try{let R=await this.browser.resolveTarget(t,S,{allowNotActionableNodesOverride:l.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(R.locator);let w=l.disableGlobalLocatorRedirect?{locator:R.locator}:await this.attemptLocatorRedirect(R.locator,g),x=await a(w);if(Rr.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`]),Ho({cmd:c,key:d,newTarget:S,logger:g}),A){let _=R.decisions.filter(M=>M.matched);if(_.length!==1)g.warn({decisions:R.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let M=_[0].type;n.heal({healType:M})}}return{result:x,elementInteractedDisplayString:R.displayString}}catch(R){this.throwIfClosed(),Rr.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!S.requirements}`,`hasAdditionalElements:${!!S.additionalElements}`]);let w=!1;if((R instanceof $r||Fp(R)||rs(R)||Up(R)||JS(R)||QS(R))&&(w=!0),R instanceof C&&!w)throw g.error({err:R},"Failed to execute action with cached target (fatal)"),R;if(f>0&&o){g.info({err:R},"Failed to execute action with cached target, retrying with AI");let x;return S.memory&&gl(S.memory)&&(x=S.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...l,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",R.message,{errOptions:{cause:R}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return xs(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await Z(this.options.slowMoMs);let a=await this.browser.getOpenPages(),l=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(s){throw this.throwIfClosed(),new C("ActionFailureError",`Failed to substitute template strings in command: ${s.message}`,{errOptions:{cause:s}})}try{let s=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&vf(n)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await Rb({beforeUrl:l,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),s}catch(s){throw s.name!=="AbortError"&&this.logger.error({err:s},"Error thrown in action controller"),s}finally{db(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Ym(e)}}async resolveCommandTemplateStrings(e,t){return zc({obj:e,context:t,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,t,n,o,i){i=i||"disableCache"in n&&!!n.disableCache;let a=this.logger.child({commandId:n.id});switch(n.type){case"SUCCESS":let l=n.condition;return l?.assertion.trim()?Zu({command:l,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 C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Zu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=uE(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:Pe(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new C("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."):E.includes("AIProviderError")&&E.includes("time")?new C("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:f}}):f}}case"NAVIGATE":if(!qi(n.url)&&!Ki(n.url,this.browser.baseUrl))throw new C("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":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;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 g,h;if(n.target&&Hr(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:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=S,h=y}let f=this.browser.getViewport()?.height??Mt.height,E=this.browser.getViewport()?.width??Mt.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let s=n.delay*1e3;await Z(s,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Hr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,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:h,thoughts:E,data:f};return Ic(g,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(Hr(n.fromTarget)&&Hr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Hr(n.fromTarget)||Hr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Hr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,S,y;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:A,result:R,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async x=>x.locator,options:{disableCache:i,targetName:"target",...n}});E=R,S=A,y=w}return await this.browser.mouseDrag(g,h,f,E,{force:n.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:y}}case"SELECT_OPTION":{if(!Ln(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:S=>this.browser.selectOption(S,h,n.force),options:{...n,targetName:"target",disableCache:i,source:Oo(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);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 u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=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:g},"Executed JavaScript in browser")):g=await Zn({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 h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Hr(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 g=this.browser.url(),h,f,E=uC(n.target);if(E){let{elementInteractedDisplayString:y,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:R=>this.browser.typeIntoTarget(n.value,R,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:Oo(n)}});h=y,f=A}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let S={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Ic(g,S.urlAfterCommand)&&(S.succeedImmediately=!0,S.succeedImmediatelyReason="URL changed"),S}case"HOVER":{if(Hr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!Ln(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!Ln(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:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Ic(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;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 g=new Mz,h=Pz(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Sb({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:xS(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await cC({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return fb({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await jb({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Zn({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=Vl.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??Gr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(gb(n.assertion)&&!n.useSelector&&n.target.type==="description"&&h&&h!=="v1"){let E={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 Zu({command:E,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{E.cache?.memory&&hc(n,E.cache?.memory.traces,a)}}let f=await mb({command:n,tracer:t,timeoutMs:g,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await en({action:async()=>Gc({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:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new ro(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await dg(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await z(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new ro(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=eu(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=eu(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new ro(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new ro(n.requestMatcher),async(h,f)=>{let E=await Zn({orgId:this.orgId,code:n.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:a,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),S=zS.parse(E);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(g=>{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:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:Pe(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:t,isClickToRecord:n}){this.recordAbortController=t;let o=new ru({signal:t.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:Pe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Pe(this.logger)})}};import{cloneDeep as Oz}from"lodash-es";var Lz={showOverlay:!1},ed=class{sessions=new Map;sessionCountByIp=new Map;latestSessionId;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:t,cleanup:n,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:t,cleanup:n,clientIp:o,browserBehavior:Oz(Lz),socket:a}),this.latestSessionId=i,i}removeSession(e,t){(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){t.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){t.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}getLatestSession(){if(this.latestSessionId)return this.getSession(this.latestSessionId)}};function dC(r,e,t,n){let o=Date.now(),i=Date.now(),a,l,c,s,u=!1,d=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let E=c;c=void 0;let S=h.url(),y=f.toEditorDisplayCopy();JSON.stringify(y)===JSON.stringify(a)&&S===s&&o>i||(r.emit("browserState",{logsPerPage:E?.logsPerPage,harPages:E?.harPages,harEntries:E?.harEntries,viewport:h.getViewport(),url:S,iframeSrcUrls:l??[],context:y,isInPageLoad:h.isInPageLoad}),o=Date.now()),s=S,a=y}catch(E){if(!r.connected)return;let S=E instanceof Error?E.message:`${E}`;if(S.includes("Frame was detached")||S.includes("Not attached to an active page")||S.includes("browser has been closed")||S.includes("UserInfrastructureError"))return;t.error({err:E,sessionId:e},"Error grabbing browser state")}},p=setInterval(()=>{let h=n.getSession(e),f=h?.controller?.browser;if(!f||f.closed){t.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(l)||f.logsPerPage.some(E=>E.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).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 E=await f.getAllFrameUrls(),S=f.retrieveAndClearDebugData();m(E,S)&&(l=E,c=S,i=Date.now())}catch(E){t.warn({err:E},"Failed to fetch extended details")}finally{u=!1}},2500);return{timers:[p,g]}}var Nz=4;async function pC({socket:r,logger:e,storageFactory:t,uploadedFileStorage:n,visualDiffScreenshotStorage:o,devicePixelRatio:i,generatorFactory:a,enricherFactory:l,authorization:c,flagStoreFactory:s,settingsFactory:u,getOrgId:d,branchGetter:p,globalE2eStateManager:m}){let g=r.id,h=r.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let f=await d({type:"e2e",testId:h}),E=await p?.();e=e.child({testId:h,orgId:f,sessionId:g,branch:E});let S=await a(f,e),y=await l(f,e),A=await s(f),R=await u(f,e),w=await t(f),{testMetadata:x,baseUrl:_,envName:M,browserConfig:K,aiSettings:$,environmentVariables:k,localCodeEvalTools:Y}=await pi({testId:h,orgId:f,logger:e,storage:w,authorization:c,flagStore:A,settings:R}),I=m.getSession(g);if(I)return e.info("Associating connection with existing session (likely reconnect)"),await I.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:g,orgId:f,testId:h};let j=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:j,event:"connect",args:r.handshake.query},"Websocket event (connect)"),j&&m.getCurrentConnectionsByIp(j)>=Nz)throw e.error({clientIp:j,sessions:m.getCurrentSessionsByIp(),...r.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.");m.reserveCapacityByIp(j);try{await Dz({socket:r,baseUrl:_,envName:M,testMetadata:x,orgId:f,sessionId:g,logger:e,environmentVariables:k,clientIp:j,devicePixelRatio:i,storage:w,uploadedFileStorage:n,visualDiffScreenshotStorage:o,localCodeEvalTools:Y,generator:S,enricher:y,browserConfig:K,aiSettings:$,flagStore:A,globalE2eStateManager:m})}catch(ue){throw e.warn({err:ue},"Error setting up socket session, possibly due to client closing the connection"),m.releaseCapacityByIp(j),ue}return{type:"e2e",sessionId:g,testId:h,orgId:f}}async function Dz({socket:r,baseUrl:e,envName:t,devicePixelRatio:n,testMetadata:o,orgId:i,sessionId:a,logger:l,storage:c,uploadedFileStorage:s,visualDiffScreenshotStorage:u,localCodeEvalTools:d,generator:p,environmentVariables:m,browserConfig:g,aiSettings:h,clientIp:f,enricher:E,flagStore:S,globalE2eStateManager:y}){let A={viewport:o.advanced?.viewport??Mt,locale:o.advanced?.locale??Un,timezoneId:o.advanced?.timezone??Bn,geolocation:o.advanced?.geolocation??zn,colorScheme:o.advanced?.colorScheme};n&&(A.deviceScaleFactor=n);let R=o.id,w=await qc({settings:g,orgId:i,baseUrl:e,envName:t,testName:o.name,localTools:d,envVariables:m,logger:l,customHeaders:void 0});l=l.child({orgId:i,sessionId:a,testId:R});let x=S.isBooleanFlagEnabled("icon_knowledge_base")?await c.fetchIconKnowledgeBase(l):null,_=await yr.init({baseUrl:e,userBrowserSettings:w,enricher:E,storage:c,flagStore:S,logger:l,contextArgs:A,iconKnowledgeBase:x,callbacks:{onTabsChange:(Y,I)=>{r.emit("tabs",{tabs:Y,activeTab:I})},onScreencastFrame:(Y,I)=>{let j=r;Sn&&(j=r.compress(!0)),j.emit("screenshot",{buffer:Y},()=>{I()})},onSvgsCollected:Y=>{r.emit("newIconDetected",{numIcons:Y.newSvgs.length}),c.saveNewIcons(Y,l)}}});await _.navigate({url:e,initialNavigation:!0});let M=new uo({browser:_,generator:p,logger:l,flagStore:S,orgId:i,options:{scratchPadId:void 0,slowMoMs:w.slowMoMs,autoFollowNewTabs:w.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??S.isBooleanFlagEnabled("rag_v2")},storage:c,localCodeEvalTools:d,uploadedFileStorage:s,visualDiffScreenshotStorage:u}),K=dC(r,a,l,y),$=async()=>{K.timers.forEach(Y=>clearInterval(Y))},k=new qt({baseUrl:e,testName:o.name,currentUrl:M.browser.url(),variablesFromEnvironment:m,envName:t});if(!r.connected)throw await _.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:yr.USER_AGENT,viewport:M.browser.getViewport(),sessionId:a}),y.registerSession({controller:M,context:k,sessionId:a,cleanup:$,clientIp:f,socket:r})}async function pi({testId:r,orgId:e,logger:t,storage:n,authorization:o,settings:i}){let a=await n.fetchTestMetadata(r,t);if(!a)throw new Error(`Test metadata could not found for test ${r}`);let l;o?.type==="API_KEY"&&(l=new Yr({httpClient:new Rt({...o,logger:t}),fakerSeed:void 0}));let c=a.envs?.find(h=>h.default),s;c&&(s=await n.fetchEnvironment(c.name,t));let u=s&&"browser"in s?s.browser:void 0,d={...i.browser,...u,...a.advanced},p=a.baseUrl||s?.variables?.[ht];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let m={...s?.variables};await Promise.all((a.parameters??[]).map(async h=>{let f=await er({orgId:e,s:h.defaultValue,context:qt.dummyContext(a.name,s?.name,m),logger:t,localTools:l});m[h.name]=f}));let g={...i.ai,...a.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:s?.name,testName:a.name,browserConfig:d,environmentVariables:m,testMetadata:a,aiSettings:g}}var wh=class{parentTracer=null;socket;step;orgId;constructor({step:e,socket:t,parentTracer:n,orgId:o}){this.socket=t,this.parentTracer=n,this.step=e,this.orgId=o}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}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 po({parentStep:this.step,socket:this.socket,parentTracer:this,orgId:this.orgId})}},po=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,t]of Object.entries(this.stepFrequenciesByType))Rr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}constructor({parentStep:e,socket:t,parentTracer:n,orgId:o}){this.parentTracer=n,this.parentStep=e,this.socket=t,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 wh({step:e.step,parentTracer:this,socket:this.socket,orgId:this.orgId})}async finish(){this.sendFinalizedStepStats()}},td=class{constructor(e,t,n,o,i){this.socket=e;this.storage=t;this.orgId=n;this.testId=o;this.stepsBeforeRun=i}children=[];async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished"),await Promise.all(this.children.map(e=>e.finish()))}async startBeforeStepList(){let e=new po({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startMainStepList(){let e=new po({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}async startAfterStepList(){let e=new po({orgId:this.orgId,parentStep:null,parentTracer:null,socket:this.socket});return this.children.push(e),e}};var Ch={currentlyExecutingRequests:{}},Fz=r=>async(e,t)=>{let{testId:n,orgId:o}=r.metadata,i=await r.flagStoreFactory(o),a=await r.settingsFactory(o,r.logger),l=await r.storageFactory(o),c,s=await pi({testId:n,orgId:o,logger:r.logger,storage:l,authorization:r.authorization,flagStore:i,settings:a}),u=`${n}|${s.baseUrl}`;try{let d=Ch.currentlyExecutingRequests[u]??0;Ch.currentlyExecutingRequests[u]=d+1,c=await Uz({...r,...e,...s,done:t})}finally{r.logger.info({result:c,sessionId:r.metadata.sessionId},"Test execution complete"),Ch.currentlyExecutingRequests[u]--}},Uz=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,toStep:i,fromStep:a,storageFactory:l,aiSettings:c,browserConfig:s,metadata:u,logger:d,envName:p,testName:m,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:E,globalE2eStateManager:S})=>{let{testId:y,sessionId:A,orgId:R}=u,w=A,x=S.getSession(A);if(!x)throw new Error("No active session found");let{controller:_,context:M}=x;_.setOpen(),d=d.child({testId:y,orgId:R,sessionId:A,runId:w}),d.info({steps:e.map(ne=>`${ne.type}${"command"in ne?` - ${ne.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:p,testName:m,baseUrl:t,context:M,flags:_.flagStore.getAllFlags()},"Socket execution parameters");let K=g??{},$=async()=>{o&&(await _.browser.reset({newUrl:t}),M.reset({baseUrl:t,currentUrl:_.browser.url(),variablesFromEnvironment:K,envName:p,testName:m}))},k=await l(R),Y=await E(R),I=async()=>{try{await Y.resolveStepCacheEntries({schemaVersion:n.schemaVersion,testId:y,stepLists:{steps:e},logger:d})}catch(ne){d.error({err:ne},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await ys({promiseGenerator:async()=>Promise.all([$(),I()]),signal:_.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),_.setOpen()}catch(ne){if(r.emit("finished"),ne.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${ne}`)}let j=kz(e),ue={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},re={orgId:R,runId:w,testMetadata:n,steps:e,fromStep:a,toStep:i,orgSettings:{ai:c,browser:s}},Re={controller:_,context:M,storage:k,codeEvalTools:h,usageTracker:new Ni,logger:d},He={test:{},step:{onDynamicAIActionStatusUpdateEvent:ne=>{r.emit("dynamicCommandStatusUpdate",ne)},onDynamicAIActionEvaluatingEvent:ne=>{r.emit("dynamicCommandEvaluating",ne)},onDynamicCommandGenerated:ne=>{r.emit("dynamicCommandGenerated",ne)},onDynamicCommandExecuted:ne=>{r.emit("dynamicCommandExecuted",ne)}}},Ar=new td(r,k,R,y,j),nt=await Wc({fixtures:Re,options:ue,callbacks:He,inputs:re,testParams:{tracer:Ar}});return nt?.status==="PASSED"?await fc({logger:d,cacheStorage:Y,orgId:R,testId:y,originalSteps:{steps:j},updatedSteps:{steps:e}}):nt?.status==="FAILED"&&await Sc({logger:d,cacheStorage:Y,orgId:R,testId:y,originalSteps:{steps:j},updatedSteps:{steps:e}}),await Ar.finish(),f?.(nt),nt.status};var mC={event:"execute",createHandler:Fz};import{cloneDeep as Bz}from"lodash-es";var zz=r=>async({command:e},t)=>{let{logger:n,generatorFactory:o,metadata:i}=r,a=Bz(e),l=qE(a);if(l.category!=="NO_DESCRIPTION_PROVIDED"){if(l.category!=="NONE"){t?.({result:l});return}"cache"in a&&(a.cache=void 0);try{let s=await(await o(i.orgId,n)).getLintStepResult({command:a},{logger:n});t?.({result:s})}catch(c){n.error({event:"lint",err:c},"Failed to lint step"),t?.({result:void 0})}}},gC={event:"lintStep",createHandler:zz};var Hz=({metadata:r,logger:e,storageFactory:t,globalE2eStateManager:n})=>{let{sessionId:o,orgId:i}=r;return async(a,l)=>{let{description:c,command:s,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 t(i),f=Fo.parse(u.advanced??{}),E={},S;if(c){if("useSelector"in s&&s.useSelector)try{let y=await m.locateElementWithSelector(c,"iframeUrl"in s?s.iframeUrl:void 0);S=y.resolution.locator,E={target:y.target,thoughts:y.thoughts}}catch(y){e.warn({err:y},"Failed resolving target with selector"),l({err:`Failed locating element: ${y.message}`,decisions:y instanceof jr?y.decisions:void 0});return}else try{let y=await m.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Oo(s),iframeUrl:"iframeUrl"in s?s.iframeUrl:void 0,memory:"cache"in s&&s.cache&&"target"in s.cache&&gl(s.cache.target.memory)?s.cache.target.memory:void 0,logger:e});E={target:y.target,thoughts:y.thoughts},S=y.resolution.locator}catch(y){(async()=>{try{let A=await m.browser.getCondensedHtml({skipWait:!0});e.warn({err:y,html:A.slice(0,1e5)},"Failed locating element with AI")}catch(A){e.warn({err:A},"Failed grabbing HTML after trying to locate element with AI")}})(),l({err:`${y.message}`});return}if(s.type==="SELECT_OPTION"&&S)try{E.options=await m.browser.getSelectOptions(S)}catch(y){e.warn({err:y},"Failed getting select options"),l({err:`Failed getting select options: ${y.message}`});return}e.info({result:E},"Locate handler result")}if(d)try{let{buffer:y,width:A,height:R}=await m.screenshotWithDimensions({clearHighlights:!0,locator:S}),w=await h.uploadScreenshot(y);E.screenshot={data:w,width:A,height:R},e.info({width:A,height:R},"Captured screenshot during locate")}catch(y){e.error({err:y},"Error capturing screenshot during locate"),l({err:`Error taking screenshot: ${y.message}`});return}if(l({result:E}),S)try{await Promise.all([m.browser.scrollIntoViewIfNeeded(S),m.browser.highlight(S)])}catch(y){e.warn({err:y},"Error highlighting element, continuing...")}}},hC={event:"locate",createHandler:Hz};var Gz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({event:o,percentX:i,percentY:a})=>{let l=t.getSession(n);if(!l)throw new Error("No active session found");let c=l.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(s){e.error({err:s},"Error performing click during cloud recording in control mode")}}},fC={event:"mouseClickEvent",createHandler:Gz};var Vz=({metadata:r,generatorFactory:e,logger:t,socket:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c,parentStepIdChain:s,attribute:u})=>{let d=o.getSession(i);if(!d)throw new Error("No active session found");let{controller:p}=d,m=await e(a,t);p.setOpen(),d.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{d.browserBehavior.showOverlay=!1,await p.stopRecordMode()}catch(E){t.warn({err:E},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(E,S)=>{S.type!=="PRESET_ACTION"||S.command.type!=="CLICK"||(n.emit("targetRecordingUpdate",{type:E,stepId:c,parentStepIdChain:s,command:S.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:s,attribute:u}))},1e4),await p.startRecordMode({params:{generator:m,logger:t,testId:l,orgId:a,callbacks:{onActionReceived:E=>f("clickReceived",E),onStepRecorded:E=>f("descriptionGenerated",E)}},abortController:g,isClickToRecord:!0}),n.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:s,attribute:u})}},SC={event:"recordTargetClick",createHandler:Vz};var jz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.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(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key down socket event error");return}throw l}}},yC={event:"keyDownEvent",createHandler:jz};var $z=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async({key:o})=>{let i=t.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(l){if(l.message.includes("has been closed")){e.debug({sessionId:n,err:l},"Browser is closed, ignoring key up socket event error");return}throw l}}},EC={event:"keyUpEvent",createHandler:$z};var Wz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r,o,i=0,a=(s,u)=>{let d=async()=>{o=void 0};clearTimeout(o),o=setTimeout(d,Math.min(1e3,250*(i+1)))},l,c=0;return async s=>{let u=t.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(s.event==="scroll"){let g=await m.scrollFromPositionPercentages(s.percentX,s.percentY,l?.x??0,l?.y??0),h=u.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}p.showOverlay&&a(m,s);try{let g=await m.moveMouseFromPositionPercentages(s.percentX,s.percentY);c=0,l=g}catch(g){c++,c%5===0&&e.warn({err:g,mouseErrors:c},"Error in socket mouse move handler")}}},TC={event:"mouseMoveEvent",createHandler:Wz};var qz=({metadata:r,generatorFactory:e,socket:t,logger:n,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:l}=r;return async({stepId:c})=>{let s=o.getSession(i);if(!s)throw new Error("No active session found");let{controller:u,browserBehavior:d}=s,p=await e(a,n);n.info("Starting cloud recording");let m=new AbortController,g=await u.startRecordMode({params:{generator:p,logger:n,testId:l,orgId:a,callbacks:{onActionReceived:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})},onStepRecorded:(h,f)=>{t.emit("stepRecorded",{stepId:c,step:h,offset:f})}}},abortController:m,isClickToRecord:!1});d.recordingState={transformer:g}}},bC={event:"recordingStart",createHandler:qz};var Kz=({metadata:r,logger:e,globalE2eStateManager:t})=>{let{sessionId:n}=r;return async()=>{let o=t.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}},vC={event:"recordingStop",createHandler:Kz};var Yz=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:l})=>async(c,s)=>{let{testId:u,sessionId:d,orgId:p}=e;t.info({testId:u,sessionId:d},"Refresh event received");let m=await i(p),g=await a(p,t),h=await n(p),{baseUrl:f}=await pi({testId:u,orgId:p,logger:t,storage:h,authorization:o,flagStore:m,settings:g}),E=l.getSession(d);if(!E){r.emit("error",{message:"No session to refresh"});return}let{controller:S}=E;S.setOpen(),await S.browser.refresh();let y=S.browser.getViewport();t.info({baseUrl:f,viewport:y},`Session refreshed for test ${u} at ${f}`),s()},RC={event:"refresh",createHandler:Yz};var Xz=({socket:r,metadata:e,logger:t,storageFactory:n,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:l})=>async()=>{let{testId:c,sessionId:s,orgId:u}=e;t.info({testId:c,sessionId:s},"Reset event received");let d=await i(u),p=await a(u,t),m=await n(u),{baseUrl:g,envName:h,testName:f,environmentVariables:E}=await pi({testId:c,orgId:u,logger:t,storage:m,authorization:o,flagStore:d,settings:p}),S=l.getSession(s);if(!S){r.emit("error",{message:"No session to reset"});return}let{controller:y,context:A}=S;await y.browser.reset({newUrl:g});let R=y.browser.baseUrl;A.reset({baseUrl:R,currentUrl:y.browser.url(),variablesFromEnvironment:E,envName:h,testName:f});let w=y.browser.getViewport(),x=yr.USER_AGENT;t.info({baseUrl:g,viewport:w},`Session reset for test ${c} at ${R}`),r.emit("session",{url:R,userAgent:x,viewport:w,sessionId:s})},AC={event:"reset",createHandler:Xz};var Jz=({metadata:r,globalE2eStateManager:e})=>{let{sessionId:t}=r;return async({url:n})=>{let o=e.getSession(t);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:n})}},wC={event:"switchTab",createHandler:Jz};async function CC(r){return pC(r)}var xC=[tb,mC,hC,AC,RC,QT,wC,gC,SC,bC,vC,TC,fC,yC,EC,eb,ZT];var _C=r=>{let{logger:e}=r,t=new Qz(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return t.on("connection",async n=>{let o;try{e.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),o=await CC({...r,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}xC.forEach(i=>Zz(i,{...r,socket:n,metadata:o,logger:e}))}),t},Zz=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event},`Websocket event (${r.event})`);let i=a=>{e.logger.error({event:r.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=t.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(r.event,n)};import{Router as oH}from"express";import{Router as tH}from"express";import el from"fs";import Zs from"path";import{v4 as rH}from"uuid";import nH from"yaml";import{hostname as eH}from"os";var xh="2.17.7",Ze=ic({app:"desktop-server",hostname:eH(),disableConsoleLogs:!0}).child({cliVersion:xh});var Ra=tH();async function _h(r){return(await Nc(r,Ze)).map(n=>{let o=r.modules[n.moduleId];if(!o){T.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)}Ra.get("/",fe(async(r,e)=>{let t=se(),n=W(t),o=await _h(n);e.status(200).json(o)}));Ra.post("/",fe(async(r,e)=>{let t;try{t=sy.parse(r.body)}catch(l){e.status(400).json({error:`Invalid request body: ${l}`});return}try{Hn(t.name)}catch(l){e.status(400).json({error:`Invalid module name: ${l}`});return}let n=se(),o=W(n).modules;if(Object.values(o).find(l=>l.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let i=Zs.join(n.rootDir,t.folderPath??"");if(!el.existsSync(i)||!el.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Lc({...t,folder:i,project:n});e.status(201).json(a)}));Ra.get("/:moduleId",fe(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=W(se()),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await hr(n,t,T);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ra.post("/:moduleId/duplicate",fe(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ay.parse(r.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Hn(t.name)}catch(h){e.status(400).json({error:h.message});return}let n=se(),o=W(n),i=o.modules[r.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===t.name)){e.status(400).send(`A module with the name "${t.name}" already exists. Please choose a different name.`);return}let a=await hr(i,o,T),l=Zs.join(n.rootDir,Zs.dirname(i.relativePath));if(!el.existsSync(l)||!el.statSync(l).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${l}' does not exist.`});return}let c=_e(t.name),s=Zs.join(l,`${c}.module.yaml`),u=rH(),{stepsToSave:d}=await Fe({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:At()}}),p={fileType:Se.MODULE,schemaVersion:ie,moduleId:u,name:t.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=nH.stringify(p);el.writeFileSync(s,m,"utf-8");let g={relativeFilePath:Zs.relative(n.rootDir,s)};e.status(201).json(g)}));Ra.patch("/:moduleId/metadata",fe(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=ly.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=se(),o=W(n);LT({moduleId:r.params.moduleId,content:t,momenticFiles:o,logger:T,project:n}),e.status(201).json({message:"ok"})}));var IC=Ra;var PC=oH();PC.get("/",fe(async(r,e)=>{let t=se(),n=W(t),o=new Set;n?.tests&&Object.values(n.tests).forEach(s=>{s.labels?.forEach(u=>o.add(u))});let i=Array.from(o).sort(),a=Object.values(n.tests),l=await _h(n),c={labels:i,tests:a,modules:l};e.status(200).json(c)}));var MC=PC;import{Router as iH}from"express";var Ih=iH();Ih.get("/",fe((r,e)=>{let t=kc(se(),Ze);e.status(200).json(t)}));Ih.get("/names",fe((r,e)=>{let n=se().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var OC=Ih;import{Router as aH}from"express";var LC=aH();LC.get("/",fe((r,e)=>{e.status(200).json({userId:Ji(),orgId:At()})}));var NC=LC;import{StreamableHTTPServerTransport as QH}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as ZH}from"@modelcontextprotocol/sdk/types.js";import{randomUUID as e1}from"crypto";import{Router as t1}from"express";import{McpServer as XH}from"@modelcontextprotocol/sdk/server/mcp.js";import{SSEServerTransport as JH}from"@modelcontextprotocol/sdk/server/sse.js";import{tool as sH}from"ai";import{z as lH}from"zod";var rd=r=>({builder:(t,n)=>sH({description:r.schema.description,inputSchema:lH.object(r.schema.inputSchema),execute:async o=>{try{await r.handle(t,o,n)}catch(i){n.addError(String(i))}return n.serialize()}}),tool:r});var nd=class{results=[];isError;addResult(e){this.results.push(e)}addError(e){this.results.push(`Error: ${e}`),this.isError=!0}getResult(){return this.results.join(`
4033
4034
  `)}async serialize(){let e=[];return this.results.length&&(e.push("### Result"),e.push(this.results.join(`
4034
4035
  `)),e.push("")),{content:[{type:"text",text:e.join(`
4035
- `)}],isError:this.isError}}};var cn=r=>{let e=(n,o)=>{let i=async(a,l)=>{let c=new ed;try{await r.handle(n,a,c)}catch(s){c.addError(String(s))}return await c.serialize()};o.registerTool(r.schema.name,{title:r.schema.name,description:r.schema.description,inputSchema:r.schema.inputSchema},i)};return{...Zu(r),addToolToMcpServer:e,name:r.schema.name}};import{z as xh}from"zod";var kr=xh.object({id:xh.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Ni.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:xh.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(r=>[r.id,r.name,r.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided.");function Fr(r,e,t){let n=W(r),o=t==="test"?n.tests:t==="module"?n.modules:n.mobileTests,i=Kz(o,e);if(e.id){if(i.length===0)throw new _e(`No ${t} found with id '${e.id}' in project '${r.rootDir}'.`);return _h(i,n)}else if(e.name){if(i.length===0)throw new _e(`No ${t} found with exact name '${e.name}' in project '${r.rootDir}'.`);if(i.length>1){let a=i.map(l=>({id:l.id,path:l.relativePath}));throw new _e([`Multiple ${t}s found with exact name '${e.name}'. Please disambiguate by id or path.`,JSON.stringify(a,null,2)].join(`
4036
- `))}return _h(i,n)}else if(e.path){let a=e.path;if(i.length===0)throw new _e(`No ${t} found at path '${a}'. Provide an absolute path or a path relative to '${r.rootDir}'.`);if(i.length>1){let l=i.map(c=>({id:c.id,path:c.fullFilePath}));throw new _e([`Multiple ${t}s matched the provided path '${a}'. Please pass the absolute path.`,JSON.stringify(l,null,2)].join(`
4037
- `))}return _h(i,n)}else throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function _h(r,e){let t=r[0];if(!t)throw r.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return{entity:t,momenticFiles:e}}function Kz(r,e){if(e.id){let t=Object.values(r).find(n=>n.id===e.id);return t?[t]:[]}else{if(e.name)return Object.values(r).filter(t=>t.name===e.name);if(e.path){let t=e.path;return Object.values(r).filter(n=>n.fullFilePath.includes(t)||n.relativePath.includes(t))}else throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}}var Yz=cn({schema:{name:"momentic_module_get",description:"Get a single fully loaded module by id, exact name, or file path. Exactly one selector must be provided. Module names must follow valid entity name rules.",inputSchema:{selector:kr}},handle:async(r,e,t)=>{let{project:n,logger:o}=r;try{let i=Fr(n,e.selector,"module"),a=await fr(i.entity,i.momenticFiles,o);t.addResult(JSON.stringify({module:a},null,2))}catch(i){t.addError(String(i));return}}}),Xz=cn({schema:{name:"momentic_module_list",description:"List modules.",inputSchema:{}},handle:async(r,e,t)=>{let{project:n}=r,o=W(n),a=Object.values(o.modules).map(l=>({id:l.id,name:l.name,description:l.description,relativePath:l.relativePath,fullFilePath:l.fullFilePath,platformSep:l.platformSep,fullPathSegments:l.fullPathSegments,relativePathSegments:l.relativePathSegments,fileName:l.fileName,lastModified:l.lastModified,createdAt:l.createdAt,type:l.type}));t.addResult(JSON.stringify({modules:a},null,2))}}),td=[Yz,Xz];var Jz=cn({schema:{name:"momentic_environment_list",description:"List environments defined in the project's momentic.config.yaml file.",inputSchema:{}},handle:async(r,e,t)=>{let{project:n,logger:o}=r,i=Lc(n,o);t.addResult(JSON.stringify({environments:i},null,2))}}),bC=[Jz];import{streamText as xH}from"ai";import _H from"path";import{z as IH}from"zod";var ba=new Ju;var go=class extends Vi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchTestMetadata(t){let n=ae(),i=W(n).tests[t];if(i)return Oc(i.relativePath,n)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,n){let o=ae();return Ts(t,o,En)}async fetchIconKnowledgeBase(t){try{return await this.client.fetchIconKnowledgeBase(t)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}};var mi=class{async prepareGoldenScreenshotForComparison(e,t,n){return await new na(ae(),!1).prepareGoldenScreenshotForComparison(e,t,n)}};import vC from"path";import{v4 as Qz}from"uuid";async function rd({project:r,input:e}){try{Vn(e.name)}catch(s){throw new _e(`${s} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new _e("Either 'baseUrl' or 'environment' must be provided when creating a test.");let t=W(r);if(Object.values(t.tests).find(s=>s.name===e.name))throw new _e(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:Qz(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:oe,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Mt},retries:0,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=vC.join(r.rootDir,...e.pathSegments||[]),l=await MT({test:i,name:e.name,folder:a});return{...i,relativeFilePath:vC.relative(r.rootDir,l)}}import{stepCountIs as CH}from"ai";import{createAnthropic as Zz}from"@ai-sdk/anthropic";import{randomUUID as eH}from"crypto";var RC=r=>e=>Zz({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${r}`},apiKey:r})(e);var Qs=async({step:r,controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l})=>{let{results:c}=await tH({steps:[r],controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l});return c[0]},tH=async({steps:r,controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l})=>{let c={controller:e,storage:t,codeEvalTools:n,logger:o,context:a,usageTracker:new Di},s=i?new mo({orgId:l,parentStep:null,parentTracer:null,socket:i}):new is;return Or({listParams:{containerName:"copilot-steps",steps:r,tracer:s},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:l,runId:eH(),steps:r,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};import rH from"dedent";var AC=rH`
4036
+ `)}],isError:this.isError}}};var cn=r=>{let e=(n,o)=>{let i=async(a,l)=>{let c=l.sessionId??"unknown",s=Date.now(),u=Ze.child({sessionId:c,toolName:r.schema.name});u.debug({toolName:r.schema.name,params:Wi({json:a,maxJsonStringSize:500}),sessionId:c},`MCP tool invoked: ${r.schema.name}`);let d=new nd,p;try{await r.handle(n,a,d)}catch(h){h instanceof Error?(p=h,d.addError(String(h))):d.addError(`Unknown value thrown: ${String(h)}`)}let m=Date.now()-s,g=await d.serialize();if(p)u.error({toolName:r.schema.name,sessionId:c,duration:m,err:p},`MCP tool failed: ${r.schema.name}`);else{let h=g.content.filter(f=>f.type==="text");u.debug({toolName:r.schema.name,sessionId:c,duration:m,responseIsError:g.isError,response:Wi({json:h,maxJsonStringSize:500})},`MCP tool completed: ${r.schema.name}`)}return g};o.registerTool(r.schema.name,{title:r.schema.name,description:r.schema.description,inputSchema:r.schema.inputSchema},i)};return{...rd(r),addToolToMcpServer:e,name:r.schema.name}};import{z as Ph}from"zod";var kr=Ph.object({id:Ph.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Li.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:Ph.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(r=>[r.id,r.name,r.path].filter(Boolean).length===1,"Exactly one of id, name, or path must be provided.");function Fr(r,e,t){let n=W(r),o=t==="test"?n.tests:t==="module"?n.modules:n.mobileTests,i=cH(o,e);if(e.id){if(i.length===0)throw new Ie(`No ${t} found with id '${e.id}' in project '${r.rootDir}'.`);return Mh(i,n)}else if(e.name){if(i.length===0)throw new Ie(`No ${t} found with exact name '${e.name}' in project '${r.rootDir}'.`);if(i.length>1){let a=i.map(l=>({id:l.id,path:l.relativePath}));throw new Ie([`Multiple ${t}s found with exact name '${e.name}'. Please disambiguate by id or path.`,JSON.stringify(a,null,2)].join(`
4037
+ `))}return Mh(i,n)}else if(e.path){let a=e.path;if(i.length===0)throw new Ie(`No ${t} found at path '${a}'. Provide an absolute path or a path relative to '${r.rootDir}'.`);if(i.length>1){let l=i.map(c=>({id:c.id,path:c.fullFilePath}));throw new Ie([`Multiple ${t}s matched the provided path '${a}'. Please pass the absolute path.`,JSON.stringify(l,null,2)].join(`
4038
+ `))}return Mh(i,n)}else throw new Error("No valid selector field provided. Exactly one of id, name, or path must be specified.")}function Mh(r,e){let t=r[0];if(!t)throw r.length>0?new Error("No entity found: matches array is not empty. Unknown error."):new Error("No entity found.");return{entity:t,momenticFiles:e}}function cH(r,e){if(e.id){let t=Object.values(r).find(n=>n.id===e.id);return t?[t]:[]}else{if(e.name)return Object.values(r).filter(t=>t.name===e.name);if(e.path){let t=e.path;return Object.values(r).filter(n=>n.fullFilePath.includes(t)||n.relativePath.includes(t))}else throw new Error("No valid selector field provided: expected exactly one of 'id', 'name', or 'path'.")}}var uH=cn({schema:{name:"momentic_module_get",description:"Get a single fully loaded module by id, exact name, or file path. Exactly one selector must be provided. Module names must follow valid entity name rules.",inputSchema:{selector:kr}},handle:async(r,e,t)=>{let{project:n,logger:o}=r;try{let i=Fr(n,e.selector,"module"),a=await hr(i.entity,i.momenticFiles,o);t.addResult(JSON.stringify({module:a},null,2))}catch(i){t.addError(String(i));return}}}),dH=cn({schema:{name:"momentic_module_list",description:"List modules.",inputSchema:{}},handle:async(r,e,t)=>{let{project:n}=r,o=W(n),a=Object.values(o.modules).map(l=>({id:l.id,name:l.name,description:l.description,relativePath:l.relativePath,fullFilePath:l.fullFilePath,platformSep:l.platformSep,fullPathSegments:l.fullPathSegments,relativePathSegments:l.relativePathSegments,fileName:l.fileName,lastModified:l.lastModified,createdAt:l.createdAt,type:l.type}));t.addResult(JSON.stringify({modules:a},null,2))}}),od=[uH,dH];var pH=cn({schema:{name:"momentic_environment_list",description:"List environments defined in the project's momentic.config.yaml file.",inputSchema:{}},handle:async(r,e,t)=>{let{project:n,logger:o}=r,i=kc(n,o);t.addResult(JSON.stringify({environments:i},null,2))}}),DC=[pH];import{streamText as GH}from"ai";import VH from"path";import{z as jH}from"zod";var Aa=new ed;var mo=class extends Gi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchTestMetadata(t){let n=se(),i=W(n).tests[t];if(i)return Dc(i.relativePath,n)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(t,n){let o=se();return Rs(t,o,yn)}async fetchIconKnowledgeBase(t){try{return await this.client.fetchIconKnowledgeBase(t)}catch(n){return t.error({err:n},"Failed to fetch icon knowledge base"),null}}};var mi=class{async prepareGoldenScreenshotForComparison(e,t,n){return await new na(se(),!1).prepareGoldenScreenshotForComparison(e,t,n)}};import kC from"path";import{v4 as mH}from"uuid";async function id({project:r,input:e}){try{Hn(e.name)}catch(s){throw new Ie(`${s} when validating the test entity name`)}if(!e.baseUrl&&!e.environment)throw new Ie("Either 'baseUrl' or 'environment' must be provided when creating a test.");let t=W(r);if(Object.values(t.tests).find(s=>s.name===e.name))throw new Ie(`A test with the name "${e.name}" already exists. Please use a different name.`);let i={id:mH(),name:e.name,description:e.description,baseUrl:e.baseUrl,schemaVersion:ie,advanced:{browserType:e.browserType??"Chromium",viewport:e.viewport??Mt},retries:0,steps:[]};e.environment&&(i.envs=[{name:e.environment,default:!0}]);let a=kC.join(r.rootDir,...e.pathSegments||[]),l=await DT({test:i,name:e.name,folder:a});return{...i,relativeFilePath:kC.relative(r.rootDir,l)}}import{stepCountIs as HH}from"ai";import{createAnthropic as gH}from"@ai-sdk/anthropic";import{randomUUID as hH}from"crypto";var FC=r=>e=>gH({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${r}`},apiKey:r})(e);var tl=async({step:r,controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l})=>{let{results:c}=await fH({steps:[r],controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l});return c[0]},fH=async({steps:r,controller:e,storage:t,codeEvalTools:n,logger:o,socket:i,testContext:a,orgId:l})=>{let c={controller:e,storage:t,codeEvalTools:n,logger:o,context:a,usageTracker:new Ni},s=i?new po({orgId:l,parentStep:null,parentTracer:null,socket:i}):new ls;return Lr({listParams:{containerName:"copilot-steps",steps:r,tracer:s},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:l,runId:hH(),steps:r,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};import SH from"dedent";var UC=SH`
4038
4039
  <core-identity>
4039
4040
  You are the Momentic Copilot. You are an experienced SDET who is building and editing a Momentic browser E2E test. Instead of CSS selectors, Momentic uses natural language descriptions to identify elements. Your responses must be specific, accurate, and concise.
4040
4041
  </core-identity>
@@ -4042,27 +4043,60 @@ You are the Momentic Copilot. You are an experienced SDET who is building and ed
4042
4043
  <edit-protocol>
4043
4044
  1. ALWAYS reset the session to make sure the browser is in a clean state.
4044
4045
  2. ALWAYS look at the page to see what is currently on the screen.
4045
- 3. ALWAYS look at the test to see what steps currently exist.
4046
- 4. ALWAYS preview the step to see if it does what you expect before making any changes.
4047
- 5. Periodically verify checkpoints using preview_ensure to make sure the test is doing what you expect.
4048
- 6. If there are existing steps, make sure to run them first to make sure the page is in the expected state.
4049
- 6. Preview changes
4050
- - Before executing, verify page state with preview_ensure.
4051
- - Execute using preview_step.
4052
- - If a step fails in preview, add/adjust a nearby wait or clarify the step, then try once more.
4053
- - If it still fails, stop the edit and report the smallest fix needed.
4054
- - DO NOT ADD BROKEN STEPS.
4055
- 7. Plan a MINIMAL DELTA:
4056
- - Prefer to use insert, replace, and remove.
4057
- - Use splice to add or remove multiple steps at once.
4058
- - DO NOT change unrelated steps.
4046
+ 3. ALWAYS look at the test to see what steps currently exist. Use the screen and html to understand the current state of the page.
4047
+ 4. ALWAYS validate elements BEFORE creating steps that interact with them:
4048
+ - Use preview_preflight with your element description to verify the element can be found and see its HTML
4049
+ - If preview_preflight fails, observe_page to understand what's actually on screen, then refine your description
4050
+ - Try at most 2-3 different element descriptions; if none work, STOP and report the issue to the user with details about what you tried
4051
+ - NEVER create steps for elements you haven't successfully validated with preview_preflight
4052
+ 5. ALWAYS check the test and execute all steps before the changes you want to add to the test. ENSURE you are in the right page state before making any changes.
4053
+ 6. Proactively verify page state using preview_ensure, especially:
4054
+ - Before adding multiple steps in sequence
4055
+ - After navigation or page transitions
4056
+ - Before interacting with dynamic content (modals, dropdowns, async-loaded elements)
4057
+ - When you suspect timing issues or async operations
4058
+ - Use preview_ensure to confirm critical elements are present and page is ready
4059
+ - If page is not ready, add an AI Check step with a wait condition before proceeding
4060
+ 7. Preview and validate ALL changes with a strict failure protocol:
4061
+ - Before executing, verify page state with preview_ensure
4062
+ - Execute using preview_step or run_step
4063
+ - If a step or tool fails:
4064
+ a. First attempt: Analyze the failure. Is it a timing issue? Add an AI Check step to wait for the condition and retry
4065
+ b. Second attempt: Is it an element description issue? Use preview_preflight to find a better description and retry
4066
+ c. Third attempt: Check if page state is wrong by using preview_ensure or observe_page
4067
+ d. If it fails 3 times, STOP IMMEDIATELY and report the specific failure to the user - include what you tried
4068
+ e. NEVER proceed to the next step if the current step is broken
4069
+ - DO NOT ADD BROKEN STEPS TO THE TEST UNDER ANY CIRCUMSTANCES
4070
+ 8. After making any new steps, execute each step sequentially and validate:
4071
+ - Execute the step and check the result status carefully
4072
+ - If a step fails, follow the strict 3-attempt protocol in #7 above
4073
+ - Verify the page state before and after each step matches expectations
4074
+ - If preview shows unexpected state from previous steps, re-execute earlier steps to confirm they work
4075
+ - Do not proceed to the next step unless the current step executes successfully
4076
+ 9. Handle tool failures gracefully and systematically:
4077
+ - If preview_preflight fails: Try alternative natural language descriptions based on visible page content
4078
+ - If preview_ensure fails: The page state is not what you expected - investigate why before proceeding
4079
+ - If run_step or preview_step fails: Check if previous steps need to be re-executed or if a wait is needed
4080
+ - If observe_page shows unexpected content: Adjust your plan based on actual page state
4081
+ - NEVER ignore or skip over tool errors - always investigate and address them
4082
+ - After 3 failed attempts to resolve a tool failure, STOP and report to the user
4083
+ 10. Plan a MINIMAL DELTA:
4084
+ - Prefer to use insert, replace, and remove
4085
+ - Use splice to add or remove many steps at once. If you add multiple steps you MUST be able to successfully execute them all in the order of the test before moving on
4086
+ - DO NOT change unrelated steps
4087
+ 11. NEVER continue onto subsequent steps if you cannot successfully execute the previous step. This is explicitly forbidden. STOP and report failures to the user after 3 attempts.
4059
4088
  </edit-protocol>
4060
4089
 
4061
4090
  <element-description>
4062
4091
  - ALWAYS use natural language descriptions to identify elements.
4063
4092
  - NEVER use CSS selectors, XPath, or HTML syntax to identify elements.
4064
4093
  - NEVER use hardcoded names or data-attributes to identify elements.
4065
- - Use the page to identify the element that the user intended to interact with.
4094
+ - Use preview_preflight first to validate your element description before creating steps.
4095
+ - When describing elements, focus on their visible characteristics, role, and context:
4096
+ - Good: "the close button in the top right of the modal", "the blue submit button at the bottom of the form"
4097
+ - Bad: "the x button", "button with class modal-close", "the icon"
4098
+ - If preview_preflight fails, use observe_page to see what's actually visible, then try alternative descriptions.
4099
+ - For elements that are hard to describe (like icons without text), describe their purpose, position, or relationship to nearby elements.
4066
4100
  </element-description>
4067
4101
 
4068
4102
  <javascript>
@@ -4101,42 +4135,48 @@ axios, moment, faker, assert, pg, Octokit (auto), createAppAuth (auto), OTPAuth
4101
4135
 
4102
4136
  <test-structure>
4103
4137
  - If there are multiple ways to achieve the same goal, choose the most appropriate one based on the context and the user's intent.
4104
- - Account for loading times and other asynchronous operations when adding steps.
4105
- - Avoid hardcoding waits, instead prefer to use AI check.
4138
+ - ALWAYS account for loading times and asynchronous operations:
4139
+ - After navigation, wait for the page to fully load before interacting with elements
4140
+ - After clicking buttons that trigger async actions (modals, dropdowns, API calls), add waits before the next interaction
4141
+ - Before interacting with dynamic content, use preview_ensure to confirm it's ready
4142
+ - Use AI Check steps to wait for specific conditions (e.g., "wait for the modal to be visible")
4143
+ - NEVER rely on hoping elements will be ready - always verify or wait explicitly
4144
+ - When adding multiple related steps (e.g., filling a form), add a preview_ensure checkpoint partway through to catch issues early.
4145
+ - Avoid hardcoding numeric waits (e.g., "wait 5 seconds"), instead prefer AI Check with specific conditions.
4106
4146
  </test-structure>
4107
4147
 
4108
4148
  <safety>
4109
4149
  - Never insert destructive actions (e.g., mass delete) unless explicitly asked.
4110
4150
  - Keep edits scoped to the user's intent; do not optimize unrelated steps.
4111
4151
  </safety>
4112
- `;import nH from"path";var nd=class{_result=[];_includeSnapshot=!1;_includeTestContext=!1;_includeTest=!1;_isError;_browser;_testContext;_project;_logger;_testPath;constructor(e,t,n,o,i){this._browser=e,this._testContext=t,this._project=n,this._logger=o,this._testPath=i}addResult(e){this._result.push(e)}result(){return this._result.join(`
4152
+ `;import yH from"path";var ad=class{_result=[];_includeSnapshot=!1;_includeTestContext=!1;_includeTest=!1;_isError;_browser;_testContext;_project;_logger;_testPath;constructor(e,t,n,o,i){this._browser=e,this._testContext=t,this._project=n,this._logger=o,this._testPath=i}addResult(e){this._result.push(e)}result(){return this._result.join(`
4113
4153
  `)}setIncludeSnapshot(){this._includeSnapshot=!0}async snapshot(){if(!this._includeSnapshot)return"";let e=this._browser.getActivePage(),t=await this._browser.getBrowserState({skipWait:!1}),n=[];return n.push("### Page state",`- Page URL: ${e.url()}`,`- Page Title: ${await e.title()}`,"- Page Snapshot:","```xml",t.serialize(),"```"),n.join(`
4114
4154
  `)}setIncludeTestContext(){this._includeTestContext=!0}testContext(){if(!this._includeTestContext)return"";let e=[],t=this._testContext.toObjectCopy();return e.push("### Environment variables","```json",JSON.stringify(t,null,2),"```"),e.join(`
4115
- `)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=W(this._project),t=await tt(nH.join(this._project.rootDir,this._testPath),this._logger,e),n=[];return n.push("### Test","```json",JSON.stringify(t,null,2),"```"),n.join(`
4155
+ `)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=W(this._project),t=await rt(yH.join(this._project.rootDir,this._testPath),this._logger,e),n=[];return n.push("### Test","```json",JSON.stringify(t,null,2),"```"),n.join(`
4116
4156
  `)}addError(e){this._result.push(e),this._isError=!0}async serialize(){let e=[];this._result.length&&(e.push("### Result"),e.push(this._result.join(`
4117
4157
  `)),e.push(""));let t=await this.snapshot();t&&e.push(t,"");let n=this.testContext();n&&e.push(n,"");let o=await this.test();return o&&e.push(o,""),{content:[{type:"text",text:e.join(`
4118
- `)}],isError:this._isError}}};var ut=r=>({builder:Zu(r).builder,name:r.schema.name});var oH=ut({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeSnapshot()}}),wC=[oH];import Ph from"path";import{v4 as sH}from"uuid";import{z as fo}from"zod";import{randomUUID as Ih}from"crypto";import{z as ho}from"zod";import{z as iH}from"zod";var gi={id:!0,cache:!0},va=iH.discriminatedUnion("type",[Ao.omit(gi),_o.omit(gi),Co.omit(gi),Un.omit(gi),Fn.omit(gi),wo.omit(gi),xo.omit(gi),$d.omit({id:!0}),Gd.omit({id:!0}),Xd.omit({id:!0}),Ai.omit({id:!0}),Yd.omit({id:!0}),Jd.omit({id:!0}),Vd.omit({id:!0})]);var aH=ho.object({selector:kr,inputs:ho.record(ho.string()).optional()}),CC=ho.discriminatedUnion("type",[ho.object({type:ho.literal("PRESET_ACTION"),action:va}),ho.object({type:ho.literal("MODULE"),module:aH})]).describe("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.");async function xC(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Ih()},id:Ih()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Fr(e,n,"module"),l=await fr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Ih(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var lH=ut({schema:{name:"momentic_module_create",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:{name:fo.string(),description:fo.string(),enabled:fo.boolean().default(!0),subDir:fo.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:fo.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:fo.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}},handle:async(r,e,t)=>{let{project:n,logger:o,testPath:i}=r,a=e.startIndex??0,l=e.endIndex??a+1,c=W(n);if(Object.values(c.modules).find(p=>p.name===e.name))throw new _e(`A module with the name "${e.name}" already exists. Please use a different name.`);let u=[];if(e.startIndex!==void 0){if(!i)throw new _e("testPath is required when extracting steps from the current test.");let p=await tt(Ph.join(n.rootDir,i),o,c);if(a<0||a>=p.steps.length)throw new _e(`startIndex ${a} is out of bounds. Test has ${p.steps.length} steps.`);if(l<=a||l>p.steps.length)throw new _e(`endIndex ${l} is out of bounds. Must be between ${a+1} and ${p.steps.length}.`);u=p.steps.slice(a,l);for(let m of u)if(m.type==="RESOLVED_MODULE")throw new _e("Modules cannot be nested. Please select steps that do not include module references.")}let d=await Pc({name:e.name,description:e.description,enabled:e.enabled,steps:u,folder:e.subDir?Ph.join(n.rootDir,e.subDir):n.rootDir,project:n});if(c=W(n),e.startIndex!==void 0){let p=await tt(Ph.join(n.rootDir,i),o,c),m={type:"RESOLVED_MODULE",id:sH(),moduleId:d.moduleId,name:e.name,description:e.description,enabled:e.enabled,parameters:[],steps:u,inputs:{}};p.steps.splice(a,l-a,m);let{stepsToSave:g,moduleUpdates:h}=await ke({stepLists:{steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps}});h.forEach(f=>{Dt({content:f,schemaVersion:oe,momenticFiles:c,project:n})}),wt({relativeTestPath:i,steps:g,schemaVersion:oe,project:n})}t.addResult(JSON.stringify(d,null,2))}});function cH(r,e,t,n){if(r===void 0&&e!==void 0)throw new _e("Validation Error: startIndex is required when endIndex is provided.");if(r!==void 0&&e===void 0&&t===0)throw new _e("Validation Error: steps are required when startIndex is provided without an endIndex.");if(r!==void 0&&(r>n||r<0))throw new _e(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&r===void 0)throw new _e("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&r!==void 0&&e<r)throw new _e("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new _e(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let o=r??n;if((e??o)===o&&t===0)throw new _e("Validation Error: Nothing to insert or delete. Provide steps or a valid delete range.")}var uH=ut({schema:{name:"momentic_module_change",description:"Edit a module's steps. 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.",inputSchema:{selector:kr,steps:CC.array(),startIndex:fo.number().optional(),endIndex:fo.number().optional()}},handle:async(r,e,t)=>{let{project:n,logger:o}=r,i=await Promise.all(e.steps.map(h=>xC(h,n,o))),{entity:a,momenticFiles:l}=Fr(n,e.selector,"module"),c=await fr(a,l,o),s=i.find(h=>!rp(h));if(s){t.addError(`Validation Error: step type ${s.type} cannot be added to a module.`);return}try{cH(e.startIndex,e.endIndex,e.steps.length,c.steps.length)}catch(h){t.addError(String(h));return}let u=[...c.steps],d=e.startIndex!==void 0?e.startIndex:u.length,p=e.endIndex!==void 0?e.endIndex:d;u.splice(d,p-d,...i);let{stepsToSave:m}=await ke({stepLists:{steps:u}});Dt({content:{...c,steps:m.steps},schemaVersion:oe,momenticFiles:l,project:n});let g={...c,steps:u,stepCount:u.length};t.addResult(JSON.stringify(g,null,2))}}),_C=[lH,uH];import{randomUUID as od}from"crypto";import{z as IC}from"zod";var dH=ut({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:{description:IC.string().describe("Description of the element to preview.")}},handle:async({controller:r,logger:e,testContext:t},n,o)=>{o.setIncludeSnapshot();try{let i=await r.locateElement({description:n.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});i.resolution.locator&&await Promise.all([r.browser.scrollIntoViewIfNeeded(i.resolution.locator),r.browser.highlight(i.resolution.locator)]),o.addResult(`Found element matching description: ${i.target.id}`),i.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${i.target.nodeOnlySerializedHtml}`);return}catch(i){o.addError(`Failed to find any element matching description: ${i}`)}}}),pH=ut({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:{assertion:IC.string().describe("Assertion to confirm page state.")}},handle:async(r,e,t)=>{t.setIncludeSnapshot();let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:l,orgId:c,testContext:s}=r,u={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:od()},id:od()},d=await Qs({step:u,controller:i,storage:o,codeEvalTools:a,logger:n,socket:l,orgId:c,testContext:s});if(!d){t.addError("Assertion executed with unknown result.");return}if(d.status==="SUCCESS"){t.addResult(`Assertion is true: ${d.message}`);return}t.addError(`Assertion is false: ${d.message}`)}}),mH=ut({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:{command:va}},handle:async(r,e,t)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:l,orgId:c,testContext:s}=r;t.setIncludeSnapshot();let u={type:"PRESET_ACTION",command:{...e.command,id:od()},id:od()},d=await Qs({step:u,controller:i,storage:o,codeEvalTools:a,logger:n,socket:l,orgId:c,testContext:s});if(!d){t.addError("Assertion executed with unknown result.");return}if(d.status==="SUCCESS"){t.addResult(`Assertion is true: ${d.message}`);return}t.addError(`Assertion is false: ${d.message}`)}}),PC=[dH,pH,mH];import gH from"path";import{z as hH}from"zod";var fH=ut({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeTestContext()}}),SH=ut({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await r.controller.browser.reset({})}}),yH=ut({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:{index:hH.number()}},handle:async(r,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:n,logger:o,testPath:i,storage:a,controller:l,codeEvalTools:c,socket:s,orgId:u,testContext:d}=r,p=W(n),g=(await tt(gH.join(n.rootDir,i),o,p)).steps[e.index];if(!g){t.addError(`Step at index ${e.index} does not exist.`);return}let h=await Qs({step:g,controller:l,storage:a,codeEvalTools:c,logger:o,socket:s,orgId:u,testContext:d});if(!h){t.addError(`Step at index ${e.index} executed with unknown result.`);return}if(h.status==="SUCCESS"){t.addResult(`Step at index ${e.index} executed successfully: ${h.message}`),h.data&&t.addResult(`Data: ${JSON.stringify(h.data,null,2)}`);return}t.addError(`Step at index ${e.index} failed: ${h.message}`)}}),MC=[fH,SH,yH];import{randomUUID as Mh}from"crypto";import Zs from"path";import{z as rr}from"zod";var EH=rr.object({selector:kr,inputs:rr.record(rr.string()).optional()}),id=rr.discriminatedUnion("type",[rr.object({type:rr.literal("PRESET_ACTION"),action:va}),rr.object({type:rr.literal("MODULE"),module:EH})]).describe("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.");async function ad(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Mh()},id:Mh()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Fr(e,n,"module"),l=await fr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Mh(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var TH=ut({schema:{name:"test_get",description:"Get test contents.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeTest()}}),bH=ut({schema:{name:"test_insert_step",description:"Insert a step or module into the test.",inputSchema:{index:rr.number(),step:id}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await tt(Zs.join(n.rootDir,i),o,l),s=await ad(e.step,n,o);c.steps.splice(e.index,0,s);let{stepsToSave:u,moduleUpdates:d}=await ke({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:oe,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:oe,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),vH=ut({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:{index:rr.number(),step:id}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await tt(Zs.join(n.rootDir,i),o,l),s=await ad(e.step,n,o);c.steps.splice(e.index,1,s);let{stepsToSave:u,moduleUpdates:d}=await ke({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:oe,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:oe,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),RH=ut({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:{index:rr.number()}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await tt(Zs.join(n.rootDir,i),o,l);c.steps.splice(e.index,1);let{stepsToSave:s,moduleUpdates:u}=await ke({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});u.forEach(d=>{Dt({content:d,schemaVersion:oe,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:s,schemaVersion:oe,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),AH=ut({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:{startIndex:rr.number(),deleteCount:rr.number(),steps:id.array()}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await tt(Zs.join(n.rootDir,i),o,l),s=await Promise.all(e.steps.map(p=>ad(p,n,o)));c.steps.splice(e.startIndex,e.deleteCount,...s);let{stepsToSave:u,moduleUpdates:d}=await ke({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:oe,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:oe,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),wH=ut({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:{commands:id.array()}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await tt(Zs.join(n.rootDir,i),o,l),s=await Promise.all(e.commands.map(p=>ad(p,n,o)));c.steps=s;let{stepsToSave:u,moduleUpdates:d}=await ke({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:oe,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:oe,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),OC=[TH,bH,vH,RH,AH,wH];var LC=[..._C,...wC,...MC,...PC,...OC,...td];function sd(r,e,t,n){let o=Qi(),i=At(),a=Qn(),l=ae(),c=new Xe({apiKey:o,baseUrl:a,logger:t}),s=new go(c,i),u=new Jr(l.config),d=new Yr({httpClient:new Rt({baseUrl:c.baseUrl,apiKey:c.apiKey,logger:t}),fakerSeed:l.config.advanced?.fakerConstantSeed?Bi:void 0}),p={project:l,apiKey:o,orgId:i,baseUrl:a,logger:t,storage:s,flagStore:u,codeEvalTools:d,testPath:r,testContext:n.context,controller:n.controller,socket:n.socket},m=LC.reduce((f,{name:y,builder:S})=>(f[y]=S(p,new nd(p.controller.browser,p.testContext,p.project,p.logger,p.testPath)),f),{});return{model:RC(o)("claude-opus-4-20250514"),stopWhen:CH(30),maxRetries:4,system:AC,messages:e,tools:m}}var PH=cn({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:Fp},handle:async(r,e,t)=>{let{project:n}=r;try{let o=await rd({project:n,input:e});t.addResult(JSON.stringify(o,null,2))}catch(o){t.addError(String(o));return}}}),MH=cn({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(r,e,t)=>{let{project:n}=r,o=W(n),a=Object.values(o.tests).map(l=>({id:l.id,name:l.name,description:l.description,relativePath:l.relativePath,fullFilePath:l.fullFilePath,platformSep:l.platformSep,fullPathSegments:l.fullPathSegments,relativePathSegments:l.relativePathSegments,fileName:l.fileName,lastModified:l.lastModified,createdAt:l.createdAt,type:l.type,labels:l.labels||[]}));t.addResult(JSON.stringify({tests:a},null,2))}}),OH=cn({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:kr}},handle:async(r,e,t)=>{let{project:n,logger:o}=r;try{let i=Fr(n,e.selector,"test"),a=await tt(i.entity.fullFilePath,o,i.momenticFiles);t.addResult(JSON.stringify({test:a},null,2))}catch(i){t.addError(String(i));return}}});async function LH(r,e,t){let n=ba.getLatestSession();if(n)return n;let o=Qi(),i=At(),a=Qn(),l=new mi,c=new Xe({apiKey:o,baseUrl:a,logger:r}),s=new go(c,i),u=new Jr(e.config),d=(await tt(t.fullFilePath,r,W(e))).advanced?.viewport??Mt,p=new Yn(e.config.ai?.agentConfig,{baseUrl:a,apiKey:o,logger:r}),m=new Xn({baseUrl:a,apiKey:o,logger:r},p),g=await yr.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:m,storage:s,flagStore:u,logger:r,contextArgs:{viewport:d,locale:zn,timezoneId:Hn,geolocation:Gn},iconKnowledgeBase:null,callbacks:{}}),h=new po({browser:g,generator:p,logger:r,flagStore:u,orgId:i,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:s,localCodeEvalTools:new Yr({httpClient:new Rt({baseUrl:a,apiKey:o,logger:r}),fakerSeed:e.config.advanced?.fakerConstantSeed?Bi:void 0}),visualDiffScreenshotStorage:l}),f=new qt({baseUrl:"about:blank",testName:_H.basename(t.relativePath),currentUrl:g.url(),variablesFromEnvironment:{},envName:void 0});return{controller:h,context:f,socket:void 0}}var NH=cn({schema:{name:"momentic_test_edit",description:"Edit a test.",inputSchema:{selector:kr,message:IH.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(r,e,t)=>{let{project:n,logger:o}=r,{entity:i,momenticFiles:a}=Fr(n,e.selector,"test"),l=sd(i.relativePath,[{role:"user",content:e.message}],o,await LH(o,n,i)),c=xH({...l}),s=[];for await(let p of c.textStream)s.push(p);let u=await tt(i.fullFilePath,o,a),d=s.join("").split(`
4119
- `).map(p=>p.trim()).filter(p=>p.length>0);t.addResult(JSON.stringify({editedTest:u,messages:d},null,2))}}),NC=[MH,PH,OH,NH];var DC=[...bC,...NC,...td];function Oh(r,e){let t=new DH({name:e.applicationName,version:e.cliVersion});for(let n of DC)n.addToolToMcpServer(r,t);return t}async function kC(r,e,t,n){let o=new kH(t,e,n);return await r.connect(o),{close:async()=>{try{await r.close()}catch{}},transport:o}}var HH="mcp-session-id",GH="sessionId",ld=zH(),el=new Map;function FC(){let r={applicationName:"momentic-mcp-desktop-server",cliVersion:Ah??"0.0.0"},e=ae(),t=ht.child({orgId:At(),userId:Ji(),...r});return{context:{project:e,logger:t},info:r}}ld.get("/sse",async(r,e)=>{let{context:t,info:n}=FC(),o=Oh(t,n),{transport:i}=await kC(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,l={transport:i,close:async()=>{el.delete(a);try{await o.close()}catch(c){t.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};el.set(a,l),i.onclose=()=>{let c=el.get(a);c&&c.close()}});ld.post("/sse",async(r,e)=>{let t=String(r.query[GH]??"");if(!t||!el.has(t)){e.status(400).send("Invalid or missing sessionId");return}await el.get(t).transport.handlePostMessage(r,e,r.body)});var UC=ld,Ra=new Map;ld.all("/",async(r,e)=>{let t=String(r.headers[HH]??"");if(t&&Ra.has(t)){await Ra.get(t).handle(r,e,r.body);return}let n=r.method==="GET",o=r.method==="POST"&&UH(r.body);if(!n&&!o){e.status(400).send("Bad Request: No valid session ID provided");return}let{context:i,info:a}=FC(),l=Oh(i,a),c=new FH({sessionIdGenerator:()=>BH(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Ra.set(s,{handle:async(u,d,p)=>{await c.handleRequest(u,d,p)},close:async()=>{Ra.delete(s);try{await c.close()}catch{}try{await l.close()}catch{}}})}});c.onclose=()=>{let s=c.sessionId;s&&Ra.has(s)&&Ra.get(s).close()},await l.connect(c),await c.handleRequest(r,e,r.body)});import{Router as VH}from"express";var cd=VH();cd.get("/",ge((r,e)=>{let t=Mm().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));cd.get("/current",ge((r,e)=>{let t=ae();if(!t){e.status(404).json({error:"No project found."});return}let n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));cd.post("/set",ge((r,e)=>{let t;try{t=ay.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Tt({configFilePath:t.configFilePath});Ic(n,o=>Tt({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var BC=cd;import{Router as jH}from"express";var zC=jH();zC.get("/",ge((r,e)=>{let n={ai:ae().config.ai};e.status(200).json(n)}));var HC=zC;import{convertToModelMessages as qH,streamText as KH}from"ai";import{Router as YH}from"express";import GC from"fs";import rl from"path";import{v4 as XH}from"uuid";import JH from"yaml";import{randomUUID as $H}from"node:crypto";import{PostHog as WH}from"posthog-node";var ud=class r{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new WH("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new r({...this.bindings,...e},this.options)}track(e,t){if(!SS(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:$H(),event:n,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};var tl=new ud({platform:"local_app"},{flushAt:1,flushInterval:0});var So=YH();So.post("/",ge(async(r,e)=>{let t;try{t=ey.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=ae(),o=await rd({project:n,input:t});tl.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof _e){e.status(400).json({error:n.message});return}throw n}}));So.get("/:testPath",ge(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=ae(),o=W(n),i;try{i=await tt(rl.join(n.rootDir,t),ht,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:l}=await ke({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});l.forEach(c=>{Dt({content:c,schemaVersion:oe,momenticFiles:o,project:n})}),wt({relativeTestPath:t,steps:a,schemaVersion:oe,project:n})}catch(a){ht.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));So.patch("/:testPath/metadata",ge(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=ZS.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Am(r.params.testPath,t,ae()).newRelativeTestPath};e.status(200).json(o)}));So.patch("/:testPath",ge(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=QS.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});return}let o=ae(),i=W(o),a;try{a=Oc(t,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:l,moduleUpdates:c,cachesToSave:s}=await ke({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:At()}}),u=new Xe({apiKey:Qi(),baseUrl:Qn(),logger:ht}),d=await Zn(ht,u,o);await Yi({orgId:At(),client:u,gitMetadata:d}).saveStepCacheEntries({logger:ht,testId:a.id,entries:s}),c.forEach(m=>{Dt({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),wt({relativeTestPath:t,steps:l,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));So.patch("/:testPath/environments",ge(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=iy.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Am(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},ae()),e.status(201).json({message:"ok"})}));So.post("/:testPath/duplicate",ge(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=ty.parse(r.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Vn(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=ae(),i=rl.join(o.rootDir,t);if(!GC.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=W(o),l;try{l=await tt(i,ht,a)}catch(f){e.status(400).send({error:f.message});return}let c=XH(),s=mr.parse({...l,name:n.name,id:c}),{stepsToSave:u}=await ke({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:At()}}),d=bn({fileType:he.TEST,...s,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=rl.dirname(i),m=rl.join(p,`${n.name}.${yt.TEST}`),g=JH.stringify(d);GC.writeFileSync(m,g,"utf-8");let h={relativeFilePath:rl.relative(o.rootDir,m)};tl.track({type:"test_editor:test_create"}),e.status(201).json(h)}));So.post("/:testPath/chat",ge(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=r.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let o=qH(n),i=ba.getLatestSession();if(!i){e.status(400).json({error:"No active browser session. Start a session first."});return}let a=sd(t,o,ht,i);KH(a).pipeUIMessageStreamToResponse(e,{onError:c=>c instanceof Error?c.message:String(c)})}));var VC=So;async function qC(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,staticDir:o,devicePixelRatio:i,alwaysSaveCache:a,noCache:l,initialProject:c}=r;e&&CT(e),await xT(t);let s=At(),u=Ji();tl.identify({user_id:u,org_id:s});let d=r.logger??ht;d=d.child({orgId:s,userId:u}),d.debug({params:r},"Desktop server init and api key check done");let p=o1(o,n,d),m=`http://localhost:${n}`;E.info(`Desktop server is running at ${m}`),Ic(c,A=>Tt({configFilePath:A})),await new Promise(A=>{try{p.listen(n,()=>{d.info(`Desktop server is running at ${m}`),A()})}catch(R){R.message.includes("EADDRINUSE")?KC(n):E.error(`An unexpected error occurred while starting the server: ${R.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:Qn(),apiKey:t,logger:d},f=async()=>{let A=ae();return new Yn(A.config.ai?.agentConfig,h)},y=async()=>new Xn(h,await f()),S=new Xe(h),T=new mi;gC({baseServer:p,getOrgId:async()=>At(),generatorFactory:f,enricherFactory:y,cacheStorageFactory:async A=>{let R=ae(),w=await Zn(d,S,R);return Yi({orgId:A,client:S,gitMetadata:w,alwaysSaveCache:a,noCache:l})},branchGetter:async()=>{try{return(await Nm(d))?.gitBranchName}catch(A){d.error({err:A},"Failed to get environment git metadata");return}},flagStoreFactory:async A=>{let R=ae();return new Jr(R.config)},settingsFactory:async()=>{let A=ae();return{ai:{},browser:{},...A.config}},storageFactory:async A=>new go(S,A),logger:d,devicePixelRatio:i,authorization:h,visualDiffScreenshotStorage:T,globalE2eStateManager:ba})}var WC="25mb";function o1(r,e,t){let n=$C();n.use(QH()),n.use(jC.json({limit:WC})),n.use(jC.urlencoded({extended:!1,limit:WC}));let o=t1();if(o.use("/tests",VC),o.use("/modules",hC),o.use("/environments",yC),o.use("/projects",BC),o.use("/folders",Rm),o.use("/settings",HC),o.use("/identify",TC),o.use("/entities",SC),o.use("/mcp",UC),n.use("/api",o),n.use((a,l,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&t.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"),l.on("close",()=>{l.statusCode>=400&&t.error({url:a.url,method:a.method,statusCode:l.statusCode},"Request completed in error")}),c()}),n.use((a,l,c,s)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}t.error({stack:a.stack,msg:a.message,err:a,url:l.url,method:l.method},"Unhandled exception leading to 500 on desktop-server"),E.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
4120
- ${a.stack}`),c.status(500).send(`Internal Server Error: ${a.message}`)}),r){let a=$C.static(r,{setHeaders:l=>{l.setHeader("Cache-Control","no-cache")},redirect:!1});n.use(a),n.use("*",(l,c)=>{c.sendFile(n1.join(r,"index.html"))})}let i=r1.createServer(n);return i.once("error",a=>{"code"in a&&a.code==="EADDRINUSE"?(KC(e),process.exit(1)):console.error("An unexpected server error occurred:",a.message)}),i}e1.setMaxListeners(50);process.on("warning",r=>{ht.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{ht.error({err:r},"Uncaught exception on desktop-server"),E.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",(r,e)=>{ht.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on desktop-server (promise rejection)"),E.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function KC(r){E.error(ZH`Port ${r} is already in use by another process. Please close the other process and try again.
4158
+ `)}],isError:this._isError}}};var pt=r=>({builder:rd(r).builder,name:r.schema.name});var EH=pt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeSnapshot()}}),BC=[EH];import Lh from"path";import{v4 as vH}from"uuid";import{z as ho}from"zod";import{randomUUID as Oh}from"crypto";import{z as go}from"zod";import{z as TH}from"zod";var gi={id:!0,cache:!0},wa=TH.discriminatedUnion("type",[Ro.omit(gi),xo.omit(gi),wo.omit(gi),kn.omit(gi),Dn.omit(gi),Ao.omit(gi),Co.omit(gi),Kd.omit({id:!0}),$d.omit({id:!0}),Zd.omit({id:!0}),Ri.omit({id:!0}),Qd.omit({id:!0}),ep.omit({id:!0}),Wd.omit({id:!0})]);var bH=go.object({selector:kr,inputs:go.record(go.string()).optional()}),zC=go.discriminatedUnion("type",[go.object({type:go.literal("PRESET_ACTION"),action:wa}),go.object({type:go.literal("MODULE"),module:bH})]).describe("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.");async function HC(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Oh()},id:Oh()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Fr(e,n,"module"),l=await hr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Oh(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var RH=pt({schema:{name:"momentic_module_create",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:{name:ho.string(),description:ho.string(),enabled:ho.boolean().default(!0),subDir:ho.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:ho.number().optional().describe("Start index of steps to extract from the current test (0-based)."),endIndex:ho.number().optional().describe("End index of steps to extract from the current test (exclusive). If not provided, extracts just the startIndex.")}},handle:async(r,e,t)=>{let{project:n,logger:o,testPath:i}=r,a=e.startIndex??0,l=e.endIndex??a+1,c=W(n);if(Object.values(c.modules).find(p=>p.name===e.name))throw new Ie(`A module with the name "${e.name}" already exists. Please use a different name.`);let u=[];if(e.startIndex!==void 0){if(!i)throw new Ie("testPath is required when extracting steps from the current test.");let p=await rt(Lh.join(n.rootDir,i),o,c);if(a<0||a>=p.steps.length)throw new Ie(`startIndex ${a} is out of bounds. Test has ${p.steps.length} steps.`);if(l<=a||l>p.steps.length)throw new Ie(`endIndex ${l} is out of bounds. Must be between ${a+1} and ${p.steps.length}.`);u=p.steps.slice(a,l);for(let m of u)if(m.type==="RESOLVED_MODULE")throw new Ie("Modules cannot be nested. Please select steps that do not include module references.")}let d=await Lc({name:e.name,description:e.description,enabled:e.enabled,steps:u,folder:e.subDir?Lh.join(n.rootDir,e.subDir):n.rootDir,project:n});if(c=W(n),e.startIndex!==void 0){let p=await rt(Lh.join(n.rootDir,i),o,c),m={type:"RESOLVED_MODULE",id:vH(),moduleId:d.moduleId,name:e.name,description:e.description,enabled:e.enabled,parameters:[],steps:u,inputs:{}};p.steps.splice(a,l-a,m);let{stepsToSave:g,moduleUpdates:h}=await Fe({stepLists:{steps:p.steps,beforeSteps:p.beforeSteps,afterSteps:p.afterSteps}});h.forEach(f=>{Dt({content:f,schemaVersion:ie,momenticFiles:c,project:n})}),wt({relativeTestPath:i,steps:g,schemaVersion:ie,project:n})}t.addResult(JSON.stringify(d,null,2))}});function AH(r,e,t,n){if(r===void 0&&e!==void 0)throw new Ie("Validation Error: startIndex is required when endIndex is provided.");if(r!==void 0&&e===void 0&&t===0)throw new Ie("Validation Error: steps are required when startIndex is provided without an endIndex.");if(r!==void 0&&(r>n||r<0))throw new Ie(`Validation Error: startIndex is out of bounds for module with ${n} steps.`);if(e!==void 0&&r===void 0)throw new Ie("Validation Error: startIndex is required when endIndex is provided.");if(e!==void 0&&r!==void 0&&e<r)throw new Ie("Validation Error: endIndex must be greater than or equal to startIndex.");if(e!==void 0&&(e>n||e<0))throw new Ie(`Validation Error: endIndex ${e} is out of bounds for module with ${n} steps.`);let o=r??n;if((e??o)===o&&t===0)throw new Ie("Validation Error: Nothing to insert or delete. Provide steps or a valid delete range.")}var wH=pt({schema:{name:"momentic_module_change",description:"Edit a module's steps. 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.",inputSchema:{selector:kr,steps:zC.array(),startIndex:ho.number().optional(),endIndex:ho.number().optional()}},handle:async(r,e,t)=>{let{project:n,logger:o}=r,i=await Promise.all(e.steps.map(h=>HC(h,n,o))),{entity:a,momenticFiles:l}=Fr(n,e.selector,"module"),c=await hr(a,l,o),s=i.find(h=>!ip(h));if(s){t.addError(`Validation Error: step type ${s.type} cannot be added to a module.`);return}try{AH(e.startIndex,e.endIndex,e.steps.length,c.steps.length)}catch(h){t.addError(String(h));return}let u=[...c.steps],d=e.startIndex!==void 0?e.startIndex:u.length,p=e.endIndex!==void 0?e.endIndex:d;u.splice(d,p-d,...i);let{stepsToSave:m}=await Fe({stepLists:{steps:u}});Dt({content:{...c,steps:m.steps},schemaVersion:ie,momenticFiles:l,project:n});let g={...c,steps:u,stepCount:u.length};t.addResult(JSON.stringify(g,null,2))}}),GC=[RH,wH];import{randomUUID as sd}from"crypto";import{z as VC}from"zod";var CH=pt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:{description:VC.string().describe("Description of the element to preview.")}},handle:async({controller:r,logger:e,testContext:t},n,o)=>{o.setIncludeSnapshot();try{let i=await r.locateElement({description:n.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});i.resolution.locator&&await Promise.all([r.browser.scrollIntoViewIfNeeded(i.resolution.locator),r.browser.highlight(i.resolution.locator)]),o.addResult(`Found element matching description: ${i.target.id}`),i.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${i.target.nodeOnlySerializedHtml}`);return}catch(i){o.addError(`Failed to find any element matching description: ${i}`)}}}),xH=pt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:{assertion:VC.string().describe("Assertion to confirm page state.")}},handle:async(r,e,t)=>{t.setIncludeSnapshot();let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:l,orgId:c,testContext:s}=r,u={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:sd()},id:sd()},d=await tl({step:u,controller:i,storage:o,codeEvalTools:a,logger:n,socket:l,orgId:c,testContext:s});if(!d){t.addError("Assertion executed with unknown result.");return}if(d.status==="SUCCESS"){t.addResult(`Assertion is true: ${d.message}`);return}t.addError(`Assertion is false: ${d.message}`)}}),_H=pt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:{command:wa}},handle:async(r,e,t)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:n,storage:o,controller:i,codeEvalTools:a,socket:l,orgId:c,testContext:s}=r;t.setIncludeSnapshot();let u={type:"PRESET_ACTION",command:{...e.command,id:sd()},id:sd()},d=await tl({step:u,controller:i,storage:o,codeEvalTools:a,logger:n,socket:l,orgId:c,testContext:s});if(!d){t.addError("Assertion executed with unknown result.");return}if(d.status==="SUCCESS"){t.addResult(`Assertion is true: ${d.message}`);return}t.addError(`Assertion is false: ${d.message}`)}}),jC=[CH,xH,_H];import IH from"path";import{z as PH}from"zod";var MH=pt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeTestContext()}}),OH=pt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await r.controller.browser.reset({})}}),LH=pt({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:{index:PH.number()}},handle:async(r,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:n,logger:o,testPath:i,storage:a,controller:l,codeEvalTools:c,socket:s,orgId:u,testContext:d}=r,p=W(n),g=(await rt(IH.join(n.rootDir,i),o,p)).steps[e.index];if(!g){t.addError(`Step at index ${e.index} does not exist.`);return}let h=await tl({step:g,controller:l,storage:a,codeEvalTools:c,logger:o,socket:s,orgId:u,testContext:d});if(!h){t.addError(`Step at index ${e.index} executed with unknown result.`);return}if(h.status==="SUCCESS"){t.addResult(`Step at index ${e.index} executed successfully: ${h.message}`),h.data&&t.addResult(`Data: ${JSON.stringify(h.data,null,2)}`);return}t.addError(`Step at index ${e.index} failed: ${h.message}`)}}),$C=[MH,OH,LH];import{randomUUID as Nh}from"crypto";import rl from"path";import{z as rr}from"zod";var NH=rr.object({selector:kr,inputs:rr.record(rr.string()).optional()}),ld=rr.discriminatedUnion("type",[rr.object({type:rr.literal("PRESET_ACTION"),action:wa}),rr.object({type:rr.literal("MODULE"),module:NH})]).describe("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.");async function cd(r,e,t){switch(r.type){case"PRESET_ACTION":return{type:"PRESET_ACTION",command:{...r.action,id:Nh()},id:Nh()};case"MODULE":{let{selector:n,inputs:o}=r.module,{entity:i,momenticFiles:a}=Fr(e,n,"module"),l=await hr(i,a,t),s=Object.keys(o??{}).length>0?o:(l.parameters?.length??0)>0?{}:void 0,u={id:Nh(),inputs:s};return{...l,...u,type:"RESOLVED_MODULE"}}default:return(o=>{throw new Error("You missed a case in the switch above")})(r)}}var DH=pt({schema:{name:"test_get",description:"Get test contents.",inputSchema:{}},handle:async(r,e,t)=>{t.setIncludeTest()}}),kH=pt({schema:{name:"test_insert_step",description:"Insert a step or module into the test.",inputSchema:{index:rr.number(),step:ld}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await rt(rl.join(n.rootDir,i),o,l),s=await cd(e.step,n,o);c.steps.splice(e.index,0,s);let{stepsToSave:u,moduleUpdates:d}=await Fe({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:ie,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:ie,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),FH=pt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:{index:rr.number(),step:ld}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await rt(rl.join(n.rootDir,i),o,l),s=await cd(e.step,n,o);c.steps.splice(e.index,1,s);let{stepsToSave:u,moduleUpdates:d}=await Fe({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:ie,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:ie,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),UH=pt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:{index:rr.number()}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await rt(rl.join(n.rootDir,i),o,l);c.steps.splice(e.index,1);let{stepsToSave:s,moduleUpdates:u}=await Fe({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});u.forEach(d=>{Dt({content:d,schemaVersion:ie,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:s,schemaVersion:ie,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),BH=pt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:{startIndex:rr.number(),deleteCount:rr.number(),steps:ld.array()}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await rt(rl.join(n.rootDir,i),o,l),s=await Promise.all(e.steps.map(p=>cd(p,n,o)));c.steps.splice(e.startIndex,e.deleteCount,...s);let{stepsToSave:u,moduleUpdates:d}=await Fe({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:ie,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:ie,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),zH=pt({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:{commands:ld.array()}},handle:async(r,e,t)=>{t.setIncludeTest();let{project:n,logger:o,testPath:i,socket:a}=r,l=W(n),c=await rt(rl.join(n.rootDir,i),o,l),s=await Promise.all(e.commands.map(p=>cd(p,n,o)));c.steps=s;let{stepsToSave:u,moduleUpdates:d}=await Fe({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(p=>{Dt({content:p,schemaVersion:ie,momenticFiles:l,project:n})}),wt({relativeTestPath:i,steps:u,schemaVersion:ie,project:n}),a?.emit("copilotStepsUpdated",c.steps)}}),WC=[DH,kH,FH,UH,BH,zH];var qC=[...GC,...BC,...$C,...jC,...WC,...od];function ud(r,e,t,n){let o=Qi(),i=At(),a=Jn(),l=se(),c=new Je({apiKey:o,baseUrl:a,logger:t}),s=new mo(c,i),u=new Jr(l.config),d=new Yr({httpClient:new Rt({baseUrl:c.baseUrl,apiKey:c.apiKey,logger:t}),fakerSeed:l.config.advanced?.fakerConstantSeed?Ui:void 0}),p={project:l,apiKey:o,orgId:i,baseUrl:a,logger:t,storage:s,flagStore:u,codeEvalTools:d,testPath:r,testContext:n.context,controller:n.controller,socket:n.socket},m=qC.reduce((f,{name:E,builder:S})=>(f[E]=S(p,new ad(p.controller.browser,p.testContext,p.project,p.logger,p.testPath)),f),{});return{model:FC(o)("claude-opus-4-20250514"),stopWhen:HH(30),maxRetries:4,system:UC,messages:e,tools:m}}var $H=cn({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:zp},handle:async(r,e,t)=>{let{project:n}=r;try{let o=await id({project:n,input:e});t.addResult(JSON.stringify(o,null,2))}catch(o){t.addError(String(o));return}}}),WH=cn({schema:{name:"momentic_test_list",description:"List tests.",inputSchema:{}},handle:async(r,e,t)=>{let{project:n}=r,o=W(n),a=Object.values(o.tests).map(l=>({id:l.id,name:l.name,description:l.description,relativePath:l.relativePath,fullFilePath:l.fullFilePath,platformSep:l.platformSep,fullPathSegments:l.fullPathSegments,relativePathSegments:l.relativePathSegments,fileName:l.fileName,lastModified:l.lastModified,createdAt:l.createdAt,type:l.type,labels:l.labels||[]}));t.addResult(JSON.stringify({tests:a},null,2))}}),qH=cn({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:kr}},handle:async(r,e,t)=>{let{project:n,logger:o}=r;try{let i=Fr(n,e.selector,"test"),a=await rt(i.entity.fullFilePath,o,i.momenticFiles);t.addResult(JSON.stringify({test:a},null,2))}catch(i){t.addError(String(i));return}}});async function KH(r,e,t){let n=Aa.getLatestSession();if(n)return n;let o=Qi(),i=At(),a=Jn(),l=new mi,c=new Je({apiKey:o,baseUrl:a,logger:r}),s=new mo(c,i),u=new Jr(e.config),d=(await rt(t.fullFilePath,r,W(e))).advanced?.viewport??Mt,p=new Kn(e.config.ai?.agentConfig,{baseUrl:a,apiKey:o,logger:r}),m=new Yn({baseUrl:a,apiKey:o,logger:r},p),g=await yr.init({baseUrl:"about:blank",userBrowserSettings:{},enricher:m,storage:s,flagStore:u,logger:r,contextArgs:{viewport:d,locale:Un,timezoneId:Bn,geolocation:zn},iconKnowledgeBase:null,callbacks:{}}),h=new uo({browser:g,generator:p,logger:r,flagStore:u,orgId:i,options:{scratchPadId:void 0,slowMoMs:void 0,autoFollowNewTabs:!0,useMemory:e.config.ai?.useMemory,aiPageFiltering:!0},storage:s,localCodeEvalTools:new Yr({httpClient:new Rt({baseUrl:a,apiKey:o,logger:r}),fakerSeed:e.config.advanced?.fakerConstantSeed?Ui:void 0}),visualDiffScreenshotStorage:l}),f=new qt({baseUrl:"about:blank",testName:VH.basename(t.relativePath),currentUrl:g.url(),variablesFromEnvironment:{},envName:void 0});return{controller:h,context:f,socket:void 0}}var YH=cn({schema:{name:"momentic_test_edit",description:"Edit a test.",inputSchema:{selector:kr,message:jH.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(r,e,t)=>{let{project:n,logger:o}=r,i,a;try{({entity:i,momenticFiles:a}=Fr(n,e.selector,"test"))}catch(p){t.addError(String(p));return}let l=ud(i.relativePath,[{role:"user",content:e.message}],o,await KH(o,n,i)),c=GH({...l}),s=[];for await(let p of c.textStream)s.push(p);let u=await rt(i.fullFilePath,o,a),d=s.join("").split(`
4159
+ `).map(p=>p.trim()).filter(p=>p.length>0);t.addResult(JSON.stringify({editedTest:u,messages:d},null,2))}}),KC=[WH,$H,qH,YH];var YC=[...DC,...KC,...od];function Dh(r,e){let t=new XH({name:e.applicationName,version:e.cliVersion});for(let n of YC)n.addToolToMcpServer(r,t);return t}async function XC(r,e,t,n){let o=new JH(t,e,n);return await r.connect(o),{close:async()=>{try{await r.close()}catch{}},transport:o}}var r1="mcp-session-id",n1="sessionId",dd=t1(),nl=new Map;function JC(){let r={applicationName:"momentic-mcp-desktop-server",cliVersion:xh??"0.0.0"},e=se(),t=Ze.child({orgId:At(),userId:Ji(),...r});return{context:{project:e,logger:t},info:r}}dd.get("/sse",async(r,e)=>{let{context:t,info:n}=JC(),o=Dh(t,n),{transport:i}=await XC(o,e,"/api/mcp/sse",{enableDnsRebindingProtection:!1}),a=i.sessionId,l={transport:i,close:async()=>{nl.delete(a);try{await o.close()}catch(c){t.logger.warn({err:c},"Failed to close MCP server on SSE session cleanup")}}};nl.set(a,l),i.onclose=()=>{let c=nl.get(a);c&&c.close()}});dd.post("/sse",async(r,e)=>{let t=String(r.query[n1]??"");if(!t||!nl.has(t)){e.status(400).send("Invalid or missing sessionId");return}await nl.get(t).transport.handlePostMessage(r,e,r.body)});var QC=dd,Ca=new Map;dd.all("/",async(r,e)=>{let t=String(r.headers[r1]??"");if(t&&Ca.has(t)){await Ca.get(t).handle(r,e,r.body);return}let n=r.method==="GET",o=r.method==="POST"&&ZH(r.body);if(!n&&!o){e.status(400).send("Bad Request: No valid session ID provided");return}let{context:i,info:a}=JC(),l=Dh(i,a),c=new QH({sessionIdGenerator:()=>e1(),enableDnsRebindingProtection:!1,onsessioninitialized:s=>{Ca.set(s,{handle:async(u,d,p)=>{await c.handleRequest(u,d,p)},close:async()=>{Ca.delete(s);try{await c.close()}catch{}try{await l.close()}catch{}}})}});c.onclose=()=>{let s=c.sessionId;s&&Ca.has(s)&&Ca.get(s).close()},await l.connect(c),await c.handleRequest(r,e,r.body)});import{Router as o1}from"express";var pd=o1();pd.get("/",fe((r,e)=>{let t=Lm().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));pd.get("/current",fe((r,e)=>{let t=se();if(!t){e.status(404).json({error:"No project found."});return}let n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));pd.post("/set",fe((r,e)=>{let t;try{t=uy.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Et({configFilePath:t.configFilePath});Oc(n,o=>Et({configFilePath:o}))}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var ZC=pd;import{Router as i1}from"express";var ex=i1();ex.get("/",fe((r,e)=>{let n={ai:se().config.ai};e.status(200).json(n)}));var tx=ex;import{convertToModelMessages as l1,streamText as c1}from"ai";import{Router as u1}from"express";import rx from"fs";import il from"path";import{v4 as d1}from"uuid";import p1 from"yaml";import{randomUUID as a1}from"node:crypto";import{PostHog as s1}from"posthog-node";var md=class r{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new s1("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new r({...this.bindings,...e},this.options)}track(e,t){if(!bS(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:a1(),event:n,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};var ol=new md({platform:"local_app"},{flushAt:1,flushInterval:0});var fo=u1();fo.post("/",fe(async(r,e)=>{let t;try{t=oy.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=se(),o=await id({project:n,input:t});ol.track({type:"test_editor:test_create"}),e.status(201).json(o)}catch(n){if(n instanceof Ie){e.status(400).json({error:n.message});return}throw n}}));fo.get("/:testPath",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=se(),o=W(n),i;try{i=await rt(il.join(n.rootDir,t),Ze,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:l}=await Fe({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});l.forEach(c=>{Dt({content:c,schemaVersion:ie,momenticFiles:o,project:n})}),wt({relativeTestPath:t,steps:a,schemaVersion:ie,project:n})}catch(a){Ze.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));fo.patch("/:testPath/metadata",fe(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=ny.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Cm(r.params.testPath,t,se()).newRelativeTestPath};e.status(200).json(o)}));fo.patch("/:testPath",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=ry.parse(r.body)}catch(m){Ze.warn({err:m},"Invalid save request"),e.status(400).json({error:`Invalid request body: ${m}`});return}Ze.info({testPath:t},"Save received");let o=se(),i=W(o),a;try{a=Dc(t,o)}catch(m){e.status(400).json({error:`Existing test file on disk is invalid: ${m}`});return}let{stepsToSave:l,moduleUpdates:c,cachesToSave:s}=await Fe({stepLists:n.stepLists,cacheCreationParams:{testId:a.id,orgId:At()}}),u=new Je({apiKey:Qi(),baseUrl:Jn(),logger:Ze}),d=await Qn(Ze,u,o);await Yi({orgId:At(),client:u,gitMetadata:d}).saveStepCacheEntries({logger:Ze,testId:a.id,entries:s}),c.forEach(m=>{Dt({content:m,schemaVersion:n.schemaVersion,momenticFiles:i,project:o})}),wt({relativeTestPath:t,steps:l,schemaVersion:n.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));fo.patch("/:testPath/environments",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=cy.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Cm(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},se()),e.status(201).json({message:"ok"})}));fo.post("/:testPath/duplicate",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=iy.parse(r.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Hn(n.name)}catch(f){e.status(400).json({error:f.message});return}let o=se(),i=il.join(o.rootDir,t);if(!rx.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=W(o),l;try{l=await rt(i,Ze,a)}catch(f){e.status(400).send({error:f.message});return}let c=d1(),s=pr.parse({...l,name:n.name,id:c}),{stepsToSave:u}=await Fe({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:At()}}),d=Tn({fileType:Se.TEST,...s,beforeSteps:u.beforeSteps??void 0,steps:u.steps,afterSteps:u.afterSteps??void 0}),p=il.dirname(i),m=il.join(p,`${n.name}.${St.TEST}`),g=p1.stringify(d);rx.writeFileSync(m,g,"utf-8");let h={relativeFilePath:il.relative(o.rootDir,m)};ol.track({type:"test_editor:test_create"}),e.status(201).json(h)}));fo.post("/:testPath/chat",fe(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let{messages:n}=r.body;if(!n){e.status(400).json({error:"Missing messages in request body."});return}let o=l1(n),i=Aa.getLatestSession();if(!i){e.status(400).json({error:"No active browser session. Start a session first."});return}let a=ud(t,o,Ze,i);c1(a).pipeUIMessageStreamToResponse(e,{onError:c=>c instanceof Error?c.message:String(c)})}));var nx=fo;async function sx(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,staticDir:o,devicePixelRatio:i,alwaysSaveCache:a,noCache:l,initialProject:c}=r;e&&PT(e),await MT(t);let s=At(),u=Ji();ol.identify({user_id:u,org_id:s});let d=r.logger??Ze;d=d.child({orgId:s,userId:u}),d.debug({params:r},"Desktop server init and api key check done");let p=E1(o,n,d),m=`http://localhost:${n}`;T.info(`Desktop server is running at ${m}`),Oc(c,A=>Et({configFilePath:A})),await new Promise(A=>{try{p.listen(n,()=>{d.info(`Desktop server is running at ${m}`),A()})}catch(R){R.message.includes("EADDRINUSE")?lx(n):T.error(`An unexpected error occurred while starting the server: ${R.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:Jn(),apiKey:t,logger:d},f=async()=>{let A=se();return new Kn(A.config.ai?.agentConfig,h)},E=async()=>new Yn(h,await f()),S=new Je(h),y=new mi;_C({baseServer:p,getOrgId:async()=>At(),generatorFactory:f,enricherFactory:E,cacheStorageFactory:async A=>{let R=se(),w=await Qn(d,S,R);return Yi({orgId:A,client:S,gitMetadata:w,alwaysSaveCache:a,noCache:l})},branchGetter:async()=>{try{return(await km(d))?.gitBranchName}catch(A){d.error({err:A},"Failed to get environment git metadata");return}},flagStoreFactory:async A=>{let R=se();return new Jr(R.config)},settingsFactory:async()=>{let A=se();return{ai:{},browser:{},...A.config}},storageFactory:async A=>new mo(S,A),logger:d,devicePixelRatio:i,authorization:h,visualDiffScreenshotStorage:y,globalE2eStateManager:Aa})}var ax="25mb";function E1(r,e,t){let n=ix();n.use(m1()),n.use(ox.json({limit:ax})),n.use(ox.urlencoded({extended:!1,limit:ax}));let o=f1();if(o.use("/tests",nx),o.use("/modules",IC),o.use("/environments",OC),o.use("/projects",ZC),o.use("/folders",wm),o.use("/settings",tx),o.use("/identify",NC),o.use("/entities",MC),o.use("/mcp",QC),n.use("/api",o),n.use((a,l,c)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&t.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"),l.on("close",()=>{l.statusCode>=400&&t.error({url:a.url,method:a.method,statusCode:l.statusCode},"Request completed in error")}),c()}),n.use((a,l,c,s)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}t.error({stack:a.stack,msg:a.message,err:a,url:l.url,method:l.method},"Unhandled exception leading to 500 on desktop-server"),T.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
4160
+ ${a.stack}`),c.status(500).send(`Internal Server Error: ${a.message}`)}),r){let a=ix.static(r,{setHeaders:l=>{l.setHeader("Cache-Control","no-cache")},redirect:!1});n.use(a),n.use("*",(l,c)=>{c.sendFile(y1.join(r,"index.html"))})}let i=S1.createServer(n);return i.once("error",a=>{"code"in a&&a.code==="EADDRINUSE"?(lx(e),process.exit(1)):console.error("An unexpected server error occurred:",a.message)}),i}h1.setMaxListeners(50);process.on("warning",r=>{Ze.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Ze.error({err:r},"Uncaught exception on desktop-server"),T.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",(r,e)=>{Ze.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on desktop-server (promise rejection)"),T.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function lx(r){T.error(g1`Port ${r} is already in use by another process. Please close the other process and try again.
4121
4161
  Using Bash on MacOS or Linux:
4122
4162
  lsof -t -i :58888 | xargs kill -9
4123
4163
 
4124
4164
  Using Command Prompt on Windows:
4125
4165
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
4126
- `)}import cG from"events";import Id from"fs";import uG from"open";import{cpus as Xx}from"os";import _d from"path";import{fileURLToPath as dG}from"url";import i1 from"diff-lines";import{gt as a1}from"semver";async function YC({test:r,fragment:e,entities:t,client:n,logger:o,yes:i}){a1(e.schemaVersion,oe)&&(E.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),LE(e.steps).forEach(g=>{t.modules[g]||(E.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await Nt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let l=r.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<l&&!i&&!await Nt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let c=Yo(r.fullFilePath,o,t),s=c.steps;if(!Array.isArray(s))throw new Error(`Test ${r.fullFilePath} is missing steps array`);let u,d;if(e.schemaVersion!==oe){let{steps:g,newVersion:h}=await ms({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:E});u=h,d=Ze.array().parse(g)}else d=Ze.array().parse(e.steps);let{stepsToSave:p}=await ke({stepLists:{steps:d}});p.beforeSteps=c.beforeSteps??void 0,p.afterSteps=c.afterSteps??void 0;let m=i1(JSON.stringify(s,void 0,2),JSON.stringify(p,void 0,2),{n_surrounding:5});E.dimmed("=".repeat(30)),E.dimmed(m),E.dimmed("=".repeat(30)),E.dimmed(""),u&&E.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${u}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await Nt("Do you want to apply this patch?")&&(E.dimmed("Cancelled."),process.exit(1)),wt({relativeTestPath:r.relativePath,steps:p,schemaVersion:u??e.schemaVersion,project:t.project}),E.success("Patch applied successfully."),await n.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as nr}from"crypto";import{z as XC}from"zod";function nl(r){return XC.string().uuid().safeParse(r).success}async function dd({fix:r,project:e}){let t=W(e),n=Object.values(t.tests),o={},i={},a=new Set,l={},c=new Set,s=0;for(let d of n)try{let p=Yo(d.fullFilePath,Q,t),m=!1,g=!1;nl(d.id)||(E.error(`Test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,g=!0,r&&(d.id=nr(),m=!0)),t.duplicateEntities[d.id]&&(E.error(`Test '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,g=!0,r&&(d.id=nr(),m=!0));let h=p.steps;if(!h||h.length===0||!Array.isArray(h)){E.debug(`Test ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f=Ot.parse(p),y=await jo(f,h,E);y.steps=y.steps.map((S,T)=>{S.id||(E.error(`Step ${T} in test '${d.name}' (${d.relativePath}) does not have an ID`),g=!0,r&&(m=!0,S.id=nr())),nl(S.id)||(E.error(`Step ${T} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${S.id}'`),s++,g=!0,r&&(m=!0,S.id=nr()));let A=o[S.id]?.testId,R=o[S.id]?.testRelativePath;if(A?(s++,g=!0,A===d.id?E.error(`Multiple steps in the test '${d.name}' (${d.relativePath}) have the same ID '${S.id}'`):E.error(`Step ${T} in test '${d.name}' (${d.relativePath}) has the ID ${S.id} which is duplicated in ${R}`),r&&(m=!0,S.id=nr())):o[S.id]={testId:d.id,testRelativePath:d.relativePath},S.type==="PRESET_ACTION"){let w=S.command.id;nl(w)||(E.error(`Command ${T} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${w}'`),s++,g=!0,r&&(m=!0,S.command.id=nr()));let x=i[w]?.testId,_=i[w]?.testRelativePath;x?(s++,g=!0,x===d.id?E.error(`Multiple commands in the test '${d.name}' (${d.relativePath}) have the same ID '${w}'`):E.error(`Command ${T} in test '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in test ${_}`),r&&(m=!0,S.command.id=nr())):i[w]={testId:d.id,testRelativePath:d.relativePath}}return Oe.parse(S)}),g&&E.dimmed("=".repeat(80)),m&&r&&(wt({relativeTestPath:d.relativePath,steps:{beforeSteps:p.beforeSteps,steps:y.steps,afterSteps:p.afterSteps},schemaVersion:oe,project:e}),a.add(d.fullFilePath))}catch(p){E.error({err:p},`Failed to parse test ${d.name} (${d.relativePath})`);continue}let u=Object.values(t.modules);for(let d of u)try{let p=!1,m=!1;nl(d.id)||(E.error(`Module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,m=!0,r&&(d.id=nr(),p=!0)),t.duplicateEntities[d.id]&&(E.error(`Module '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,m=!0,r&&(d.id=nr(),p=!0));let g=vn(d.fullFilePath,E),h=g.steps;if(!h||h.length===0||!Array.isArray(h)){E.debug(`Module ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f,y;try{let T=await jo({id:g.moduleId,schemaVersion:g.schemaVersion},g.steps,E);f=T.steps,y=T.newVersion}catch(T){E.error({err:T},`Failed to migrate module ${d.name} (${d.relativePath})`);continue}let S=f.map((T,A)=>{if(XC.string().uuid().safeParse(T.id)||(E.error(`Step ${A} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${T.id}'`),s++,m=!0,r&&(p=!0,T.id=nr())),o[T.id]?.testId){let w=o[T.id]?.testRelativePath;s++,m=!0,E.error(`Step ${A} in module '${d.name}' (${d.relativePath}) has the ID ${T.id} which is duplicated in test ${w}`),r&&(p=!0,T.id=nr())}if(T.type==="PRESET_ACTION"){let w=T.command.id;nl(w)||(E.error(`Command ${A} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${w}'`),s++,m=!0,r&&(p=!0,T.command.id=nr()));let x=i[w],_=l[w];x||_?(s++,m=!0,_?.moduleId===d.id?E.error(`Multiple commands in module '${d.name}' (${d.relativePath}) have the same ID '${w}'`):x?E.error(`Command in module '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in test ${x.testRelativePath}`):E.error(`Command ${A} in module '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in module ${_.moduleRelativePath}`),r&&(p=!0,T.command.id=nr())):l[w]={moduleId:d.id,moduleRelativePath:d.relativePath}}return Oe.parse(T)});m&&E.dimmed("=".repeat(80)),p&&r&&(Dt({content:{...g,steps:S},schemaVersion:y,momenticFiles:t,project:e,forceSaveOnNoDiffs:!0}),c.add(d.fullFilePath))}catch(p){E.error({err:p},`Failed to parse module ${d.name} (${d.relativePath})`);continue}return{errors:s,modifiedTestFilePaths:a,modifiedModuleFilePaths:c}}async function JC({fix:r,project:e}){let{errors:t,modifiedTestFilePaths:n,modifiedModuleFilePaths:o}=await dd({fix:r,project:e});t>0?(E.error(`Found errors in ${t} steps`),r?(E.warn(`Modified the following test files:
4127
- ${[...n].map(i=>`${it}- ${i}`).join(`
4128
- `)}`),o.size>0&&E.warn(`Modified the following module files:
4129
- ${[...o].map(i=>`${it}- ${i}`).join(`
4130
- `)}`)):E.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(E.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function QC({project:r}){let e=W(r),t=Object.values(e.tests),n=await Mc(e,Q),o={},i={},a=new Set,l=new Set;for(let s of t)o[s.name]?i[s.name]?i[s.name].push(s.fullFilePath):i[s.name]=[o[s.name],s.fullFilePath]:o[s.name]=s.fullFilePath;for(let s of n)l.has(s.name)&&a.add(s.name),l.add(s.name);if(Object.entries(i).length>0||a.size>0){for(let[s,u]of Object.entries(i))for(let d of u)E.error(`Test Name ${s} is duplicated in ${d}`);for(let s of a)E.error(`Module name ${s} is duplicated in your project`);process.exit(1)}E.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as s1}from"lodash-es";async function ZC({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=s1(t.config);o.environments||(o.environments=[]);for(let i of n){let a=o.environments?.find(l=>l.name===i.name);if(a)!e&&!await Nt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[ft],delete i.variables[ft],a.envVariables=i.variables;else{let l=i.variables[ft];delete i.variables[ft],o.environments.push({name:i.name,baseUrl:l,envVariables:i.variables})}}ta(o,t.configFilePath),E.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as ex}from"crypto";import tx from"fs";async function Lh({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:r,all:t}),a=0;for(let[c,s]of Object.entries(o)){let u=rx(c,he.TEST);!n&&!await tm(u)||(a+=1,tx.writeFileSync(u,s,"utf-8"),Q.info({checksum:ex("md5").update(s).digest("hex")},`Wrote '${u}'`))}let l=0;for(let[c,s]of Object.entries(i)){let u=rx(c,he.MODULE);!n&&!await tm(u)||(l+=1,tx.writeFileSync(u,s,"utf-8"),Q.info({checksum:ex("md5").update(s).digest("hex")},`Wrote '${u}'`))}a===0?E.success("Pulled 0 tests."):E.success(`Pulled ${a} test${a>1?"s":""}${l?` and ${l} module${l>1?"s":""}`:""}!`)}function rx(r,e){switch(e){case he.TEST:return`${xe(r)}.${yt.TEST}`;case he.MODULE:return`${xe(r)}.${yt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function nx(r){let{project:e,client:t,skipPrompts:n}=r;E.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),E.info("Importing environments from Momentic Cloud."),E.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await Nt("Are you sure you want to proceed?",!0)||(E.info("Aborting..."),process.exit(1)),await ZC({client:t,project:e,skipPrompts:n}),E.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.`),E.info("Importing tests and modules from Momentic Cloud."),await Lh({testsToFetch:[],client:t,all:!0,yes:n}),E.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 ox(r){let{client:e,skipPrompts:t,paths:n}=r;await Lh({testsToFetch:n,client:e,all:void 0,yes:t}),E.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 hi,InvalidArgumentError as ol,Option as Me}from"@commander-js/extra-typings";import{validateHeaderValue as l1}from"http";import{z as ix}from"zod";var pd=58888;function yo(r){let e=parseInt(r,10);if(isNaN(e))throw new ol("Not a number.");return e}function md(r){if(r===void 0)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,n),i=t.slice(n+1);l1(o,i),e[o]=i}return e}var Ur=new Me("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new ol("API key is required.");return r}).makeOptionMandatory(),Br=new Me("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return ix.string().url().parse(r),r}catch{throw new ol("Not a valid URL.")}}),Eo=new Me("-y, --yes","Skip all confirmation prompts.").env("CI"),Nh=new Me("-w, --wait","Wait for tests to finish running before exiting."),Dh=new Me("--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(yo),gd=new Me("--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."),ax=new Me("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(Nl)),sx=new Me("--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"),kh=new Me("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),lx=new Me("--upload-results","Upload test results to Momentic Cloud.").default(!1),Fh=new Me("--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."),Uh=new Me("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Bh=new Me("--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(yo),zh=new Me("--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."),hd=new Me("--env <env>","Name of the environment to use when running tests."),fd=new Me("--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(r=>{try{return ix.string().url().parse(r),r}catch{throw new ol("Not a valid URL.")}}),cx=new Me("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=yo(r);if(e<1)throw new ol("Shard index must be greater than 0.");return e}),ux=new Me("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(yo),or=new Me("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Aa=new Me("-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."),dx=new Me("--fix","Attempt to fix any issues found."),Hh=new Me("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),Gh=new Me("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),px=new Me("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),mx=new Me("--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}),gx=new Me("--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}),hx=new hi("<tests...>","One or more test paths to queue on Momentic Cloud."),fx=new hi("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),Vh=new hi("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),Sx=new hi("<suites...>","One or more suite paths that exist on Momentic Cloud."),yx=new hi("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),Ex=new hi("<results>","Path to the results archive.").argRequired(),jh=new Me("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),$h=new hi("<test>","Name of the test to quarantine.").argOptional();async function Tx(r){let e=W(r),t=Object.values(e.tests);for(let n of t)try{let o=Yo(n.fullFilePath,E,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){E.debug(`Test ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=Ot.parse(o),l=await jo(a,i,E);E.dimmed(`Updating ${n.relativePath}`),wt({relativeTestPath:n.relativePath,steps:{beforeSteps:o.beforeSteps,steps:l.steps,afterSteps:o.afterSteps},schemaVersion:oe,project:r,forceSaveOnNoDiffs:!0})}catch(o){E.error({err:o},`Failed to read or migrate test ${n.name} (${n.relativePath}), continuing...`)}for(let n of Object.values(e.modules)){E.dimmed(`Updating ${n.relativePath}`);try{let o=vn(n.fullFilePath,E),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){E.debug(`Module ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=await jo({id:o.moduleId,schemaVersion:o.schemaVersion},i,E);Dt({content:{...o,steps:a.steps},schemaVersion:oe,momenticFiles:e,project:r,forceSaveOnNoDiffs:!0})}catch(o){E.error({err:o},`Failed to read or migrate module ${n.name} (${n.relativePath}), continuing...`)}}}import{spawnSync as d1}from"child_process";import{PostHog as u1}from"posthog-node";async function bx(r,e){let t,n=0,o=3,i,a;for(;n<o;)try{let l=await H(r.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){t=l,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw t}var Sd=class r extends es{constructor(t,n,o,i){super(o,i);this.client=t;this.orgId=n}static async init(t){let n=new u1("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await bx(n,t);return new r(n,t,o,i)}async refresh(){let{flags:t,payloads:n}=await bx(this.client,this.orgId);this.flags=t,this.payloads=n}};function p1(){try{let e=d1("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();E.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(r){let e=r instanceof Error?r.message:String(r);E.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
4131
- ${e}`)}}async function vx({project:r,orgId:e,apiClient:t}){E.info("Pulling browser and AI configuration options from Cloud");let n=await Sd.init(e);r.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"),...r.config.browser},r.config.advanced={fakerConstantSeed:n.isBooleanFlagEnabled("faker_constant_seed"),...r.config.advanced},r.config.ai={aiPageFiltering:n.isBooleanFlagEnabled("rag_v2"),agentConfig:await t.getAgentConfig(),...r.config.ai},E.info(`Updated ${r.configFilePath} to include V2 browser and AI configuration options`),E.info("Determining main Git branch"),r.config.gitMainBranch=p1(),ta(r.config,r.configFilePath),E.success("Migration complete!")}import{input as m1,search as g1}from"@inquirer/prompts";import h1 from"fuse.js";async function yd({prompt:r,inputtedTest:e,testOptions:t}){if(e){let a=t.find(l=>l.name===e);if(!a)E.error(`${e} is not a valid test option.`);else return{name:a.name,id:a.value}}let n=new h1(t,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await g1({message:r,source:async a=>!a||a.length===0?t:n.search({name:a}).map(c=>c.item)}),i=t.find(a=>a.value===o);return{name:i.name,id:i.value}}async function Ed({prompt:r,inputtedReason:e}){return e||m1({message:r})}async function Rx({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=W(n).tests,l=Object.values(a).map(u=>({value:u.id,name:u.name})),c=await yd({prompt:"Select a test to quarantine.",inputtedTest:r,testOptions:l}),s=await Ed({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await t.quarantineTest(c,s,i),E.success(`Test ${c.name} has been successfully quarantined. Navigate to ${t.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${c.name}'.`)}async function Ax({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=W(n).tests,l=Object.values(a).map(m=>({value:m.id,name:m.name})),c=(await t.getQuarantinedTests()).quarantined,s=new Set(c.map(m=>m.testId)),u=l.filter(m=>s.has(m.value)),d=await yd({prompt:"Select a test to unquarantine.",inputtedTest:r,testOptions:u}),p=await Ed({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p,i),E.success(`Test ${d.name} has been successfully removed from quarantine.`)}function wx(r){return r?xe(r):"Unknown suite"}async function Cx({client:r,orgId:e,suitePaths:t,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:l}=await r.queueSuiteRuns({paths:t,...i});Q.info({orgId:e,suiteRunIds:a,runGroupIds:l,suitePaths:t},"Queued suites remotely"),E.dimmed(`Queued ${t.length} suites.`),n||process.exit(0);let c=Date.now();E.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of l)E.dimmed(`${it}- ${r.getAppUrl()}/run-groups/${f}`);let s=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(S=>S.status==="FAILED"&&(S.failureReason||S.finishedAt&&Date.now()-S.finishedAt.getTime()>30*1e3)||S.status==="PASSED"||S.status==="CANCELLED"),p=await nc({name:"suites",getResults:async()=>{let f=l.filter(T=>!u.some(A=>A.id===T)),y=await r.bulkGetRunGroupStatus(f),S=[];for(let T of y)d(T)?u.push(T):S.push(T);return[...u,...S]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(y=>{y.status==="RUNNING"&&(s.has(y.id)||(s.add(y.id),E.log(`${s.size}/${l.length} ${wx(y.suite?.name)}`)))}),f.every(d))}),m=r.getAppUrl(),h=Gi({results:p,startTime:c,onFailed:f=>{let y=wx(f.suite?.name),S=f.runs.filter(A=>A.status==="FAILED").length,T=f.runs.length;E.error(`${y} (${S}/${T} tests failed):`);for(let A of f.runs)if(A.status==="FAILED"){let R=A.testName||A.test?.name;E.error(` ${R?xe(R):"Unknown test"} (${m}/runs/${A.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?xe(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function xx({tests:r,client:e,orgId:t,...n}){!n.yes&&!await Nt(`This command will queue ${r.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:r,...n});if(Q.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),E.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;E.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,l=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",s=e.getAppUrl(),u=Date.now(),d=await nc({name:"runs",getResults:async()=>{let m=i.filter(f=>!l.some(y=>y.id===f)),g=await e.bulkGetRunStatus(m),h=[];for(let f of g)c(f)?l.push(f):h.push(f);return[...l,...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&&E.log(`${a.size}/${o.length} ${xe(h)}`)}}),m.every(c))}),p=Gi({results:d,startTime:u,onFailed:m=>{let g=m.testName||m.test?.name;oc(m,g?xe(g):"Unknown test")},getDisplayLine:m=>{let g=m.testName||m.test?.name,h=` ${g?xe(g):"Unknown test"}`;return m.id&&(h+=` (${s}/runs/${m.id})`),h},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as tG}from"crypto";import rG from"fs";import{existsSync as I1,mkdirSync as P1,statSync as M1}from"fs";import{randomUUID as _x}from"crypto";import Wh from"fs";import{hostname as f1}from"os";import qh from"path";async function Td(r,e,t,n){if(n){let o=await e.getScreenshot(r,n);if(o){let i=`${n}-screenshot.jpeg`,a=qh.join(t,i);return Wh.writeFileSync(a,o),i}}}async function S1(r,e,t,n){let o=n.runId??_x(),i={uuid:o,historyId:o,testCaseId:n.test.id,fullName:n.test.name,name:xe(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:t.suiteName},{name:"host",value:f1()},{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[l,c]of Object.entries(n.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});n.results&&await y1(r,e,t.folder,i.steps,n.results);let a=`${o}-result.json`;Wh.writeFileSync(qh.join(t.folder,a),JSON.stringify(i,void 0,2))}async function wa(r,e,t,n){let o={name:Jn(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 Td(r,e,t,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await Td(r,e,t,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){let l=`${_x()}-attachment.json`,c=qh.join(t,l);Wh.writeFileSync(c,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:l,type:"text/plain"})}return o}async function y1(r,e,t,n,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{n.push(await wa(r,e,t,i));break}case"CONDITIONAL":{let a=await wa(r,e,t,i);a.steps=[],i.assertionResult&&a.steps.push(await wa(r,e,t,i.assertionResult)),a.steps.push(...await Promise.all(i.results.map(l=>wa(r,e,t,l)))),n.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await wa(r,e,t,i);if(a.steps=await Promise.all(i.results.map(l=>wa(r,e,t,l))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[l,c]of Object.entries(i.inputs))a.parameters.push({name:l,value:c})}n.push(a)}}}async function Ix(r,e,t,n){for(let o of n.runs)await S1(r,e,{folder:t,suiteName:n.suiteName},o)}import E1 from"junit-report-builder";import bd from"path";function T1(r,e){if(e.name(r.test.name).className(r.test.name).file(bd.relative(".",r.filePath)).property("id",r.test.id).property("dd_tags[id]",r.test.id),r.test.labels&&(e.property("labels",r.test.labels.join(",")),r.test.labels.forEach(t=>{e.property("dd_tags[label]",t)})),r.baseUrl&&(e.property("base_url",r.baseUrl),e.property("dd_tags[base_url]",r.baseUrl)),r.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${r.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${r.runId}`)),r.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),r.quarantinedReason&&(e.property("quarantined_reason",r.quarantinedReason),e.property("dd_tags[quarantined_reason]",r.quarantinedReason))),r.beforeResults?.some(t=>t.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),r.results?.some(t=>t.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),r.afterResults?.some(t=>t.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),r.status==="FAILED"){if(r.failureReason){let t=Rl[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Pi[r.failureReason];r.runId&&(n+=` Visit https://app.momentic.ai/runs/${r.runId} for more details.`),e.failure(n,t)}r.failureDetails?.errorStack&&e.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&e.skipped();return e.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("started_at",r.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",r.lastAttemptStartedAt.toISOString()).property("finished_at",r.finishedAt.toISOString()).property("dd_tags[finished_at]",r.finishedAt.toISOString()),e.property("attempts",r.attempts.toString()).property("dd_tags[attempts]",r.attempts.toString()),r.parameters.envName&&(e.property("environment",r.parameters.envName),e.property("dd_tags[environment]",r.parameters.envName)),r.parameters.urlOverride&&e.property("url_override",r.parameters.urlOverride),e}function b1(r,{suiteId:e,suiteName:t,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestReasons:c}){let s=r.testSuite().name(t);e&&s.property("id",e),s.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=s.testCase();T1(u,d)}for(let u of a){let d=s.testCase();d.name(u.name).className(u.name).file(bd.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 l){let d=s.testCase();d.name(u.name).className(u.name).file(bd.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 s}function Px(r,e){let t=E1.newBuilder();b1(t,e),t.writeTo(bd.join(r,`${e.suiteName}.xml`))}import v1 from"fs";import R1 from"path";function Mx(r){return{title:Jn(r),duration:r.finishedAt.getTime()-r.startedAt.getTime(),error:r.status==="FAILED"?{value:r.failureReason}:void 0,steps:r.results&&r.type!=="PRESET_ACTION"?r.results.map(Mx):[]}}async function A1(r,e,t,n){if(n.results?.length){let o=await Td(r,e,t,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function w1(r,e,t,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||Pi[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map(Mx)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await A1(r,e,t,n)}}async function C1(r,e,t,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await w1(r,e,t,n)]}}async function x1(r,e,t,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await C1(r,e,t,n)],id:n.runId,file:n.filePath}}function Kh(r,e){return r.reduce((t,n)=>e(n)?t+1:t,0)}async function _1(r,e,t,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(o=>x1(r,e,t,o)))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:Kh(n.runs,o=>o.status==="PASSED"),unexpected:Kh(n.runs,o=>o.status!=="PASSED"),flaky:Kh(n.runs,o=>!!o.isFlake),skipped:0}}}async function Ox(r,e,t,n){let o=await _1(r,e,t,n);v1.writeFileSync(R1.join(t,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function Lx(r,e,t,n,o){switch(I1(o)?M1(o).isDirectory()||(E.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)):(E.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),P1(o,{recursive:!0})),t){case"junit":Px(o,n);return;case"allure":case"allure-json":await Ix(r,e,o,n);return;case"playwright-json":await Ox(r,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import nG from"wait-on";import{execSync as O1}from"child_process";import{platform as L1}from"os";function Yh(){return Nx()?(E.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),E.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.
4132
- `),2):(E.dimmed("Setting device pixel ratio to 1."),E.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.
4133
- l.`),1)}function Nx(){return L1()==="darwin"&&O1("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Xh(r){Nx()&&r===1&&(E.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),E.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import N1 from"@actions/exec";import D1 from"@actions/io";import k1 from"quote";import F1 from"string-argv";async function Dx(r,e=!0){let t=F1(r),n=await D1.which(t[0],!0),o=t.slice(1),i=N1.exec(k1(n),o,{delay:100});if(e)return i}import U1 from"csv-parser";import{createReadStream as B1}from"fs";function Jh(r){return new Promise((e,t)=>{let n=[];B1(r).pipe(U1()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import vd from"semver";import{z as Rd}from"zod";var Pn="2.17.5",z1="https://registry.npmjs.org/momentic",H1=Rd.object({versions:Rd.record(Rd.string(),Rd.unknown()).optional()});async function kx(r){try{await G1(r)}catch(e){E.warn({err:e},"Failed to check CLI version against NPM servers")}}async function G1(r){if(!Pn){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await H(fetch(z1),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=H1.parse(i).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))vd.valid(n)&&(!t||vd.gt(n,t))&&vd.gt(n,Pn)&&vd.lt(n,"2.0.0")&&!n.includes("alpha")&&(t=n);t&&(E.warn(`Update available: v${Pn} -> v${t}`),E.warn("This version may be missing critical fixes, features, and security updates."),E.warn(`Run "npx momentic@${t} -V" to update`))}import Qh from"fs";import{compact as V1,partition as Ad}from"lodash-es";import Zh from"path";import{cwd as j1}from"process";import $1 from"semver";async function wd({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,labels:a,logger:l}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>Qh.existsSync(p)),d=j1();u?(d!==t.rootDir&&l.warn(`The current working directory ('${d}') is different from the project root directory ('${t.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.`),l.info(`Reading tests from the following local file paths:
4134
- ${r.map(p=>`${it}- ${p}`).join(`
4166
+ `)}import AG from"events";import Od from"fs";import wG from"open";import{cpus as u_}from"os";import Md from"path";import{fileURLToPath as CG}from"url";import T1 from"diff-lines";import{gt as b1}from"semver";async function cx({test:r,fragment:e,entities:t,client:n,logger:o,yes:i}){b1(e.schemaVersion,ie)&&(T.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),FE(e.steps).forEach(g=>{t.modules[g]||(T.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await Nt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let l=r.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<l&&!i&&!await Nt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let c=Yo(r.fullFilePath,o,t),s=c.steps;if(!Array.isArray(s))throw new Error(`Test ${r.fullFilePath} is missing steps array`);let u,d;if(e.schemaVersion!==ie){let{steps:g,newVersion:h}=await fs({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:T});u=h,d=et.array().parse(g)}else d=et.array().parse(e.steps);let{stepsToSave:p}=await Fe({stepLists:{steps:d}});p.beforeSteps=c.beforeSteps??void 0,p.afterSteps=c.afterSteps??void 0;let m=T1(JSON.stringify(s,void 0,2),JSON.stringify(p,void 0,2),{n_surrounding:5});T.dimmed("=".repeat(30)),T.dimmed(m),T.dimmed("=".repeat(30)),T.dimmed(""),u&&T.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${u}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await Nt("Do you want to apply this patch?")&&(T.dimmed("Cancelled."),process.exit(1)),wt({relativeTestPath:r.relativePath,steps:p,schemaVersion:u??e.schemaVersion,project:t.project}),T.success("Patch applied successfully."),await n.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as nr}from"crypto";import{z as ux}from"zod";function al(r){return ux.string().uuid().safeParse(r).success}async function gd({fix:r,project:e}){let t=W(e),n=Object.values(t.tests),o={},i={},a=new Set,l={},c=new Set,s=0;for(let d of n)try{let p=Yo(d.fullFilePath,Q,t),m=!1,g=!1;al(d.id)||(T.error(`Test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,g=!0,r&&(d.id=nr(),m=!0)),t.duplicateEntities[d.id]&&(T.error(`Test '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,g=!0,r&&(d.id=nr(),m=!0));let h=p.steps;if(!h||h.length===0||!Array.isArray(h)){T.debug(`Test ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f=Ot.parse(p),E=await jo(f,h,T);E.steps=E.steps.map((S,y)=>{S.id||(T.error(`Step ${y} in test '${d.name}' (${d.relativePath}) does not have an ID`),g=!0,r&&(m=!0,S.id=nr())),al(S.id)||(T.error(`Step ${y} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${S.id}'`),s++,g=!0,r&&(m=!0,S.id=nr()));let A=o[S.id]?.testId,R=o[S.id]?.testRelativePath;if(A?(s++,g=!0,A===d.id?T.error(`Multiple steps in the test '${d.name}' (${d.relativePath}) have the same ID '${S.id}'`):T.error(`Step ${y} in test '${d.name}' (${d.relativePath}) has the ID ${S.id} which is duplicated in ${R}`),r&&(m=!0,S.id=nr())):o[S.id]={testId:d.id,testRelativePath:d.relativePath},S.type==="PRESET_ACTION"){let w=S.command.id;al(w)||(T.error(`Command ${y} in test '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${w}'`),s++,g=!0,r&&(m=!0,S.command.id=nr()));let x=i[w]?.testId,_=i[w]?.testRelativePath;x?(s++,g=!0,x===d.id?T.error(`Multiple commands in the test '${d.name}' (${d.relativePath}) have the same ID '${w}'`):T.error(`Command ${y} in test '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in test ${_}`),r&&(m=!0,S.command.id=nr())):i[w]={testId:d.id,testRelativePath:d.relativePath}}return Le.parse(S)}),g&&T.dimmed("=".repeat(80)),m&&r&&(wt({relativeTestPath:d.relativePath,steps:{beforeSteps:p.beforeSteps,steps:E.steps,afterSteps:p.afterSteps},schemaVersion:ie,project:e}),a.add(d.fullFilePath))}catch(p){T.error({err:p},`Failed to parse test ${d.name} (${d.relativePath})`);continue}let u=Object.values(t.modules);for(let d of u)try{let p=!1,m=!1;al(d.id)||(T.error(`Module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${d.id}'`),s++,m=!0,r&&(d.id=nr(),p=!0)),t.duplicateEntities[d.id]&&(T.error(`Module '${d.name}' (${d.relativePath}) has a duplicate ID: '${d.id}'`),s++,m=!0,r&&(d.id=nr(),p=!0));let g=bn(d.fullFilePath,T),h=g.steps;if(!h||h.length===0||!Array.isArray(h)){T.debug(`Module ${d.name} (${d.relativePath}) has no steps, skipping...`);continue}let f,E;try{let y=await jo({id:g.moduleId,schemaVersion:g.schemaVersion},g.steps,T);f=y.steps,E=y.newVersion}catch(y){T.error({err:y},`Failed to migrate module ${d.name} (${d.relativePath})`);continue}let S=f.map((y,A)=>{if(ux.string().uuid().safeParse(y.id)||(T.error(`Step ${A} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${y.id}'`),s++,m=!0,r&&(p=!0,y.id=nr())),o[y.id]?.testId){let w=o[y.id]?.testRelativePath;s++,m=!0,T.error(`Step ${A} in module '${d.name}' (${d.relativePath}) has the ID ${y.id} which is duplicated in test ${w}`),r&&(p=!0,y.id=nr())}if(y.type==="PRESET_ACTION"){let w=y.command.id;al(w)||(T.error(`Command ${A} in module '${d.name}' (${d.relativePath}) has an ID that does not parse as a UUID: '${w}'`),s++,m=!0,r&&(p=!0,y.command.id=nr()));let x=i[w],_=l[w];x||_?(s++,m=!0,_?.moduleId===d.id?T.error(`Multiple commands in module '${d.name}' (${d.relativePath}) have the same ID '${w}'`):x?T.error(`Command in module '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in test ${x.testRelativePath}`):T.error(`Command ${A} in module '${d.name}' (${d.relativePath}) has the ID ${w} which is duplicated in module ${_.moduleRelativePath}`),r&&(p=!0,y.command.id=nr())):l[w]={moduleId:d.id,moduleRelativePath:d.relativePath}}return Le.parse(y)});m&&T.dimmed("=".repeat(80)),p&&r&&(Dt({content:{...g,steps:S},schemaVersion:E,momenticFiles:t,project:e,forceSaveOnNoDiffs:!0}),c.add(d.fullFilePath))}catch(p){T.error({err:p},`Failed to parse module ${d.name} (${d.relativePath})`);continue}return{errors:s,modifiedTestFilePaths:a,modifiedModuleFilePaths:c}}async function dx({fix:r,project:e}){let{errors:t,modifiedTestFilePaths:n,modifiedModuleFilePaths:o}=await gd({fix:r,project:e});t>0?(T.error(`Found errors in ${t} steps`),r?(T.warn(`Modified the following test files:
4167
+ ${[...n].map(i=>`${st}- ${i}`).join(`
4168
+ `)}`),o.size>0&&T.warn(`Modified the following module files:
4169
+ ${[...o].map(i=>`${st}- ${i}`).join(`
4170
+ `)}`)):T.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(T.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function px({project:r}){let e=W(r),t=Object.values(e.tests),n=await Nc(e,Q),o={},i={},a=new Set,l=new Set;for(let s of t)o[s.name]?i[s.name]?i[s.name].push(s.fullFilePath):i[s.name]=[o[s.name],s.fullFilePath]:o[s.name]=s.fullFilePath;for(let s of n)l.has(s.name)&&a.add(s.name),l.add(s.name);if(Object.entries(i).length>0||a.size>0){for(let[s,u]of Object.entries(i))for(let d of u)T.error(`Test Name ${s} is duplicated in ${d}`);for(let s of a)T.error(`Module name ${s} is duplicated in your project`);process.exit(1)}T.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as v1}from"lodash-es";async function mx({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=v1(t.config);o.environments||(o.environments=[]);for(let i of n){let a=o.environments?.find(l=>l.name===i.name);if(a)!e&&!await Nt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[ht],delete i.variables[ht],a.envVariables=i.variables;else{let l=i.variables[ht];delete i.variables[ht],o.environments.push({name:i.name,baseUrl:l,envVariables:i.variables})}}ta(o,t.configFilePath),T.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as gx}from"crypto";import hx from"fs";async function kh({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:r,all:t}),a=0;for(let[c,s]of Object.entries(o)){let u=fx(c,Se.TEST);!n&&!await om(u)||(a+=1,hx.writeFileSync(u,s,"utf-8"),Q.info({checksum:gx("md5").update(s).digest("hex")},`Wrote '${u}'`))}let l=0;for(let[c,s]of Object.entries(i)){let u=fx(c,Se.MODULE);!n&&!await om(u)||(l+=1,hx.writeFileSync(u,s,"utf-8"),Q.info({checksum:gx("md5").update(s).digest("hex")},`Wrote '${u}'`))}a===0?T.success("Pulled 0 tests."):T.success(`Pulled ${a} test${a>1?"s":""}${l?` and ${l} module${l>1?"s":""}`:""}!`)}function fx(r,e){switch(e){case Se.TEST:return`${_e(r)}.${St.TEST}`;case Se.MODULE:return`${_e(r)}.${St.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function Sx(r){let{project:e,client:t,skipPrompts:n}=r;T.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),T.info("Importing environments from Momentic Cloud."),T.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await Nt("Are you sure you want to proceed?",!0)||(T.info("Aborting..."),process.exit(1)),await mx({client:t,project:e,skipPrompts:n}),T.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.`),T.info("Importing tests and modules from Momentic Cloud."),await kh({testsToFetch:[],client:t,all:!0,yes:n}),T.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 yx(r){let{client:e,skipPrompts:t,paths:n}=r;await kh({testsToFetch:n,client:e,all:void 0,yes:t}),T.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 hi,InvalidArgumentError as sl,Option as Oe}from"@commander-js/extra-typings";import{validateHeaderValue as R1}from"http";import{z as Ex}from"zod";var hd=58888;function So(r){let e=parseInt(r,10);if(isNaN(e))throw new sl("Not a number.");return e}function fd(r){if(r===void 0)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,n),i=t.slice(n+1);R1(o,i),e[o]=i}return e}var Ur=new Oe("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new sl("API key is required.");return r}).makeOptionMandatory(),Br=new Oe("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return Ex.string().url().parse(r),r}catch{throw new sl("Not a valid URL.")}}),yo=new Oe("-y, --yes","Skip all confirmation prompts.").env("CI"),Fh=new Oe("-w, --wait","Wait for tests to finish running before exiting."),Uh=new Oe("--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(So),Sd=new Oe("--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."),Tx=new Oe("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(Ul)),bx=new Oe("--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"),Bh=new Oe("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),vx=new Oe("--upload-results","Upload test results to Momentic Cloud.").default(!1),zh=new Oe("--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."),Hh=new Oe("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Gh=new Oe("--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(So),Vh=new Oe("--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."),yd=new Oe("--env <env>","Name of the environment to use when running tests."),Ed=new Oe("--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(r=>{try{return Ex.string().url().parse(r),r}catch{throw new sl("Not a valid URL.")}}),Rx=new Oe("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>{let e=So(r);if(e<1)throw new sl("Shard index must be greater than 0.");return e}),Ax=new Oe("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(So),or=new Oe("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),xa=new Oe("-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."),wx=new Oe("--fix","Attempt to fix any issues found."),jh=new Oe("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),$h=new Oe("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),Cx=new Oe("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),xx=new Oe("--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}),_x=new Oe("--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}),Ix=new hi("<tests...>","One or more test paths to queue on Momentic Cloud."),Px=new hi("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),Wh=new hi("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),Mx=new hi("<suites...>","One or more suite paths that exist on Momentic Cloud."),Ox=new hi("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),Lx=new hi("<results>","Path to the results archive.").argRequired(),qh=new Oe("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Kh=new hi("<test>","Name of the test to quarantine.").argOptional();async function Nx(r){let e=W(r),t=Object.values(e.tests);for(let n of t)try{let o=Yo(n.fullFilePath,T,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){T.debug(`Test ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=Ot.parse(o),l=await jo(a,i,T);T.dimmed(`Updating ${n.relativePath}`),wt({relativeTestPath:n.relativePath,steps:{beforeSteps:o.beforeSteps,steps:l.steps,afterSteps:o.afterSteps},schemaVersion:ie,project:r,forceSaveOnNoDiffs:!0})}catch(o){T.error({err:o},`Failed to read or migrate test ${n.name} (${n.relativePath}), continuing...`)}for(let n of Object.values(e.modules)){T.dimmed(`Updating ${n.relativePath}`);try{let o=bn(n.fullFilePath,T),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){T.debug(`Module ${n.name} (${n.relativePath}) has no steps, skipping...`);continue}let a=await jo({id:o.moduleId,schemaVersion:o.schemaVersion},i,T);Dt({content:{...o,steps:a.steps},schemaVersion:ie,momenticFiles:e,project:r,forceSaveOnNoDiffs:!0})}catch(o){T.error({err:o},`Failed to read or migrate module ${n.name} (${n.relativePath}), continuing...`)}}}import{spawnSync as C1}from"child_process";import{PostHog as w1}from"posthog-node";async function Dx(r,e){let t,n=0,o=3,i,a;for(;n<o;)try{let l=await z(r.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=l.featureFlags||{},a=l.featureFlagPayloads||{};break}catch(l){t=l,n++,await new Promise(c=>setTimeout(c,100*n))}if(i&&a)return{flags:i,payloads:a};throw t}var Td=class r extends ns{constructor(t,n,o,i){super(o,i);this.client=t;this.orgId=n}static async init(t){let n=new w1("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await Dx(n,t);return new r(n,t,o,i)}async refresh(){let{flags:t,payloads:n}=await Dx(this.client,this.orgId);this.flags=t,this.payloads=n}};function x1(){try{let e=C1("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();T.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(r){let e=r instanceof Error?r.message:String(r);T.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
4171
+ ${e}`)}}async function kx({project:r,orgId:e,apiClient:t}){T.info("Pulling browser and AI configuration options from Cloud");let n=await Td.init(e);r.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"),...r.config.browser},r.config.advanced={fakerConstantSeed:n.isBooleanFlagEnabled("faker_constant_seed"),...r.config.advanced},r.config.ai={aiPageFiltering:n.isBooleanFlagEnabled("rag_v2"),agentConfig:await t.getAgentConfig(),...r.config.ai},T.info(`Updated ${r.configFilePath} to include V2 browser and AI configuration options`),T.info("Determining main Git branch"),r.config.gitMainBranch=x1(),ta(r.config,r.configFilePath),T.success("Migration complete!")}import{input as _1,search as I1}from"@inquirer/prompts";import P1 from"fuse.js";async function bd({prompt:r,inputtedTest:e,testOptions:t}){if(e){let a=t.find(l=>l.name===e);if(!a)T.error(`${e} is not a valid test option.`);else return{name:a.name,id:a.value}}let n=new P1(t,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await I1({message:r,source:async a=>!a||a.length===0?t:n.search({name:a}).map(c=>c.item)}),i=t.find(a=>a.value===o);return{name:i.name,id:i.value}}async function vd({prompt:r,inputtedReason:e}){return e||_1({message:r})}async function Fx({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=W(n).tests,l=Object.values(a).map(u=>({value:u.id,name:u.name})),c=await bd({prompt:"Select a test to quarantine.",inputtedTest:r,testOptions:l}),s=await vd({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await t.quarantineTest(c,s,i),T.success(`Test ${c.name} has been successfully quarantined. Navigate to ${t.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${c.name}'.`)}async function Ux({test:r,reason:e,apiClient:t,project:n,logger:o,identity:i}){let a=W(n).tests,l=Object.values(a).map(m=>({value:m.id,name:m.name})),c=(await t.getQuarantinedTests()).quarantined,s=new Set(c.map(m=>m.testId)),u=l.filter(m=>s.has(m.value)),d=await bd({prompt:"Select a test to unquarantine.",inputtedTest:r,testOptions:u}),p=await vd({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await t.unquarantineTest(d,p,i),T.success(`Test ${d.name} has been successfully removed from quarantine.`)}function Bx(r){return r?_e(r):"Unknown suite"}async function zx({client:r,orgId:e,suitePaths:t,wait:n,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:l}=await r.queueSuiteRuns({paths:t,...i});Q.info({orgId:e,suiteRunIds:a,runGroupIds:l,suitePaths:t},"Queued suites remotely"),T.dimmed(`Queued ${t.length} suites.`),n||process.exit(0);let c=Date.now();T.dimmed(`Waiting for ${t.length} suites to finish. You can view results upon completion at:`);for(let f of l)T.dimmed(`${st}- ${r.getAppUrl()}/run-groups/${f}`);let s=new Set,u=[],d=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(S=>S.status==="FAILED"&&(S.failureReason||S.finishedAt&&Date.now()-S.finishedAt.getTime()>30*1e3)||S.status==="PASSED"||S.status==="CANCELLED"),p=await sc({name:"suites",getResults:async()=>{let f=l.filter(y=>!u.some(A=>A.id===y)),E=await r.bulkGetRunGroupStatus(f),S=[];for(let y of E)d(y)?u.push(y):S.push(y);return[...u,...S]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(E=>{E.status==="RUNNING"&&(s.has(E.id)||(s.add(E.id),T.log(`${s.size}/${l.length} ${Bx(E.suite?.name)}`)))}),f.every(d))}),m=r.getAppUrl(),h=Hi({results:p,startTime:c,onFailed:f=>{let E=Bx(f.suite?.name),S=f.runs.filter(A=>A.status==="FAILED").length,y=f.runs.length;T.error(`${E} (${S}/${y} tests failed):`);for(let A of f.runs)if(A.status==="FAILED"){let R=A.testName||A.test?.name;T.error(` ${R?_e(R):"Unknown test"} (${m}/runs/${A.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?_e(f.suite.name):"Unknown suite name"} (${m}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function Hx({tests:r,client:e,orgId:t,...n}){!n.yes&&!await Nt(`This command will queue ${r.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:r,...n});if(Q.info({queuedTests:o,runIds:i,orgId:t},"Queued tests remotely"),T.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;T.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,l=[],c=m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED",s=e.getAppUrl(),u=Date.now(),d=await sc({name:"runs",getResults:async()=>{let m=i.filter(f=>!l.some(E=>E.id===f)),g=await e.bulkGetRunStatus(m),h=[];for(let f of g)c(f)?l.push(f):h.push(f);return[...l,...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&&T.log(`${a.size}/${o.length} ${_e(h)}`)}}),m.every(c))}),p=Hi({results:d,startTime:u,onFailed:m=>{let g=m.testName||m.test?.name;lc(m,g?_e(g):"Unknown test")},getDisplayLine:m=>{let g=m.testName||m.test?.name,h=` ${g?_e(g):"Unknown test"}`;return m.id&&(h+=` (${s}/runs/${m.id})`),h},entity:"test"});process.exit(p.failed>0?1:0)}import{randomUUID as fG}from"crypto";import SG from"fs";import{existsSync as j1,mkdirSync as $1,statSync as W1}from"fs";import{randomUUID as Gx}from"crypto";import Yh from"fs";import{hostname as M1}from"os";import Xh from"path";async function Rd(r,e,t,n){if(n){let o=await e.getScreenshot(r,n);if(o){let i=`${n}-screenshot.jpeg`,a=Xh.join(t,i);return Yh.writeFileSync(a,o),i}}}async function O1(r,e,t,n){let o=n.runId??Gx(),i={uuid:o,historyId:o,testCaseId:n.test.id,fullName:n.test.name,name:_e(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:t.suiteName},{name:"host",value:M1()},{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[l,c]of Object.entries(n.parameters))c!=null&&i.parameters.push({name:l,value:JSON.stringify(c)});n.results&&await L1(r,e,t.folder,i.steps,n.results);let a=`${o}-result.json`;Yh.writeFileSync(Xh.join(t.folder,a),JSON.stringify(i,void 0,2))}async function _a(r,e,t,n){let o={name:Xn(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 Rd(r,e,t,n.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await Rd(r,e,t,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){let l=`${Gx()}-attachment.json`,c=Xh.join(t,l);Yh.writeFileSync(c,JSON.stringify(n.data,null,2)),o.attachments.push({name:"Step output data",source:l,type:"text/plain"})}return o}async function L1(r,e,t,n,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{n.push(await _a(r,e,t,i));break}case"CONDITIONAL":{let a=await _a(r,e,t,i);a.steps=[],i.assertionResult&&a.steps.push(await _a(r,e,t,i.assertionResult)),a.steps.push(...await Promise.all(i.results.map(l=>_a(r,e,t,l)))),n.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await _a(r,e,t,i);if(a.steps=await Promise.all(i.results.map(l=>_a(r,e,t,l))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[l,c]of Object.entries(i.inputs))a.parameters.push({name:l,value:c})}n.push(a)}}}async function Vx(r,e,t,n){for(let o of n.runs)await O1(r,e,{folder:t,suiteName:n.suiteName},o)}import N1 from"junit-report-builder";import Ad from"path";function D1(r,e){if(e.name(r.test.name).className(r.test.name).file(Ad.relative(".",r.filePath)).property("id",r.test.id).property("dd_tags[id]",r.test.id),r.test.labels&&(e.property("labels",r.test.labels.join(",")),r.test.labels.forEach(t=>{e.property("dd_tags[label]",t)})),r.baseUrl&&(e.property("base_url",r.baseUrl),e.property("dd_tags[base_url]",r.baseUrl)),r.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${r.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${r.runId}`)),r.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),r.quarantinedReason&&(e.property("quarantined_reason",r.quarantinedReason),e.property("dd_tags[quarantined_reason]",r.quarantinedReason))),r.beforeResults?.some(t=>t.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),r.results?.some(t=>t.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),r.afterResults?.some(t=>t.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),r.status==="FAILED"){if(r.failureReason){let t=xl[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||Ii[r.failureReason];r.runId&&(n+=` Visit https://app.momentic.ai/runs/${r.runId} for more details.`),e.failure(n,t)}r.failureDetails?.errorStack&&e.stacktrace(r.failureDetails.errorStack)}else r.status==="CANCELLED"&&e.skipped();return e.time((r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime())/1e3).property("started_at",r.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",r.lastAttemptStartedAt.toISOString()).property("finished_at",r.finishedAt.toISOString()).property("dd_tags[finished_at]",r.finishedAt.toISOString()),e.property("attempts",r.attempts.toString()).property("dd_tags[attempts]",r.attempts.toString()),r.parameters.envName&&(e.property("environment",r.parameters.envName),e.property("dd_tags[environment]",r.parameters.envName)),r.parameters.urlOverride&&e.property("url_override",r.parameters.urlOverride),e}function k1(r,{suiteId:e,suiteName:t,startedAt:n,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:l,quarantinedTestReasons:c}){let s=r.testSuite().name(t);e&&s.property("id",e),s.timestamp(n).property("startedAt",n.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-n.getTime())/1e3);for(let u of i){let d=s.testCase();D1(u,d)}for(let u of a){let d=s.testCase();d.name(u.name).className(u.name).file(Ad.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 l){let d=s.testCase();d.name(u.name).className(u.name).file(Ad.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 s}function jx(r,e){let t=N1.newBuilder();k1(t,e),t.writeTo(Ad.join(r,`${e.suiteName}.xml`))}import F1 from"fs";import U1 from"path";function $x(r){return{title:Xn(r),duration:r.finishedAt.getTime()-r.startedAt.getTime(),error:r.status==="FAILED"?{value:r.failureReason}:void 0,steps:r.results&&r.type!=="PRESET_ACTION"?r.results.map($x):[]}}async function B1(r,e,t,n){if(n.results?.length){let o=await Rd(r,e,t,n.results[n.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function z1(r,e,t,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||Ii[n.failureReason]}:void 0,retry:n.attempts-1,steps:n.results?.map($x)||[],startTime:n.lastAttemptStartedAt.toISOString(),attachments:await B1(r,e,t,n)}}async function H1(r,e,t,n){return{expectedStatus:"passed",status:n.status==="PASSED"?"expected":"unexpected",results:[await z1(r,e,t,n)]}}async function G1(r,e,t,n){return{tags:[],title:n.test.name,ok:n.status==="PASSED",tests:[await H1(r,e,t,n)],id:n.runId,file:n.filePath}}function Jh(r,e){return r.reduce((t,n)=>e(n)?t+1:t,0)}async function V1(r,e,t,n){return{suites:[{title:n.suiteName,file:n.projectConfigPath,specs:await Promise.all(n.runs.map(o=>G1(r,e,t,o)))}],errors:[],stats:{startTime:n.startedAt.toISOString(),duration:n.finishedAt.getTime()-n.startedAt.getTime(),expected:Jh(n.runs,o=>o.status==="PASSED"),unexpected:Jh(n.runs,o=>o.status!=="PASSED"),flaky:Jh(n.runs,o=>!!o.isFlake),skipped:0}}}async function Wx(r,e,t,n){let o=await V1(r,e,t,n);F1.writeFileSync(U1.join(t,`${n.suiteName}.json`),JSON.stringify(o,null,2))}async function qx(r,e,t,n,o){switch(j1(o)?W1(o).isDirectory()||(T.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)):(T.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),$1(o,{recursive:!0})),t){case"junit":jx(o,n);return;case"allure":case"allure-json":await Vx(r,e,o,n);return;case"playwright-json":await Wx(r,e,o,n);return;default:throw new Error(`Unknown reporter format requested: '${t}'`)}}import yG from"wait-on";import{execSync as q1}from"child_process";import{platform as K1}from"os";function Qh(){return Kx()?(T.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),T.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.
4172
+ `),2):(T.dimmed("Setting device pixel ratio to 1."),T.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.
4173
+ l.`),1)}function Kx(){return K1()==="darwin"&&q1("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Zh(r){Kx()&&r===1&&(T.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),T.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import Y1 from"@actions/exec";import X1 from"@actions/io";import J1 from"quote";import Q1 from"string-argv";async function Yx(r,e=!0){let t=Q1(r),n=await X1.which(t[0],!0),o=t.slice(1),i=Y1.exec(J1(n),o,{delay:100});if(e)return i}import Z1 from"csv-parser";import{createReadStream as eG}from"fs";function ef(r){return new Promise((e,t)=>{let n=[];eG(r).pipe(Z1()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import wd from"semver";import{z as Cd}from"zod";var _n="2.17.7",tG="https://registry.npmjs.org/momentic",rG=Cd.object({versions:Cd.record(Cd.string(),Cd.unknown()).optional()});async function Xx(r){try{await nG(r)}catch(e){T.warn({err:e},"Failed to check CLI version against NPM servers")}}async function nG(r){if(!_n){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await z(fetch(tG),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=rG.parse(i).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))wd.valid(n)&&(!t||wd.gt(n,t))&&wd.gt(n,_n)&&wd.lt(n,"2.0.0")&&!n.includes("alpha")&&(t=n);t&&(T.warn(`Update available: v${_n} -> v${t}`),T.warn("This version may be missing critical fixes, features, and security updates."),T.warn(`Run "npx momentic@${t} -V" to update`))}import tf from"fs";import{compact as oG,partition as xd}from"lodash-es";import rf from"path";import{cwd as iG}from"process";import aG from"semver";async function _d({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,labels:a,logger:l}){let c=new Set;if(r&&r.length>0){let u=r.some(p=>tf.existsSync(p)),d=iG();u?(d!==t.rootDir&&l.warn(`The current working directory ('${d}') is different from the project root directory ('${t.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.`),l.info(`Reading tests from the following local file paths:
4174
+ ${r.map(p=>`${st}- ${p}`).join(`
4135
4175
  `)}
4136
- `),r.forEach(p=>{if(!Qh.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=Qh.statSync(p),g=m.isDirectory()}catch(f){l.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=Zh.resolve(p);Object.values(e.tests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(l.info(`Reading all tests from the project and running those matching the following substring filters:
4137
- ${r.map(p=>`${it}- ${p}`).join(`
4138
- `)}`),Object.values(e.tests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Nt("No test paths or substrings were provided. Do you want to run all tests?")&&(l.error("Cancelled by user."),process.exit(1));let u=Object.values(e.tests);l.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=Zh.relative(t.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 s=Array.from(c).map(async u=>{try{let d=await tt(u,Q,e);if($1.gt(d.schemaVersion,oe)&&l.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:Zh.relative(t.rootDir,u)}}catch(d){l.error(`Failed to read and resolve test at '${u}': ${d}`),process.exit(1)}});return Promise.all(s).then(V1)}function Fx({testDefinitions:r,quarantinedTestReasons:e,onlyQuarantined:t=!1,skipQuarantined:n=!1}){if(t){let[u,d]=Ad(r,g=>g.id in e),[p,m]=Ad(u,g=>g.disabled||n);return{testsToSkip:p,quarantinedTestsToSkip:[],testsToRun:m,quarantinedTestsToRun:[]}}let[o,i]=Ad(r,u=>u.disabled),[a,l]=Ad(i,u=>u.id in e);return{testsToSkip:o,testsToRun:l,quarantinedTestsToRun:n?[]:a,quarantinedTestsToSkip:n?a:[]}}function Ux({testsToRun:r,quarantinedTestsToRun:e,quarantinedTestReasons:t,testInputMatrix:n}){let o=[],i=(a,l,c)=>{n?n.forEach((s,u)=>{o.push({inputs:s,inputIndex:u,testDefinition:a,quarantined:l,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:a,quarantined:l,quarantinedReason:c})};return r.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,t[a.id])),o}import{partition as W1}from"lodash-es";function Cd(r){return r.length===1?"test":"tests"}function Bx(r){return r===1?"1 worker":`${r} workers`}function zx(r){r.length!==0&&(E.info(`Skipping ${r.length} disabled ${Cd(r)}:`),r.forEach(e=>{E.info(`${it}- ${[e.relativeFilePath]}`)}),E.log(""))}function Hx(r,e){r.length!==0&&(E.info(`Skipping ${r.length} quarantined ${Cd(r)}:`),r.forEach(t=>{E.info(`${it}- ${[t.relativeFilePath]}: ${e[t.id]}`)}),E.log(""))}function q1(r,e){r.length!==0&&(E.info(`Running ${r.length} quarantined ${Cd(r)} with ${Bx(e)}:`),r.forEach(t=>{E.info(`${it}- ${[t.testDefinition.relativeFilePath]}${typeof t.inputIndex=="number"?` with input set ${t.inputIndex}`:""}`)}),E.log(""))}function K1(r,e,t){e.length===0&&r.length>0||(E.info(`Running ${e.length} ${Cd(e)} with ${Bx(t)}:`),e.forEach(n=>{E.info(`${it}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),E.log(""))}function Gx({logger:r,localTestsToRunWithInputs:e,parallel:t,shardCount:n,shardIndex:o}){r.info({tests:e.length,shardCount:n,shardIndex:o,parallel:t},"Running local tests");let[i,a]=W1(e,l=>l.quarantined);q1(i,t),K1(i,a,t)}import{cloneDeep as Ca}from"lodash-es";async function Vx({orgId:r,codeEvalTools:e,logger:t,outputDefinitions:n,testContext:o,flagStore:i}){let a={};for(let l of n){let{name:c,value:s}=l;a[c]=await er({orgId:r,s,localTools:e,logger:t,context:o})}return a}async function jx({baseUrl:r,envName:e,testName:t,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:l,generator:c,orgId:s,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,flagStore:y}){let S=await jc({settings:g,customHeaders:p,envVariables:u,envName:e,testName:t,baseUrl:r,logger:d,localTools:l,orgId:s}),T={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:Q},A=y.isBooleanFlagEnabled("icon_knowledge_base")?await a.fetchIconKnowledgeBase(d):null,R=S.browserType??"Chromium";if(!RE(R)){let P=`Browser ${R} 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...`;E.warn(P),Q.warn(P)}let w=await yr.init({baseUrl:r,logger:d,userBrowserSettings:S,storage:a,flagStore:y,enricher:new Xn(T,c),contextArgs:{viewport:i.advanced.viewport??Mt,locale:i.advanced.locale??zn,geolocation:i.advanced.geolocation??Gn,timezoneId:i.advanced.timezone??Hn,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},iconKnowledgeBase:A}),x=new po({browser:w,generator:c,logger:d,orgId:s,options:{scratchPadId:void 0,slowMoMs:S.slowMoMs,autoFollowNewTabs:S.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??y.isBooleanFlagEnabled("rag_v2")},storage:a,flagStore:y,localCodeEvalTools:l,visualDiffScreenshotStorage:f}),_=new qt({baseUrl:r,currentUrl:x.browser.url(),variablesFromEnvironment:u,envName:e,testName:t});return i.parameters&&await Promise.all(i.parameters.map(async P=>{let{name:Y,defaultValue:$,required:U}=P,L=m?.[Y];U&&L===void 0&&(E.error(`Required parameter '${Y}' is required by test '${i.name}' but not provided`),process.exit(1));let M=await er({orgId:s,s:L??$,localTools:l,logger:d,context:qt.dummyContext(_.getEnvName())});_.setMomenticSystemVariable(Y,M)})),{controller:x,context:_}}async function $x({testAdvancedSettings:r,orgSettings:e,logger:t}){if(r.failureRecovery===!1||r.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Pa){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return t.warn(n),E.warn(n),!1}return!0}async function Wx({attemptInputs:r,attemptFixtures:e,attemptMetadata:t}){let{orgId:n,runId:o}=t,{controller:i,context:a,codeEvalTools:l,storageClient:c,logger:s,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=r;s.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:s,codeEvalTools:l},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 $x({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:s})};return await Vc({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function qx(r){let{testDefinition:e,logger:t}=r,n=new Date;try{return await Y1(r)}catch(o){let i="Fatal error running test";return E.error(`${i}: ${o.message}`),t.error({err:o},i),{results:[],parameters:r,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 Y1(r){let{testDefinition:e,project:t,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:l,logger:c,gitMetadata:s,alwaysSaveCache:u,noCache:d,runId:p,testInputs:m,quarantined:g,quarantinedReason:h,usageTracker:f}=r,y=new Vi(n,o),S=Yi({orgId:o,client:n,gitMetadata:s,alwaysSaveCache:u,noCache:d}),T=Ca(e.steps),A=Ca(e.beforeSteps)??void 0,R=Ca(e.afterSteps)??void 0;try{await S.resolveStepCacheEntries({testId:e.id,stepLists:{steps:T,beforeSteps:A,afterSteps:R},schemaVersion:e.schemaVersion,logger:c})}catch(U){throw c.error({err:U},"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: ${U}`)}let w=r.envName??J1(e),x,_={};if(w){try{x=Ts(w,t,c)}catch(U){let L=`Failed to resolve environment ${w} for test ${e.name}: ${U}`;throw new Error(L)}_=x.variables}let P=e.baseUrl;if(i)P=i;else if(!P){let U=_[ft];typeof U=="string"&&(P=U)}if(!P){let U=`Cannot run test with no base URL and no ${ft} variable defined in its environment`;throw new Error(U)}let Y=await l.startRun({logger:c,runId:p,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:P,environmentName:w,schemaVersion:e.schemaVersion,resolvedInputs:m,quarantined:g,quarantinedReason:h}),$=c.child(Y.loggerBindings||{});Object.entries(Y.envVarBindings||{}).forEach(([U,L])=>{_[U]=L});try{let U=await X1({...r,variables:_,envName:w,resolvedEnv:x,baseUrl:P,storageClient:y,tracer:Y,logger:$,cacheStorage:S,stepsWithCaches:T,beforeStepsWithCaches:A,afterStepsWithCaches:R,usageTracker:f});return await Y.finish({logger:c,status:U.status,finishedAt:U.finishedAt,failureDetails:U.failureDetails,failureReason:U.failureReason,isFlake:U.isFlake,failureRecoveryDetails:U.failureRecoveryDetails}),{runId:Y.runId,...U}}finally{a?.pop()}}async function X1(r){let{testDefinition:e,stepsWithCaches:t,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:s,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:g,testInputs:h,variables:f,resolvedEnv:y,retriesOverride:S,devicePixelRatio:T,logUpdate:A,tracer:R,logger:w,flagStore:x,cacheStorage:_,gitMetadata:P,quarantined:Y,quarantinedReason:$,usageTracker:U}=r,L=i.config.ai?.aiFailureAnalysis??!1,M=new Date,q=new na(i,a),we={...i.config},se={envName:p,urlOverride:m,customHeaders:g,testInputs:h},ze,Qe=Math.abs(S??i.config.retries??e.retries??0),ir=[];w.info({...P,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let dt=0;dt<=Qe;dt++){let re=await R.startAttempt(),Ce=w.child(re.loggerBindings||{}),He={...e,steps:Ca(t),beforeSteps:Ca(n),afterSteps:Ca(o)};dt!==0&&A("RETRY",`attempt ${dt+1}/${Qe+1}`);let Ar=new Date,fi=we.advanced?.fakerConstantSeed??x.isBooleanFlagEnabled("faker_constant_seed"),_a=new Yr({httpClient:new Rt({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:Ce}),fakerSeed:fi?Bi:void 0}),Pd=re;try{let{controller:Ut,context:wr}=await jx({baseUrl:s,envName:p,testName:He.name,apiClient:l,devicePixelRatio:T,logger:Ce,storageClient:u,codeEvalTools:_a,test:He,generator:c,orgId:d,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...i.config.browser||{},...y?.browser||{},...He.advanced},aiSettings:{...i.config.ai||{},...He.advanced||{}},visualDiffScreenshotStorage:q,flagStore:x});ze=await Wx({attemptMetadata:{attemptNumber:dt+1,orgId:d,runId:R.runId},attemptFixtures:{logger:Ce,storageClient:u,usageTracker:U,codeEvalTools:_a,flagStore:x,apiClient:l,context:wr,controller:Ut,tracer:re},attemptInputs:{test:He,orgSettings:we}});let bo=new Date,zr={logger:w,cacheStorage:_,orgId:d,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:He.steps,beforeSteps:He.beforeSteps,afterSteps:He.afterSteps}};ze?.status==="PASSED"?await mc(zr):ze?.status==="FAILED"&&await gc(zr),await re.finish({logger:Ce,result:ze}),ir.unshift(ze.status);let V=await Vx({orgId:d,codeEvalTools:_a,logger:Ce,outputDefinitions:e.outputs??[],testContext:wr,flagStore:x}),Mn=Xf(ir),Si=dt+1;if(ze.status!=="FAILED")return{...ze,parameters:se,test:He,filePath:He.relativeFilePath,startedAt:M,lastAttemptStartedAt:Ar,finishedAt:bo,attempts:Si,baseUrl:s,outputs:V,isFlake:Mn,quarantined:Y,quarantinedReason:$};let yi=ze.failedStepResult,un=yi?.message||"Unknown failure",Cr=yi?.failureReason??WS(un)??"UnknownError",Md=Ce.child({errResult:yi,failureReason:Cr,errorMessage:un,numAttempts:Qe+1,name:He.name});if(dt<Qe){Md.warn(`Retrying failed execution attempt for run: ${un}`);continue}Md.error(`Test failed after all exhausting attempts: ${un}`);let il=new Error(un),xt={errorMessage:un,errorStack:il.stack},vo;if(L){let On;try{if(ze.results&&ze.results.length>0){let{classification:bt,aiFailureReason:dn}=await RT({logger:Ce,browserStateStorage:Pd,generator:c,fullResults:ze,failureReason:Cr,error:il,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});On=bt,vo=dn}}catch(bt){Ce.warn({err:bt},"Failed to classify test results")}On&&(xt.classification=On,Cr=vo??Cr)}return{...ze,parameters:se,failureDetails:xt,failureReason:Cr,test:He,filePath:He.relativeFilePath,startedAt:M,lastAttemptStartedAt:Ar,finishedAt:bo,attempts:dt+1,baseUrl:s,outputs:V,quarantined:Y,quarantinedReason:$}}catch(Ut){Ia(Ut);let wr=`Encountered fatal platform error while running test '${He.name}': ${Ut}`,bo=new Date,zr=dt+1;Ce.error({err:Ut},wr),E.error(wr);let V={errorMessage:Ut.message,errStack:Ut.stack},Mn={status:"FAILED",failureDetails:V,failureReason:"InternalPlatformError",finishedAt:bo};return await re.finish({logger:Ce,result:{status:"FAILED",results:[]}}),{...Mn,results:[],parameters:se,test:He,filePath:He.relativeFilePath,startedAt:M,lastAttemptStartedAt:Ar,finishedAt:new Date,attempts:zr,baseUrl:s,outputs:{},quarantined:Y,quarantinedReason:$}}}throw new Error("This code should not be reachable")}function J1(r){for(let e of r.envs??[])if(e.default)return e.name}import{randomUUID as Q1}from"crypto";var To="assets";function Z1(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function eG(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var ef=class{constructor(e,t,n,o,i){this.orgId=e;this.testId=t;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${To}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${To}/${t}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${To}/${t}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${To}/${t}.html`,contents:n})}heal(e){let{healType:t}=e;this.metadata.healMetadata={healType:t,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:eG(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new xa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},xa=class{constructor(e,t,n,o){this.orgId=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,t){return this.diskStorage.readFile(`${To}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${To}/${t}.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,t]of Object.entries(this.stepFrequenciesByType))vr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}async startStep(e){let{step:t}=e;this.recordStepStat(t);let n={step:t,status:"RUNNING",startedAt:new Date},o=new ef(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(t=>t.finishInternal({status:Z1(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}},tf=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:Ec(n.results,t),beforeResults:n.beforeResults?Ec(n.beforeResults,t):void 0,afterResults:n.afterResults?Ec(n.afterResults,t):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new xa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new xa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new xa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${To}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${To}/${t}.html`)?.toString()}},rf=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[Eb]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...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:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(){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 e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t=Q1(),n={id:t,schemaVersion:oe,runAttemptSchemaVersion:lE,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new tf(this.orgId,this.testId,this.testName,t,n,e);return this.children.push(o),o}},xd=class r{constructor(e,t,n,o){this.orgId=e;this.runGroupId=t;this.metadata=n;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,n,o,i){let a={...o,id:t,trigger:ur.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Pn,labels:i??[]},l=new vs(n);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new r(e,t,a,l)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,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 t=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:Pn,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new rf(this.orgId,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function Kx(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function Yx(r){let{logger:e,tests:t,yes:n,start:o,waitOn:i,client:a,debugDataStorage:l,flagStore:c,project:s,retriesOverride:u,urlOverride:d,envName:p,orgId:m,devicePixelRatio:g,customHeaders:h,testInputMatrix:f,reporter:y,include:S,exclude:T,labels:A,reporterDir:R=HT,outputDir:w=GT,uploadResults:x=!1,waitOnTimeout:_=60,parallel:P,shardIndex:Y=1,shardCount:$=1,regenerateGoldenFiles:U,gitMetadata:L,alwaysSaveCache:M,noCache:q,ignoreQuarantine:we,skipQuarantined:se,onlyQuarantined:ze,runGroupId:Qe}=r;o&&(e.info({orgId:m},`Executing start command: ${o}`),await Dx(o,!1)),i&&(e.info({orgId:m},`Waiting for url: ${i} with timeout: ${_} seconds.`),await nG({resources:[i],interval:2500,timeout:_*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let ir=new Yn(s.config.ai?.agentConfig,{baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),dt=W(s),re=await wd({tests:t,momenticFiles:dt,yes:n,project:s,include:S,exclude:T,labels:A,logger:E}),Ce=await Kx(e,a,we),{testsToSkip:He,quarantinedTestsToSkip:Ar,testsToRun:fi,quarantinedTestsToRun:_a}=Fx({testDefinitions:re,quarantinedTestReasons:Ce,onlyQuarantined:ze,skipQuarantined:se});zx(He),Hx(Ar,Ce);let Pd=Ux({testsToRun:fi,quarantinedTestsToRun:_a,quarantinedTestReasons:Ce,testInputMatrix:f}),Ut=iG({globalTestsToRunWithInputs:Pd,shardIndex:Y,shardCount:$});Gx({logger:e,localTestsToRunWithInputs:Ut,parallel:P,shardCount:$,shardIndex:Y});let wr=[],bo=new Date,zr=new Set,V=async()=>{let xt=a.getAppUrl(),vo=Gi({results:wr,startTime:bo.getTime(),onFailed:bt=>{oc(bt,bt.filePath)},getDisplayLine:bt=>{let dn=`${it}- ${bt.filePath}${bt.failureRecoveryDetails?" [recovered] ":""}`;return bt.runId&&(dn+=` ( link when uploaded: ${xt}/runs/${bt.runId} )`),dn},entity:"test"}),On=wr.filter(bt=>!!bt.failureRecoveryDetails?.attempts);return On.length>0&&E.warn(`Our AI agent automatically prevented ${On.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),E.log(""),x?(E.success(`Test results have been saved to the folder ${w}. Uploading to Momentic Cloud...`),await kc({client:a,consoleLogger:E,resultsPath:w})):E.success(`Test results have been saved to the folder ${w}. Upload them to Momentic Cloud by running 'npx momentic results upload ${w}'.`),vo};rG.existsSync(w)&&E.warn(`Output directory ${w} already exists, removing before test execution...`);let Mn=await xd.start(m,Qe,w,L,A),Si=e.child(Mn.loggerBindings||{}),yi=[],un=async()=>{E.warn("SIGINT received. Stopping tests and printing latest results..."),await Mn.finish({logger:Si,status:"CANCELLED"}),await V(),await Promise.allSettled(yi.map(xt=>xt())),process.exit(1)};process.once("SIGINT",un);let Cr={};for(let xt=0;xt<Ut.length;xt++){let vo=Object.values(Cr);vo.length===P&&await Promise.race(vo.map(dn=>dn.promise));let On=Ut[xt],bt=`test-${xt}`;Cr[bt]={done:!1,promise:(async({inputs:dn,quarantined:t_,quarantinedReason:r_,testDefinition:Ro})=>{zr.add({inputs:dn});let al=Ro.relativeFilePath.includes("..")?Ro.fullFilePath:Ro.relativeFilePath;cs({status:"START",testLogRef:al,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length});let n_=setInterval(()=>cs({status:"RUN",testLogRef:al,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length}),5*60*1e3),Od=tG(),Ld=Si.child({testId:Ro.id,runId:Od}),af=new xc({logger:Ld,reporter:new ac(a),runType:"test-run",runId:Od,testMetadata:Ro,suiteMetadata:void 0});try{let sl=await qx({testDefinition:Ro,project:s,testInputs:dn,quarantined:t_,quarantinedReason:r_,orgId:m,runId:Od,devicePixelRatio:g,apiClient:a,runGroupTracer:Mn,generator:ir,retriesOverride:u,urlOverride:d,envName:p,customHeaders:h,regenerateGoldenFiles:U,logUpdate:(ll,o_)=>cs({status:ll,testLogRef:al,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length,additionalText:o_}),runSigIntHandlers:yi,logger:Ld,flagStore:c,gitMetadata:L,alwaysSaveCache:M,noCache:q,usageTracker:af});cs({status:sl.status,testLogRef:al,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length}),wr.push(sl)}catch(sl){let ll=`Encountered unexpected fatal error when running test '${Ro.name}': ${sl.message}`;E.error(ll),Ld.error(ll)}finally{clearInterval(n_),Cr[bt].done=!0,delete Cr[bt]}await af.flush(e)})(On)}}await Promise.allSettled(Object.values(Cr).map(xt=>xt.promise));let il=wr.some(xt=>!xt.quarantined&&xt.status==="FAILED")?"FAILED":"PASSED";return await Mn.finish({logger:Si,status:il}),process.off("SIGINT",un),y&&await Lx(Si,l,y,{projectConfigPath:s.configFilePath,suiteName:s.config.name,startedAt:bo,finishedAt:new Date,runs:wr,testsToSkip:He,quarantinedTestsToSkip:Ar,quarantinedTestReasons:Ce},R),V()}function oG(r,e,t){if(t>r.length&&(E.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.sort().filter((a,l)=>l>=n&&l<o)}function iG({globalTestsToRunWithInputs:r,shardIndex:e,shardCount:t}){return t&&t>1?oG(r,e,t):r}Nd||Q.warn("Sentry is not enabled in this environment due to unsupported node version");Fw({serviceName:"cli"});var pG=process.argv.some(r=>r.includes("--log-level"))&&process.argv.some(r=>r.includes("debug")),nf=r=>{pG&&E.dimmed(r)},Ft=new aG;Ft.name("momentic").description("Momentic CLI").version(Pn);Ft.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: ${rm.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(E.error("No browsers specified"),process.exit(1)),await AE({rawBrowsers:r,force:e.force,all:e.all})});Ft.addOption(new Jt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{r==="debug"&&E.info("Enabling debug logging"),E.setMinLevel(r.toLowerCase())});Ft.addOption(new Jt("--verbose","enable verbose logging")).on("option:verbose",()=>{Q.enableConsoleLogs(),E.setMinLevel(20)});var of=Ft.command("checks").alias("check").description("Perform various project checks");of.command("config").addOption(or).action(async r=>{Tt({configFilePath:r.config})});of.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(or).addOption(dx).action(async r=>{let e=Tt({configFilePath:r.config});await JC({project:e,fix:r.fix})});of.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(or).action(async r=>{let e=Tt({configFilePath:r.config});await QC({project:e})});var Jx=Ft.command("migrate").description("Migrate and upgrade tooling");Jx.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(or).action(async r=>{let e=Tt({configFilePath:r.config});await Tx(e)});Jx.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(Br).addOption(or).addOption(Ur).addOption(Eo).action(async r=>{!r.yes&&!await Nt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=Tt({configFilePath:r.config}),t=new Xe({baseUrl:r.server,apiKey:r.apiKey,logger:Q}),{orgId:n}=await t.getAuthInfo();await vx({project:e,orgId:n,apiClient:t}),process.exit(0)});Ft.command("import").addOption(Ur).addOption(Br).addOption(or).addOption(Eo).addArgument(fx).action(async(r,e)=>{let{apiKey:t,server:n,config:o,yes:i}=e,a=Tt({configFilePath:o}),l=new Xe({baseUrl:n,apiKey:t,logger:Q});!r||r.length===0?await nx({client:l,project:a,skipPrompts:i}):await ox({client:l,project:a,paths:r,skipPrompts:i}),process.exit(0)});Ft.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Jt("--name <name>","Name of the project")).action(async r=>{E.info(`Welcome to the Momentic project setup wizard! \u{1F680}
4139
- `),E.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."),Id.existsSync(ea)&&(E.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 t={name:r.name??await EE("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Cm};ta(t,ea),E.success(`Initialized Momentic project file at ${_d.resolve(ea)}`)});Ft.command("app").addOption(Ur).addOption(Br).addOption(Eo).addOption(Bh).addOption(or).addOption(Hh).addOption(Gh).action(async r=>{let{apiKey:e,yes:t,server:n,pixelRatio:o,disableCache:i,saveCache:a}=r,l=Tt({configFilePath:r.config,nameFilter:void 0}),{errors:c}=await dd({project:l,fix:!1});c>0&&(E.error(`Found ${c} errors`),E.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 s=new Xe({baseUrl:n,apiKey:e,logger:Q});await sm({client:s,skipPrompts:t});let u=dG(import.meta.url),d=_d.dirname(u),p=_d.resolve(d,"..","static"),m=_d.resolve(d,"..","assets"),g=o??Yh();Xh(g),await qC({momenticServerUrl:n,apiKey:e,serverPort:pd,appPort:pd,staticDir:p,assetsDir:m,devicePixelRatio:g,noCache:i,alwaysSaveCache:a,initialProject:l});let h=`http://localhost:${pd}`;await uG(h)});var Qx=Ft.command("queue").description("Queue tests or suites to run on Momentic Cloud");Qx.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Ur).addOption(Br).addOption(Nh).addOption(Dh).addOption(Eo).addArgument(Sx).addOption(fd).addOption(hd).addOption(gd).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:i,env:a,urlOverride:l}=e,c=md(e.customHeaders),s=new Xe({baseUrl:n,apiKey:t,logger:Q});(!r||!Array.isArray(r)||!r.length)&&(E.error("Must pass at least one suite to run."),process.exit(1));let{orgId:u}=await s.getAuthInfo();await Cx({client:s,orgId:u,wait:o,suitePaths:r,waitTimeout:i,env:a,urlOverride:l,customHeaders:c})});Qx.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Ur).addOption(Br).addOption(Eo).addOption(gd).addOption(zh).addOption(fd).addOption(hd).addOption(new Jt("--all","Run all tests.").default(!1)).addOption(Nh).addOption(Dh).addArgument(hx).action(async(r,e)=>{let{all:t,apiKey:n,env:o,server:i,inputCsv:a,urlOverride:l,wait:c,waitTimeout:s,yes:u}=e,d=md(e.customHeaders);for(let h of r)(h.endsWith(".yaml")||Id.existsSync(h))&&E.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 Xe({baseUrl:i,apiKey:n,logger:Q}),{orgId:m}=await p.getAuthInfo(),g;a&&(g=await Jh(a)),await xx({client:p,orgId:m,tests:r,all:t,customHeaders:d,env:o,urlOverride:l,wait:c,waitTimeout:s,testInputMatrix:g,yes:u}),process.exit(0)});var mG=Ft.command("list").description("List test paths");mG.addOption(or).addOption(Aa).addOption(Fh).addOption(Uh).addOption(new Jt("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(Vh).action(async(r,e)=>{let t=Tt({configFilePath:e.config,nameFilter:e.filter}),n=W(t),o=await wd({tests:r,momenticFiles:n,yes:!0,project:t,include:e.include,exclude:e.exclude,labels:e.labels,logger:new ns(40,{})});E.info(o.map(i=>i.relativeFilePath).join(`
4140
- `)),process.exit(0)});var gG=Ft.command("run").alias("test").description("Run tests on the local machine");gG.addOption(Ur).addOption(Br).addOption(or).addOption(Aa).addOption(Eo).addOption(gd).addOption(zh).addOption(Hh).addOption(Gh).addOption(px).addOption(mx).addOption(gx).addOption(hd).addOption(fd).addOption(Bh).addOption(new Jt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Jt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Jt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(yo)).addOption(new Jt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(yo)).addOption(new Jt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(yo)).addOption(new Jt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Jt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(ax).addOption(sx).addOption(kh).addOption(lx).addOption(ux).addOption(cx).addOption(Fh).addOption(Uh).addArgument(Vh).action(async(r,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let t=md(e.customHeaders),n=Tt({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??n.config.parallel??1;Xx().length<o*2&&E.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${Xx().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),E.debug({projectName:n.config.name},"Identified project config");let{errors:i}=await dd({project:n,fix:!1});i>0&&(E.error(`Found ${i} errors`),E.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),await vr.flush(),process.exit(1));let a=new Xe({baseUrl:e.server,apiKey:e.apiKey,logger:Q});E.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await sm({client:a,skipPrompts:e.yes});E.debug("API key check and browser installation complete");let s=new Ja,u=e.outputDir??n.config.outputDir,d=e.reporterDir??n.config.reporterDir,p=lG(),m=Q.child({runGroupId:p,orgId:l,cliVersion:Pn}),g=await Zn(Q,a,n);m.info({userId:c,...g},"Got local git metadata");let h=new Jr(n.config),f;e.inputCsv&&(f=await Jh(e.inputCsv));let y=e.pixelRatio??Yh();Xh(y);try{let S=await Yx({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:y,tests:r,project:n,client:a,debugDataStorage:s,flagStore:h,outputDir:u,uploadResults:e.uploadResults,reporterDir:d,customHeaders:t,envName:e.env,orgId:l,testInputMatrix:f,logger:m,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:g,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:p});await vr.flush(),S.failed>0?process.exit(1):process.exit(0)}catch(S){E.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),E.error(S),await vr.flush(),process.exit(1)}});var hG=Ft.command("apply").description("Apply an operation to local resources");hG.command("patch").addOption(Ur).addOption(Br).addOption(or).addOption(Aa).addOption(Eo).addOption(new Jt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Jt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async r=>{let{apiKey:e,server:t,config:n,yes:o}=r,i=Tt({configFilePath:n}),a=Q,l=new Xe({baseUrl:t,apiKey:e,logger:a}),c=W(i),s=c.tests[r.to]??Object.values(c.tests).find(d=>xe(d.name)===r.to.trim());s||(E.error(`No test matching '${r.to}' could be found in the current project.`),process.exit(1));let u=await l.fetchTestFragment(r.from);await YC({client:l,test:s,fragment:u,yes:o,entities:c,logger:Q}),process.exit(0)});var Zx=Ft.command("results").description("Merge and upload test results.");Zx.command("merge").description("Merge test results files.").addOption(kh).addArgument(yx).action(async(r,e)=>{let{outputDir:t}=e;t||(E.error("Output directory is required."),process.exit(1)),Id.existsSync(r)||(E.warn("Results path does not exist, skipping merge."),process.exit(0)),Id.existsSync(t)&&E.warn(`Output directory ${t} already exists, removing before merging...`),WT(Q,t,r)});Zx.command("upload").description("Upload test results to Momentic cloud.").addOption(Ur).addOption(Br).addArgument(Ex).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Q,i=new Xe({baseUrl:n,apiKey:t,logger:o});await kc({consoleLogger:E,resultsPath:r,client:i}),process.exit(0)});var e_=Ft.command("quarantine").description("Manage test quarantines");e_.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(Ur).addOption(Br).addOption(or).addOption(Aa).addOption(jh).addArgument($h).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=Q,l=Tt({configFilePath:o}),c=new Xe({baseUrl:n,apiKey:t,logger:a}),s=await Zn(Q,c,l);await Rx({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});e_.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(Ur).addOption(Br).addOption(or).addOption(Aa).addOption(jh).addArgument($h).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=Q,l=Tt({configFilePath:o}),c=new Xe({baseUrl:n,apiKey:t,logger:a}),s=await Zn(Q,c,l);await Ax({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});async function fG(){nf("Main program started"),await kx(Q),nf("CLI version check complete");try{await Ft.parseAsync(process.argv)}catch(r){let e={};try{e.playwrightVersion=sG("npx playwright --version").toString()}catch(t){Q.error({err:t},"Error fetching debug information")}Q.error({err:r,debugInfo:e},"Uncaught error in CLI"),Q.flush(),Ia(r,e),E.error(r),process.exit(1)}}cG.setMaxListeners(50);process.on("warning",r=>{Q.warn({err:r},`Node warning received on CLI: ${r.message}`)});nf("CLI parsing setup complete");fG();
4176
+ `),r.forEach(p=>{if(!tf.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let m,g;try{m=tf.statSync(p),g=m.isDirectory()}catch(f){l.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=rf.resolve(p);Object.values(e.tests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(l.info(`Reading all tests from the project and running those matching the following substring filters:
4177
+ ${r.map(p=>`${st}- ${p}`).join(`
4178
+ `)}`),Object.values(e.tests).forEach(p=>{r.some(m=>p.relativePath.includes(m))&&c.add(p.fullFilePath)}))}else{!n&&!await Nt("No test paths or substrings were provided. Do you want to run all tests?")&&(l.error("Cancelled by user."),process.exit(1));let u=Object.values(e.tests);l.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=rf.relative(t.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 s=Array.from(c).map(async u=>{try{let d=await rt(u,Q,e);if(aG.gt(d.schemaVersion,ie)&&l.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:rf.relative(t.rootDir,u)}}catch(d){l.error(`Failed to read and resolve test at '${u}': ${d}`),process.exit(1)}});return Promise.all(s).then(oG)}function Jx({testDefinitions:r,quarantinedTestReasons:e,onlyQuarantined:t=!1,skipQuarantined:n=!1}){if(t){let[u,d]=xd(r,g=>g.id in e),[p,m]=xd(u,g=>g.disabled||n);return{testsToSkip:p,quarantinedTestsToSkip:[],testsToRun:m,quarantinedTestsToRun:[]}}let[o,i]=xd(r,u=>u.disabled),[a,l]=xd(i,u=>u.id in e);return{testsToSkip:o,testsToRun:l,quarantinedTestsToRun:n?[]:a,quarantinedTestsToSkip:n?a:[]}}function Qx({testsToRun:r,quarantinedTestsToRun:e,quarantinedTestReasons:t,testInputMatrix:n}){let o=[],i=(a,l,c)=>{n?n.forEach((s,u)=>{o.push({inputs:s,inputIndex:u,testDefinition:a,quarantined:l,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:a,quarantined:l,quarantinedReason:c})};return r.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,t[a.id])),o}import{partition as sG}from"lodash-es";function Id(r){return r.length===1?"test":"tests"}function Zx(r){return r===1?"1 worker":`${r} workers`}function e_(r){r.length!==0&&(T.info(`Skipping ${r.length} disabled ${Id(r)}:`),r.forEach(e=>{T.info(`${st}- ${[e.relativeFilePath]}`)}),T.log(""))}function t_(r,e){r.length!==0&&(T.info(`Skipping ${r.length} quarantined ${Id(r)}:`),r.forEach(t=>{T.info(`${st}- ${[t.relativeFilePath]}: ${e[t.id]}`)}),T.log(""))}function lG(r,e){r.length!==0&&(T.info(`Running ${r.length} quarantined ${Id(r)} with ${Zx(e)}:`),r.forEach(t=>{T.info(`${st}- ${[t.testDefinition.relativeFilePath]}${typeof t.inputIndex=="number"?` with input set ${t.inputIndex}`:""}`)}),T.log(""))}function cG(r,e,t){e.length===0&&r.length>0||(T.info(`Running ${e.length} ${Id(e)} with ${Zx(t)}:`),e.forEach(n=>{T.info(`${st}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),T.log(""))}function r_({logger:r,localTestsToRunWithInputs:e,parallel:t,shardCount:n,shardIndex:o}){r.info({tests:e.length,shardCount:n,shardIndex:o,parallel:t},"Running local tests");let[i,a]=sG(e,l=>l.quarantined);lG(i,t),cG(i,a,t)}import{cloneDeep as Ia}from"lodash-es";async function n_({orgId:r,codeEvalTools:e,logger:t,outputDefinitions:n,testContext:o,flagStore:i}){let a={};for(let l of n){let{name:c,value:s}=l;a[c]=await er({orgId:r,s,localTools:e,logger:t,context:o})}return a}async function o_({baseUrl:r,envName:e,testName:t,devicePixelRatio:n,apiClient:o,test:i,storageClient:a,codeEvalTools:l,generator:c,orgId:s,variables:u,logger:d,customHeaders:p,testInputs:m,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,flagStore:E}){let S=await qc({settings:g,customHeaders:p,envVariables:u,envName:e,testName:t,baseUrl:r,logger:d,localTools:l,orgId:s}),y={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:Q},A=E.isBooleanFlagEnabled("icon_knowledge_base")?await a.fetchIconKnowledgeBase(d):null,R=S.browserType??"Chromium";if(!xE(R)){let M=`Browser ${R} 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...`;T.warn(M),Q.warn(M)}let w=await yr.init({baseUrl:r,logger:d,userBrowserSettings:S,storage:a,flagStore:E,enricher:new Yn(y,c),contextArgs:{viewport:i.advanced.viewport??Mt,locale:i.advanced.locale??Un,geolocation:i.advanced.geolocation??zn,timezoneId:i.advanced.timezone??Bn,colorScheme:i.advanced.colorScheme,deviceScaleFactor:n},iconKnowledgeBase:A}),x=new uo({browser:w,generator:c,logger:d,orgId:s,options:{scratchPadId:void 0,slowMoMs:S.slowMoMs,autoFollowNewTabs:S.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??E.isBooleanFlagEnabled("rag_v2")},storage:a,flagStore:E,localCodeEvalTools:l,visualDiffScreenshotStorage:f}),_=new qt({baseUrl:r,currentUrl:x.browser.url(),variablesFromEnvironment:u,envName:e,testName:t});return i.parameters&&await Promise.all(i.parameters.map(async M=>{let{name:K,defaultValue:$,required:k}=M,Y=m?.[K];k&&Y===void 0&&(T.error(`Required parameter '${K}' is required by test '${i.name}' but not provided`),process.exit(1));let I=await er({orgId:s,s:Y??$,localTools:l,logger:d,context:qt.dummyContext(_.getEnvName())});_.setMomenticSystemVariable(K,I)})),{controller:x,context:_}}async function i_({testAdvancedSettings:r,orgSettings:e,logger:t}){if(r.failureRecovery===!1||r.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!La){let n="This test is ineligible for failure recovery since this does not appear to be a CI environment";return t.warn(n),T.warn(n),!1}return!0}async function a_({attemptInputs:r,attemptFixtures:e,attemptMetadata:t}){let{orgId:n,runId:o}=t,{controller:i,context:a,codeEvalTools:l,storageClient:c,logger:s,usageTracker:u,tracer:d}=e,{test:p,orgSettings:m}=r;s.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:s,codeEvalTools:l},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 i_({testAdvancedSettings:p.advanced,orgSettings:m.ai,logger:s})};return await Wc({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:d}})}async function s_(r){let{testDefinition:e,logger:t}=r,n=new Date;try{return await uG(r)}catch(o){let i="Fatal error running test";return T.error(`${i}: ${o.message}`),t.error({err:o},i),{results:[],parameters:r,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 uG(r){let{testDefinition:e,project:t,apiClient:n,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:l,logger:c,gitMetadata:s,alwaysSaveCache:u,noCache:d,runId:p,testInputs:m,quarantined:g,quarantinedReason:h,usageTracker:f}=r,E=new Gi(n,o),S=Yi({orgId:o,client:n,gitMetadata:s,alwaysSaveCache:u,noCache:d}),y=Ia(e.steps),A=Ia(e.beforeSteps)??void 0,R=Ia(e.afterSteps)??void 0;try{await S.resolveStepCacheEntries({testId:e.id,stepLists:{steps:y,beforeSteps:A,afterSteps:R},schemaVersion:e.schemaVersion,logger:c})}catch(k){throw c.error({err:k},"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: ${k}`)}let w=r.envName??pG(e),x,_={};if(w){try{x=Rs(w,t,c)}catch(k){let Y=`Failed to resolve environment ${w} for test ${e.name}: ${k}`;throw new Error(Y)}_=x.variables}let M=e.baseUrl;if(i)M=i;else if(!M){let k=_[ht];typeof k=="string"&&(M=k)}if(!M){let k=`Cannot run test with no base URL and no ${ht} variable defined in its environment`;throw new Error(k)}let K=await l.startRun({logger:c,runId:p,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:M,environmentName:w,schemaVersion:e.schemaVersion,resolvedInputs:m,quarantined:g,quarantinedReason:h}),$=c.child(K.loggerBindings||{});Object.entries(K.envVarBindings||{}).forEach(([k,Y])=>{_[k]=Y});try{let k=await dG({...r,variables:_,envName:w,resolvedEnv:x,baseUrl:M,storageClient:E,tracer:K,logger:$,cacheStorage:S,stepsWithCaches:y,beforeStepsWithCaches:A,afterStepsWithCaches:R,usageTracker:f});return await K.finish({logger:c,status:k.status,finishedAt:k.finishedAt,failureDetails:k.failureDetails,failureReason:k.failureReason,isFlake:k.isFlake,failureRecoveryDetails:k.failureRecoveryDetails}),{runId:K.runId,...k}}finally{a?.pop()}}async function dG(r){let{testDefinition:e,stepsWithCaches:t,beforeStepsWithCaches:n,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:l,generator:c,baseUrl:s,storageClient:u,orgId:d,envName:p,urlOverride:m,customHeaders:g,testInputs:h,variables:f,resolvedEnv:E,retriesOverride:S,devicePixelRatio:y,logUpdate:A,tracer:R,logger:w,flagStore:x,cacheStorage:_,gitMetadata:M,quarantined:K,quarantinedReason:$,usageTracker:k}=r,Y=i.config.ai?.aiFailureAnalysis??!1,I=new Date,j=new na(i,a),ue={...i.config},re={envName:p,urlOverride:m,customHeaders:g,testInputs:h},Re,He=Math.abs(S??i.config.retries??e.retries??0),Ar=[];w.info({...M,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let nt=0;nt<=He;nt++){let ne=await R.startAttempt(),xe=w.child(ne.loggerBindings||{}),Ge={...e,steps:Ia(t),beforeSteps:Ia(n),afterSteps:Ia(o)};nt!==0&&A("RETRY",`attempt ${nt+1}/${He+1}`);let wr=new Date,fi=ue.advanced?.fakerConstantSeed??x.isBooleanFlagEnabled("faker_constant_seed"),Ma=new Yr({httpClient:new Rt({baseUrl:l.baseUrl,apiKey:l.apiKey,logger:xe}),fakerSeed:fi?Ui:void 0}),Ld=ne;try{let{controller:Ut,context:Cr}=await o_({baseUrl:s,envName:p,testName:Ge.name,apiClient:l,devicePixelRatio:y,logger:xe,storageClient:u,codeEvalTools:Ma,test:Ge,generator:c,orgId:d,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...i.config.browser||{},...E?.browser||{},...Ge.advanced},aiSettings:{...i.config.ai||{},...Ge.advanced||{}},visualDiffScreenshotStorage:j,flagStore:x});Re=await a_({attemptMetadata:{attemptNumber:nt+1,orgId:d,runId:R.runId},attemptFixtures:{logger:xe,storageClient:u,usageTracker:k,codeEvalTools:Ma,flagStore:x,apiClient:l,context:Cr,controller:Ut,tracer:ne},attemptInputs:{test:Ge,orgSettings:ue}});let To=new Date,zr={logger:w,cacheStorage:_,orgId:d,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:Ge.steps,beforeSteps:Ge.beforeSteps,afterSteps:Ge.afterSteps}};Re?.status==="PASSED"?await fc(zr):Re?.status==="FAILED"&&await Sc(zr),await ne.finish({logger:xe,result:Re}),Ar.unshift(Re.status);let G=await n_({orgId:d,codeEvalTools:Ma,logger:xe,outputDefinitions:e.outputs??[],testContext:Cr,flagStore:x}),In=eS(Ar),Si=nt+1;if(Re.status!=="FAILED")return{...Re,parameters:re,test:Ge,filePath:Ge.relativeFilePath,startedAt:I,lastAttemptStartedAt:wr,finishedAt:To,attempts:Si,baseUrl:s,outputs:G,isFlake:In,quarantined:K,quarantinedReason:$};let yi=Re.failedStepResult,un=yi?.message||"Unknown failure",xr=yi?.failureReason??XS(un)??"UnknownError",Nd=xe.child({errResult:yi,failureReason:xr,errorMessage:un,numAttempts:He+1,name:Ge.name});if(nt<He){Nd.warn(`Retrying failed execution attempt for run: ${un}`);continue}Nd.error(`Test failed after all exhausting attempts: ${un}`);let ll=new Error(un),xt={errorMessage:un,errorStack:ll.stack},bo;if(Y){let Pn;try{if(Re.results&&Re.results.length>0){let{classification:bt,aiFailureReason:dn}=await xT({logger:xe,browserStateStorage:Ld,generator:c,fullResults:Re,failureReason:xr,error:ll,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Pn=bt,bo=dn}}catch(bt){xe.warn({err:bt},"Failed to classify test results")}Pn&&(xt.classification=Pn,xr=bo??xr)}return{...Re,parameters:re,failureDetails:xt,failureReason:xr,test:Ge,filePath:Ge.relativeFilePath,startedAt:I,lastAttemptStartedAt:wr,finishedAt:To,attempts:nt+1,baseUrl:s,outputs:G,quarantined:K,quarantinedReason:$}}catch(Ut){Oa(Ut);let Cr=`Encountered fatal platform error while running test '${Ge.name}': ${Ut}`,To=new Date,zr=nt+1;xe.error({err:Ut},Cr),T.error(Cr);let G={errorMessage:Ut.message,errStack:Ut.stack},In={status:"FAILED",failureDetails:G,failureReason:"InternalPlatformError",finishedAt:To};return await ne.finish({logger:xe,result:{status:"FAILED",results:[]}}),{...In,results:[],parameters:re,test:Ge,filePath:Ge.relativeFilePath,startedAt:I,lastAttemptStartedAt:wr,finishedAt:new Date,attempts:zr,baseUrl:s,outputs:{},quarantined:K,quarantinedReason:$}}}throw new Error("This code should not be reachable")}function pG(r){for(let e of r.envs??[])if(e.default)return e.name}import{randomUUID as mG}from"crypto";var Eo="assets";function gG(r){switch(r){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function hG(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var nf=class{constructor(e,t,n,o,i){this.orgId=e;this.testId=t;this.testName=n;this.metadata=o;this.diskStorage=i}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.jpeg`,contents:n})}attachBeforeHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.beforeSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.html`,contents:n})}attachAfterHtmlSnapshot(e){let{snapshotId:t,html:n}=e;this.metadata.afterSnapshotId=t,this.diskStorage.storeFile({name:`${Eo}/${t}.html`,contents:n})}heal(e){let{healType:t}=e;this.metadata.healMetadata={healType:t,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finish({status:hG(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new Pa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Pa=class{constructor(e,t,n,o){this.orgId=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;stepFrequenciesByType={};async getScreenshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.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,t]of Object.entries(this.stepFrequenciesByType))Rr.increment("test_step_execution",t,[`type:${e}`,`orgId:${this.orgId}`])}async startStep(e){let{step:t}=e;this.recordStepStat(t);let n={step:t,status:"RUNNING",startedAt:new Date},o=new nf(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(t=>t.finishInternal({status:gG(e.status),finishedAt:e.finishedAt}))),this.sendFinalizedStepStats())}},of=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(t,null,2)})}attachConsoleLogs(e){let{logs:t}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(t,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,result:n}=e,o={...this.metadata,status:n.status,finishedAt:new Date,results:vc(n.results,t),beforeResults:n.beforeResults?vc(n.beforeResults,t):void 0,afterResults:n.afterResults?vc(n.afterResults,t):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new Pa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Pa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Pa(this.orgId,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.jpeg`)}async getHtmlSnapshot(e,t){return this.diskStorage.readFile(`${Eo}/${t}.html`)?.toString()}},af=class{constructor(e,t,n,o,i,a){this.orgId=e;this.testId=t;this.testName=n;this.runId=o;this.metadata=i;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[Ab]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let t={...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:t.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(){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 e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),t=mG(),n={id:t,schemaVersion:ie,runAttemptSchemaVersion:pE,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new of(this.orgId,this.testId,this.testName,t,n,e);return this.children.push(o),o}},Pd=class r{constructor(e,t,n,o){this.orgId=e;this.runGroupId=t;this.metadata=n;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,t,n,o,i){let a={...o,id:t,trigger:cr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:_n,labels:i??[]},l=new ws(n);return l.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new r(e,t,a,l)}async finish(e){if(this.finished)return;this.finished=!0;let{status:t}=e,n={...this.metadata,status:t,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 t=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:_n,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new af(this.orgId,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function l_(r,e,t){if(t)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(n){return r.warn({err:n},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function c_(r){let{logger:e,tests:t,yes:n,start:o,waitOn:i,client:a,debugDataStorage:l,flagStore:c,project:s,retriesOverride:u,urlOverride:d,envName:p,orgId:m,devicePixelRatio:g,customHeaders:h,testInputMatrix:f,reporter:E,include:S,exclude:y,labels:A,reporterDir:R=$T,outputDir:w=WT,uploadResults:x=!1,waitOnTimeout:_=60,parallel:M,shardIndex:K=1,shardCount:$=1,regenerateGoldenFiles:k,gitMetadata:Y,alwaysSaveCache:I,noCache:j,ignoreQuarantine:ue,skipQuarantined:re,onlyQuarantined:Re,runGroupId:He}=r;o&&(e.info({orgId:m},`Executing start command: ${o}`),await Yx(o,!1)),i&&(e.info({orgId:m},`Waiting for url: ${i} with timeout: ${_} seconds.`),await yG({resources:[i],interval:2500,timeout:_*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let Ar=new Kn(s.config.ai?.agentConfig,{baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),nt=W(s),ne=await _d({tests:t,momenticFiles:nt,yes:n,project:s,include:S,exclude:y,labels:A,logger:T}),xe=await l_(e,a,ue),{testsToSkip:Ge,quarantinedTestsToSkip:wr,testsToRun:fi,quarantinedTestsToRun:Ma}=Jx({testDefinitions:ne,quarantinedTestReasons:xe,onlyQuarantined:Re,skipQuarantined:re});e_(Ge),t_(wr,xe);let Ld=Qx({testsToRun:fi,quarantinedTestsToRun:Ma,quarantinedTestReasons:xe,testInputMatrix:f}),Ut=TG({globalTestsToRunWithInputs:Ld,shardIndex:K,shardCount:$});r_({logger:e,localTestsToRunWithInputs:Ut,parallel:M,shardCount:$,shardIndex:K});let Cr=[],To=new Date,zr=new Set,G=async()=>{let xt=a.getAppUrl(),bo=Hi({results:Cr,startTime:To.getTime(),onFailed:bt=>{lc(bt,bt.filePath)},getDisplayLine:bt=>{let dn=`${st}- ${bt.filePath}${bt.failureRecoveryDetails?" [recovered] ":""}`;return bt.runId&&(dn+=` ( link when uploaded: ${xt}/runs/${bt.runId} )`),dn},entity:"test"}),Pn=Cr.filter(bt=>!!bt.failureRecoveryDetails?.attempts);return Pn.length>0&&T.warn(`Our AI agent automatically prevented ${Pn.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),T.log(""),x?(T.success(`Test results have been saved to the folder ${w}. Uploading to Momentic Cloud...`),await Bc({client:a,consoleLogger:T,resultsPath:w})):T.success(`Test results have been saved to the folder ${w}. Upload them to Momentic Cloud by running 'npx momentic results upload ${w}'.`),bo};SG.existsSync(w)&&T.warn(`Output directory ${w} already exists, removing before test execution...`);let In=await Pd.start(m,He,w,Y,A),Si=e.child(In.loggerBindings||{}),yi=[],un=async()=>{T.warn("SIGINT received. Stopping tests and printing latest results..."),await In.finish({logger:Si,status:"CANCELLED"}),await G(),await Promise.allSettled(yi.map(xt=>xt())),process.exit(1)};process.once("SIGINT",un);let xr={};for(let xt=0;xt<Ut.length;xt++){let bo=Object.values(xr);bo.length===M&&await Promise.race(bo.map(dn=>dn.promise));let Pn=Ut[xt],bt=`test-${xt}`;xr[bt]={done:!1,promise:(async({inputs:dn,quarantined:h_,quarantinedReason:f_,testDefinition:vo})=>{zr.add({inputs:dn});let cl=vo.relativeFilePath.includes("..")?vo.fullFilePath:vo.relativeFilePath;ps({status:"START",testLogRef:cl,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length});let S_=setInterval(()=>ps({status:"RUN",testLogRef:cl,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length}),5*60*1e3),Dd=fG(),kd=Si.child({testId:vo.id,runId:Dd}),cf=new Pc({logger:kd,reporter:new uc(a),runType:"test-run",runId:Dd,testMetadata:vo,suiteMetadata:void 0});try{let ul=await s_({testDefinition:vo,project:s,testInputs:dn,quarantined:h_,quarantinedReason:f_,orgId:m,runId:Dd,devicePixelRatio:g,apiClient:a,runGroupTracer:In,generator:Ar,retriesOverride:u,urlOverride:d,envName:p,customHeaders:h,regenerateGoldenFiles:k,logUpdate:(dl,y_)=>ps({status:dl,testLogRef:cl,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length,additionalText:y_}),runSigIntHandlers:yi,logger:kd,flagStore:c,gitMetadata:Y,alwaysSaveCache:I,noCache:j,usageTracker:cf});ps({status:ul.status,testLogRef:cl,getRunningTestsCount:()=>zr.size,getTotalTestsCount:()=>Ut.length}),Cr.push(ul)}catch(ul){let dl=`Encountered unexpected fatal error when running test '${vo.name}': ${ul.message}`;T.error(dl),kd.error(dl)}finally{clearInterval(S_),xr[bt].done=!0,delete xr[bt]}await cf.flush(e)})(Pn)}}await Promise.allSettled(Object.values(xr).map(xt=>xt.promise));let ll=Cr.some(xt=>!xt.quarantined&&xt.status==="FAILED")?"FAILED":"PASSED";return await In.finish({logger:Si,status:ll}),process.off("SIGINT",un),E&&await qx(Si,l,E,{projectConfigPath:s.configFilePath,suiteName:s.config.name,startedAt:To,finishedAt:new Date,runs:Cr,testsToSkip:Ge,quarantinedTestsToSkip:wr,quarantinedTestReasons:xe},R),G()}function EG(r,e,t){if(t>r.length&&(T.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.sort().filter((a,l)=>l>=n&&l<o)}function TG({globalTestsToRunWithInputs:r,shardIndex:e,shardCount:t}){return t&&t>1?EG(r,e,t):r}Fd||Q.warn("Sentry is not enabled in this environment due to unsupported node version");Jw({serviceName:"cli"});var xG=process.argv.some(r=>r.includes("--log-level"))&&process.argv.some(r=>r.includes("debug")),sf=r=>{xG&&T.dimmed(r)},Ft=new bG;Ft.name("momentic").description("Momentic CLI").version(_n);Ft.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: ${im.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(T.error("No browsers specified"),process.exit(1)),await _E({rawBrowsers:r,force:e.force,all:e.all})});Ft.addOption(new Jt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{r==="debug"&&T.info("Enabling debug logging"),T.setMinLevel(r.toLowerCase())});Ft.addOption(new Jt("--verbose","enable verbose logging")).on("option:verbose",()=>{Q.enableConsoleLogs(),T.setMinLevel(20)});var lf=Ft.command("checks").alias("check").description("Perform various project checks");lf.command("config").addOption(or).action(async r=>{Et({configFilePath:r.config})});lf.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(or).addOption(wx).action(async r=>{let e=Et({configFilePath:r.config});await dx({project:e,fix:r.fix})});lf.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(or).action(async r=>{let e=Et({configFilePath:r.config});await px({project:e})});var d_=Ft.command("migrate").description("Migrate and upgrade tooling");d_.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(or).action(async r=>{let e=Et({configFilePath:r.config});await Nx(e)});d_.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(Br).addOption(or).addOption(Ur).addOption(yo).action(async r=>{!r.yes&&!await Nt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=Et({configFilePath:r.config}),t=new Je({baseUrl:r.server,apiKey:r.apiKey,logger:Q}),{orgId:n}=await t.getAuthInfo();await kx({project:e,orgId:n,apiClient:t}),process.exit(0)});Ft.command("import").addOption(Ur).addOption(Br).addOption(or).addOption(yo).addArgument(Px).action(async(r,e)=>{let{apiKey:t,server:n,config:o,yes:i}=e,a=Et({configFilePath:o}),l=new Je({baseUrl:n,apiKey:t,logger:Q});!r||r.length===0?await Sx({client:l,project:a,skipPrompts:i}):await yx({client:l,project:a,paths:r,skipPrompts:i}),process.exit(0)});Ft.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Jt("--name <name>","Name of the project")).action(async r=>{T.info(`Welcome to the Momentic project setup wizard! \u{1F680}
4179
+ `),T.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."),Od.existsSync(ea)&&(T.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 t={name:r.name??await RE("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:_m};ta(t,ea),T.success(`Initialized Momentic project file at ${Md.resolve(ea)}`)});Ft.command("app").addOption(Ur).addOption(Br).addOption(yo).addOption(Gh).addOption(or).addOption(jh).addOption($h).action(async r=>{let{apiKey:e,yes:t,server:n,pixelRatio:o,disableCache:i,saveCache:a}=r,l=Et({configFilePath:r.config,nameFilter:void 0}),{errors:c}=await gd({project:l,fix:!1});c>0&&(T.error(`Found ${c} errors`),T.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 s=new Je({baseUrl:n,apiKey:e,logger:Q});await um({client:s,skipPrompts:t});let u=CG(import.meta.url),d=Md.dirname(u),p=Md.resolve(d,"..","static"),m=Md.resolve(d,"..","assets"),g=o??Qh();Zh(g),await sx({momenticServerUrl:n,apiKey:e,serverPort:hd,appPort:hd,staticDir:p,assetsDir:m,devicePixelRatio:g,noCache:i,alwaysSaveCache:a,initialProject:l});let h=`http://localhost:${hd}`;await wG(h)});var p_=Ft.command("queue").description("Queue tests or suites to run on Momentic Cloud");p_.command("suites").description("Run one or more suites on Momentic Cloud").addOption(Ur).addOption(Br).addOption(Fh).addOption(Uh).addOption(yo).addArgument(Mx).addOption(Ed).addOption(yd).addOption(Sd).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:i,env:a,urlOverride:l}=e,c=fd(e.customHeaders),s=new Je({baseUrl:n,apiKey:t,logger:Q});(!r||!Array.isArray(r)||!r.length)&&(T.error("Must pass at least one suite to run."),process.exit(1));let{orgId:u}=await s.getAuthInfo();await zx({client:s,orgId:u,wait:o,suitePaths:r,waitTimeout:i,env:a,urlOverride:l,customHeaders:c})});p_.command("tests").description("Run one or more tests on Momentic Cloud").addOption(Ur).addOption(Br).addOption(yo).addOption(Sd).addOption(Vh).addOption(Ed).addOption(yd).addOption(new Jt("--all","Run all tests.").default(!1)).addOption(Fh).addOption(Uh).addArgument(Ix).action(async(r,e)=>{let{all:t,apiKey:n,env:o,server:i,inputCsv:a,urlOverride:l,wait:c,waitTimeout:s,yes:u}=e,d=fd(e.customHeaders);for(let h of r)(h.endsWith(".yaml")||Od.existsSync(h))&&T.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 Je({baseUrl:i,apiKey:n,logger:Q}),{orgId:m}=await p.getAuthInfo(),g;a&&(g=await ef(a)),await Hx({client:p,orgId:m,tests:r,all:t,customHeaders:d,env:o,urlOverride:l,wait:c,waitTimeout:s,testInputMatrix:g,yes:u}),process.exit(0)});var _G=Ft.command("list").description("List test paths");_G.addOption(or).addOption(xa).addOption(zh).addOption(Hh).addOption(new Jt("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(Wh).action(async(r,e)=>{let t=Et({configFilePath:e.config,nameFilter:e.filter}),n=W(t),o=await _d({tests:r,momenticFiles:n,yes:!0,project:t,include:e.include,exclude:e.exclude,labels:e.labels,logger:new as(40,{})});T.info(o.map(i=>i.relativeFilePath).join(`
4180
+ `)),process.exit(0)});var IG=Ft.command("run").alias("test").description("Run tests on the local machine");IG.addOption(Ur).addOption(Br).addOption(or).addOption(xa).addOption(yo).addOption(Sd).addOption(Vh).addOption(jh).addOption($h).addOption(Cx).addOption(xx).addOption(_x).addOption(yd).addOption(Ed).addOption(Gh).addOption(new Jt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Jt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Jt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(So)).addOption(new Jt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(So)).addOption(new Jt("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(So)).addOption(new Jt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Jt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(Tx).addOption(bx).addOption(Bh).addOption(vx).addOption(Ax).addOption(Rx).addOption(zh).addOption(Hh).addArgument(Wh).action(async(r,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let t=fd(e.customHeaders),n=Et({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??n.config.parallel??1;u_().length<o*2&&T.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${u_().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),T.debug({projectName:n.config.name},"Identified project config");let{errors:i}=await gd({project:n,fix:!1});i>0&&(T.error(`Found ${i} errors`),T.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),await Rr.flush(),process.exit(1));let a=new Je({baseUrl:e.server,apiKey:e.apiKey,logger:Q});T.debug("Checking API key and dependencies");let{orgId:l,userId:c}=await um({client:a,skipPrompts:e.yes});T.debug("API key check and browser installation complete");let s=new es,u=e.outputDir??n.config.outputDir,d=e.reporterDir??n.config.reporterDir,p=RG(),m=Q.child({runGroupId:p,orgId:l,cliVersion:_n}),g=await Qn(Q,a,n);m.info({userId:c,...g},"Got local git metadata");let h=new Jr(n.config),f;e.inputCsv&&(f=await ef(e.inputCsv));let E=e.pixelRatio??Qh();Zh(E);try{let S=await c_({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:E,tests:r,project:n,client:a,debugDataStorage:s,flagStore:h,outputDir:u,uploadResults:e.uploadResults,reporterDir:d,customHeaders:t,envName:e.env,orgId:l,testInputMatrix:f,logger:m,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:g,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:p});await Rr.flush(),S.failed>0?process.exit(1):process.exit(0)}catch(S){T.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),T.error(S),await Rr.flush(),process.exit(1)}});var PG=Ft.command("apply").description("Apply an operation to local resources");PG.command("patch").addOption(Ur).addOption(Br).addOption(or).addOption(xa).addOption(yo).addOption(new Jt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Jt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async r=>{let{apiKey:e,server:t,config:n,yes:o}=r,i=Et({configFilePath:n}),a=Q,l=new Je({baseUrl:t,apiKey:e,logger:a}),c=W(i),s=c.tests[r.to]??Object.values(c.tests).find(d=>_e(d.name)===r.to.trim());s||(T.error(`No test matching '${r.to}' could be found in the current project.`),process.exit(1));let u=await l.fetchTestFragment(r.from);await cx({client:l,test:s,fragment:u,yes:o,entities:c,logger:Q}),process.exit(0)});var m_=Ft.command("results").description("Merge and upload test results.");m_.command("merge").description("Merge test results files.").addOption(Bh).addArgument(Ox).action(async(r,e)=>{let{outputDir:t}=e;t||(T.error("Output directory is required."),process.exit(1)),Od.existsSync(r)||(T.warn("Results path does not exist, skipping merge."),process.exit(0)),Od.existsSync(t)&&T.warn(`Output directory ${t} already exists, removing before merging...`),XT(Q,t,r)});m_.command("upload").description("Upload test results to Momentic cloud.").addOption(Ur).addOption(Br).addArgument(Lx).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=Q,i=new Je({baseUrl:n,apiKey:t,logger:o});await Bc({consoleLogger:T,resultsPath:r,client:i}),process.exit(0)});var g_=Ft.command("quarantine").description("Manage test quarantines");g_.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(Ur).addOption(Br).addOption(or).addOption(xa).addOption(qh).addArgument(Kh).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=Q,l=Et({configFilePath:o}),c=new Je({baseUrl:n,apiKey:t,logger:a}),s=await Qn(Q,c,l);await Fx({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});g_.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(Ur).addOption(Br).addOption(or).addOption(xa).addOption(qh).addArgument(Kh).action(async(r,e)=>{let{apiKey:t,server:n,config:o,reason:i}=e,a=Q,l=Et({configFilePath:o}),c=new Je({baseUrl:n,apiKey:t,logger:a}),s=await Qn(Q,c,l);await Ux({test:r,reason:i,apiClient:c,project:l,logger:a,identity:s})});async function MG(){sf("Main program started"),await Xx(Q),sf("CLI version check complete");try{await Ft.parseAsync(process.argv)}catch(r){let e={};try{e.playwrightVersion=vG("npx playwright --version").toString()}catch(t){Q.error({err:t},"Error fetching debug information")}Q.error({err:r,debugInfo:e},"Uncaught error in CLI"),Q.flush(),Oa(r,e),T.error(r),process.exit(1)}}AG.setMaxListeners(50);process.on("warning",r=>{Q.warn({err:r},`Node warning received on CLI: ${r.message}`)});sf("CLI parsing setup complete");MG();
4141
4181
  //# sourceMappingURL=cli.js.map
4142
- //# debugId=54b84a56-febc-5edb-b704-618fc9fa3bc2
4182
+ //# debugId=5c578492-ad0b-5b1b-a1ed-310b5ae0f7d0