momentic-mobile 0.9.1 → 0.9.2
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 +20 -20
- package/npm-shrinkwrap.json +65 -130
- package/package.json +1 -1
- package/static/assets/{index-LYuRkbHC.js → index-a9ES5CBa.js} +1 -1
- package/static/index.html +1 -1
package/bin/cli.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var EM=Object.defineProperty;var We=(r,e)=>()=>(r&&(e=r(r=0)),e);var TM=(r,e)=>{for(var t in e)EM(r,t,{get:e[t],enumerable:!0})};var TE,vE=We(()=>{"use strict";TE=typeof globalThis=="object"?globalThis:global});var AE=We(()=>{"use strict";vE()});var wE=We(()=>{"use strict";AE()});var en,Pm=We(()=>{"use strict";en="1.9.0"});function dN(r){var e=new Set([r]),t=new Set,n=r.match(CE);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(s){return t.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var l=c.match(CE);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var CE,RE,xE=We(()=>{"use strict";Pm();CE=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;RE=dN(en)});function ci(r,e,t,n){var o;n===void 0&&(n=!1);var i=ka[Da]=(o=ka[Da])!==null&&o!==void 0?o:{version:en};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!==en){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+en);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+en+"."),!0}function tn(r){var e,t,n=(e=ka[Da])===null||e===void 0?void 0:e.version;if(!(!n||!RE(n)))return(t=ka[Da])===null||t===void 0?void 0:t[r]}function ui(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+en+".");var t=ka[Da];t&&delete t[r]}var mN,Da,ka,Ua=We(()=>{"use strict";wE();Pm();xE();mN=en.split(".")[0],Da=Symbol.for("opentelemetry.js.api."+mN),ka=TE});function Fa(r,e,t){var n=tn("diag");if(n)return t.unshift(e),n[r].apply(n,gN([],pN(t),!1))}var pN,gN,ME,_E=We(()=>{"use strict";Ua();pN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gN=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))},ME=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 Fa("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("verbose",this._namespace,e)},r}()});var Ue,Bl=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"})(Ue||(Ue={}))});function PE(r,e){r<Ue.NONE?r=Ue.NONE:r>Ue.ALL&&(r=Ue.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",Ue.ERROR),warn:t("warn",Ue.WARN),info:t("info",Ue.INFO),debug:t("debug",Ue.DEBUG),verbose:t("verbose",Ue.VERBOSE)}}var IE=We(()=>{"use strict";Bl()});var hN,fN,SN,kr,Ba=We(()=>{"use strict";_E();IE();Bl();Ua();hN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},fN=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))},SN="diag",kr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=tn("diag");if(s)return s[o].apply(s,fN([],hN(i),!1))}}var t=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:Ue.INFO}),o===t){var l=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=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=tn("diag"),d=PE((s=i.logLevel)!==null&&s!==void 0?s:Ue.INFO,o);if(u&&!i.suppressOverrideMessage){var m=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+m),d.warn("Current logger will overwrite one already registered from "+m)}return ci("diag",d,t,!0)};t.setLogger=n,t.disable=function(){ui(SN,t)},t.createComponentLogger=function(o){return new ME(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 OE,LE=We(()=>{"use strict";OE=Symbol("BaggageEntryMetadata")});function Im(r){return typeof r!="string"&&(yN.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:OE,toString:function(){return r}}}var yN,NE=We(()=>{"use strict";Ba();LE();yN=kr.instance()});function Om(r){return Symbol.for(r)}var bN,Lm,Nm=We(()=>{"use strict";bN=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}(),Lm=new bN});function Um(){return km}var co,EN,zl,TN,vN,AN,wN,Dm,CN,RN,xN,km,MN,_N,PN,IN,ON,LN,NN,Fm=We(()=>{"use strict";co=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)}}(),EN=function(){function r(){}return r.prototype.createGauge=function(e,t){return _N},r.prototype.createHistogram=function(e,t){return PN},r.prototype.createCounter=function(e,t){return MN},r.prototype.createUpDownCounter=function(e,t){return IN},r.prototype.createObservableGauge=function(e,t){return LN},r.prototype.createObservableCounter=function(e,t){return ON},r.prototype.createObservableUpDownCounter=function(e,t){return NN},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),zl=function(){function r(){}return r}(),TN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(zl),vN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(zl),AN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(zl),wN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(zl),Dm=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),CN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dm),RN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dm),xN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dm),km=new EN,MN=new TN,_N=new AN,PN=new wN,IN=new vN,ON=new CN,LN=new RN,NN=new xN});var jt,DE=We(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(jt||(jt={}))});var DN,kN,kE,UE=We(()=>{"use strict";Nm();DN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},kN=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))},kE=function(){function r(){}return r.prototype.active=function(){return Lm},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,kN([n],DN(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var UN,FN,Bm,BN,FE,BE=We(()=>{"use strict";UE();Ua();Ba();UN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},FN=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))},Bm="context",BN=new kE,FE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return ci(Bm,e,kr.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,FN([e,t,n],UN(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return tn(Bm)||BN},r.prototype.disable=function(){this._getContextManager().disable(),ui(Bm,kr.instance())},r}()});var di,zE=We(()=>{"use strict";BE();di=FE.getInstance()});var H,HE=We(()=>{"use strict";Ba();H=kr.instance()});var zN,GE,VE=We(()=>{"use strict";Fm();zN=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return km},r}(),GE=new zN});var zm,WE,jE=We(()=>{"use strict";VE();Ua();Ba();zm="metrics",WE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return ci(zm,e,kr.instance())},r.prototype.getMeterProvider=function(){return tn(zm)||GE},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){ui(zm,kr.instance())},r}()});var Hl,$E=We(()=>{"use strict";jE();Hl=WE.getInstance()});var Me=We(()=>{"use strict";NE();Nm();Bl();Fm();DE();zE();HE();$E()});import{Argument as Lh,Command as WG,Option as jG}from"@commander-js/extra-typings";import I0 from"appium";import{execSync as O0}from"child_process";import{z as qu}from"zod";var tV=qu.object({input:qu.string(),agentConfigVersion:qu.string().optional()});import{z as st}from"zod";var oV=st.object({srcs:st.array(st.string()),urls:st.array(st.string()),desiredSrc:st.string().optional(),desiredUrl:st.string().optional()}),kh=st.object({srcRegex:st.string().optional(),urlRegex:st.string().optional()}),Uh=st.object({x:st.number(),y:st.number(),correlation:st.number()}),iV=st.object({searchImageBase64String:st.string(),pageImageBase64String:st.string(),id:st.string().uuid(),timeoutMs:st.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as vM}from"zod-openapi";vM(L);var dn=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(dn||{}),AM=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),Ku=L.object({result:L.number(),traceId:L.string()}).array(),Ls=L.object({type:L.literal("GCS_TRACES"),traces:Ku}),un=(o=>(o.Precise="precise",o.Narrow="narrow",o.Unspecific="broad",o.Irrelevant="irrelevant",o))(un||{}),Fh=L.object({attributes:L.record(L.string(),L.string()).optional(),text:L.string().optional(),position:L.object({x1:L.number(),y1:L.number(),x2:L.number(),y2:L.number(),tolerance:L.nativeEnum(un)}).optional(),shape:L.object({width:L.number(),height:L.number(),tolerance:L.nativeEnum(un)}).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),wM=L.object({selectors:L.string().array(),requirements:Fh.optional()}),mn=L.object({id:L.number().int(),dataMomenticId:L.number().int().optional(),selector:L.string().optional(),hybridSelector:L.object({textContent:L.string().nullish(),attributes:L.record(L.string(),L.string().optional()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:Fh.optional(),additionalElements:wM.array().optional(),role:L.string().optional(),name:L.string().optional(),numChildren:L.number().optional(),content:L.string().optional(),pathFromRoot:L.string().optional(),serializedHtml:L.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:L.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:L.string().url().optional(),boundingBox:L.object({x:L.number().optional(),y:L.number().optional(),width:L.number(),height:L.number()}).describe("css pixel bounding box").optional(),frameCache:AM.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(dn).optional(),targetUpdateTime:L.string().optional(),targetUpdateLoggerTags:L.record(L.string(),L.string()).optional(),cacheResolutionUpdateSource:L.string().optional(),cacheResolutionUpdateTime:L.string().optional(),cacheResolutionUpdateLoggerTags:L.record(L.string(),L.string()).optional(),memory:Ls.optional()}).openapi({ref:"ElementTargetCache"});function Ns(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var CM=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),RM=L.object({x:L.number(),y:L.number()}),xM=L.object({type:L.literal("coordinates"),pixels:RM}).openapi({ref:"CoordinatesTarget"});function pn(r){return r.type==="description"}function xr(r){return r.type==="coordinates"}var At=L.discriminatedUnion("type",[CM,xM]).openapi({ref:"ElementTarget"});function Yu(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Bh(r){return Ls.safeParse(r).success}import{v4 as Ee}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as FM}from"zod-openapi";import{z as ce}from"zod";import{extendZodWithOpenApi as MM}from"zod-openapi";import{z as Ki}from"zod";import zh from"zod";var qi=zh.object({updatedAt:zh.coerce.date().optional()});var Xu=Ki.object({result:Ki.boolean(),traceId:Ki.string()}).array(),Ju=Ki.object({type:Ki.literal("GCS_TRACES"),traces:Xu}),Qu=qi.extend({memory:Ju.optional()});MM(ce);var Hh=ce.object({thoughts:ce.string(),result:ce.boolean(),relevantElements:ce.array(ce.number()).optional(),updatedMemory:Xu.optional()}),Kt=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Kt||{});var _M=ce.object({type:ce.literal("ELEMENT_NAME"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),value:ce.string()}).openapi({ref:"ElementNameAssertion"}),PM=ce.object({type:ce.literal("ELEMENT_STYLE"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),property:ce.string(),value:ce.string()}).openapi({ref:"ElementStyleAssertion"}),IM=ce.object({type:ce.literal("ELEMENT_CONTENT"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),value:ce.string()}).openapi({ref:"ElementContentAssertion"}),OM=ce.object({type:ce.literal("ELEMENT_ATTRIBUTE"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),attr:ce.string(),value:ce.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Mr=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Mr||{});var LM=ce.object({type:ce.literal("ELEMENT_EXISTENCE"),negated:ce.boolean().optional(),condition:ce.nativeEnum(Mr).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Ds=ce.discriminatedUnion("type",[IM,OM,LM,_M,PM]).openapi({ref:"ManualElementAssertion"});var NM=ce.object({type:ce.literal("CONTENT"),negated:ce.boolean().optional(),value:ce.string()}).openapi({ref:"PageContentAssertion"}),Gh=ce.discriminatedUnion("type",[NM]).openapi({ref:"ManualPageAssertion"});import Pt from"zod";var Zu=Pt.discriminatedUnion("type",[Pt.object({type:Pt.literal("SUBSTRING"),url:Pt.string()}),Pt.object({type:Pt.literal("GLOB"),glob:Pt.string()}),Pt.object({type:Pt.literal("REGEX"),regex:Pt.string()}),Pt.object({type:Pt.literal("DOMAIN"),domain:Pt.string()})]),Yi=Pt.object({urlMatcher:Zu,method:Pt.string().optional()});import{z as ie}from"zod";var DM=ie.object({type:ie.literal("json"),content:ie.string().describe("The JSON content to send in the request body")}),kM=ie.object({type:ie.literal("form-urlencoded"),content:ie.record(ie.string(),ie.string()).describe("The form fields to send in the request body")}),UM=ie.discriminatedUnion("type",[DM,kM]),$n=ie.object({url:ie.string(),method:ie.union([ie.literal("GET"),ie.literal("POST"),ie.literal("PUT"),ie.literal("DELETE"),ie.literal("PATCH")]),headers:ie.record(ie.string(),ie.string()).optional(),params:ie.record(ie.string(),ie.string()).optional(),body:UM.optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),Vh=ie.object({url:ie.string(),headers:ie.record(ie.string(),ie.string()).optional(),query:ie.string(),variables:ie.string().optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),ks=ie.object({code:ie.string(),fragment:ie.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:ie.union([ie.literal("NODE"),ie.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:ie.number().int().max(60).optional().describe("Max seconds for the code to complete")});var et=($=>($.AI_EXTRACT="AI_EXTRACT",$.AI_ASSERTION="AI_ASSERTION",$.AUTH_LOAD="AUTH_LOAD",$.AUTH_SAVE="AUTH_SAVE",$.BLUR="BLUR",$.CAPTCHA="CAPTCHA",$.CLICK="CLICK",$.COOKIE="COOKIE",$.COPY="COPY",$.DIALOG="DIALOG",$.DRAG="DRAG",$.ELEMENT_CHECK="ELEMENT_CHECK",$.FILE_UPLOAD="FILE_UPLOAD",$.FOCUS="FOCUS",$.GO_BACK="GO_BACK",$.GO_FORWARD="GO_FORWARD",$.HOVER="HOVER",$.JAVASCRIPT="JAVASCRIPT",$.LOCAL_STORAGE="LOCAL_STORAGE",$.MOUSE_DRAG="MOUSE_DRAG",$.NAVIGATE="NAVIGATE",$.NEW_TAB="NEW_TAB",$.PAGE_CHECK="PAGE_CHECK",$.PASTE="PASTE",$.PRESS="PRESS",$.KEY_DOWN="KEY_DOWN",$.KEY_UP="KEY_UP",$.REFRESH="REFRESH",$.REQUEST="REQUEST",$.GRAPHQL_REQUEST="GRAPHQL_REQUEST",$.SCROLL_DOWN="SCROLL_DOWN",$.SCROLL_UP="SCROLL_UP",$.SCROLL_LEFT="SCROLL_LEFT",$.SCROLL_RIGHT="SCROLL_RIGHT",$.SELECT_OPTION="SELECT_OPTION",$.SWITCH_TAB="TAB",$.TYPE="TYPE",$.VISUAL_DIFF="VISUAL_DIFF",$.WAIT="WAIT",$.WAIT_FOR_URL="WAIT_FOR_URL",$.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="SUCCESS",$))(et||{});FM(y);var X=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),Yt=y.object({useSelector:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Xt=qi.extend({target:mn}).optional().openapi({ref:"SingleTargetCache"});function Wh(r){return Xt.safeParse(r).success}var Us=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),jh=X.merge(Us).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),Fs=Yt.merge(y.object({cache:Xt})),qn=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Kn=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Lo=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),No=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),UV=y.discriminatedUnion("type",[qn,Kn,Lo,No]).openapi({ref:"AllScrollCommands"}),BM=X.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),$h=X.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),zM=y.object({caseInsensitive:y.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:y.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:y.number().int().optional().describe("Max seconds to wait for the URL to match")}),qh=X.extend({type:y.literal("WAIT_FOR_URL"),matcher:Zu}).merge(zM).openapi({ref:"WaitUrlCommand"}),Kh=X.merge(Us).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Yh=X.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Xh=X.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),HM=X.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),GM=X.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),td=X.merge(Yt).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Jh=X.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),Qh=X.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),Zh=X.merge(ks).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Do=X.merge(Yt).extend({type:y.literal("CLICK"),target:At,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForDownload:y.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:y.number().optional(),downloadTimeoutMs:y.number().optional(),cache:Xt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),ef=qi.extend({fromTarget:mn.optional(),toTarget:mn.optional()}),ko=X.merge(Yt).merge(y.object({type:y.literal("DRAG"),fromTarget:At,toTarget:At,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:ef.optional()})).openapi({ref:"DragCommand"}),Uo=X.merge(Yt).merge(y.object({type:y.literal("MOUSE_DRAG"),target:At.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:Xt})).openapi({ref:"MouseDragCommand"}),Fo=X.merge(Yt).merge(y.object({type:y.literal("HOVER"),target:At,cache:Xt})).openapi({ref:"HoverCommand"}),Xi=X.merge(Yt).merge(y.object({type:y.literal("FOCUS"),target:At,cache:Xt})).openapi({ref:"FocusCommand"}),Ji=X.merge(Yt).extend({type:y.literal("BLUR"),target:At.optional(),cache:Xt}).openapi({ref:"BlurCommand"}),VM=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),WM=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),jM=X.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[VM,WM]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),tf=y.discriminatedUnion("type",[y.object({type:y.literal("VALUE"),value:y.string()}),y.object({type:y.literal("LABEL"),label:y.string()}),y.object({type:y.literal("INDEX"),index:y.coerce.string()})]),Bo=X.merge(Yt).extend({type:y.literal("SELECT_OPTION"),target:At,cache:Xt,choice:tf.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),rd=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),Qi=X.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:rd.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Qu.optional()})).openapi({ref:"AIAssertionCommand"}),zt=5,zo=600,Ho=X.merge(Yt).extend({type:y.literal("ELEMENT_CHECK"),target:At,assertion:Ds,cache:Xt.or(Qu).optional(),timeout:y.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),rf=X.extend({type:y.literal("PAGE_CHECK"),assertion:Gh,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),nf=X.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})).openapi({ref:"AIExtractCommand"}),$M=y.object({clearContent:y.boolean().optional(),forceClearContent:y.boolean().optional(),delay:y.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:y.boolean().optional(),pressEnter:y.boolean().optional(),relativePosition:y.object({x:y.number(),y:y.number()}).optional()}),of=25,Go=X.merge(Yt).merge($M).extend({type:y.literal("TYPE"),target:At.optional(),value:y.string(),cache:Xt}).openapi({ref:"TypeCommand"}),af=X.merge(y.object({type:y.literal("PRESS"),value:y.string(),repeat:y.number().optional(),convertMeta:y.boolean().optional(),delayMs:y.number().optional()})).openapi({ref:"PressCommand"}),sf=X.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),lf=X.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),qM=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),KM=y.object({type:y.literal("REGEX"),pattern:y.string()}),YM=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),XM=y.discriminatedUnion("type",[qM,KM,YM]),JM=X.merge(Us).merge(y.object({type:y.literal("TAB"),action:XM})).openapi({ref:"TabCommand"}),cf=X.merge(Us).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),QM=X.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),uf=X.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),df=X.extend({type:y.literal("REQUEST")}).merge($n).openapi({ref:"RequestCommand"}),mf=X.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Vh).openapi({ref:"GraphQLRequestCommand"}),pf=X.merge(y.object({type:y.literal("SUCCESS"),condition:Qi.optional()})).openapi({ref:"SuccessCommand"}),gf=X.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),ZM=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),Zi=X.merge(Yt).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:At.optional(),screenshot:ZM.optional(),cache:Xt})).openapi({ref:"VisualDiffCommand"}),e_=X.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Yi,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),t_=X.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),r_=X.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Yi,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),n_=X.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),o_=X.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Yi.optional()})).openapi({ref:"SetHeaderCommand"}),i_=X.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Yi,responseGenerator:y.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:y.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:y.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"})),a_=X.merge(y.object({type:y.literal("REMOVE_ROUTE_MOCK"),key:y.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),s_=X.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),l_=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],FV=[...l_,"DRAG"],c_=y.discriminatedUnion("type",[Do,Go,af,sf,lf,Bo,jh,Kn,qn,Qi,Yh,Fo,$h]),u_=y.discriminatedUnion("type",[...c_.options,ko]),d_=y.discriminatedUnion("type",[...u_.options]),hf=y.discriminatedUnion("type",[...d_.options,pf]),nd=y.discriminatedUnion("type",[pf,Do,Go,af,sf,lf,Bo,jh,Kn,qn,Qi,Yh,Fo,$h,Zh,Ho,rf,cf,qh,nf,Jh,Xh,uf,ko,Uo,Qh,Kh,df,mf]),m_=y.discriminatedUnion("type",[nf,GM,HM,td,QM,Jh,BM,Ho,jM,Xh,Zh,uf,Uo,cf,rf,Qh,Kh,df,mf,Lo,No,JM,Zi,Xi,Ji,qh,e_,t_,r_,n_,o_,i_,a_,s_]),Vo=y.discriminatedUnion("type",[...hf.options,...m_.options]).openapi({ref:"Command"}),Bs=y.discriminatedUnion("type",[...hf.options,gf]),BV=y.discriminatedUnion("type",[...nd.options,gf]);function Kr(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 ff(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 p_}from"zod";var WV=p_.discriminatedUnion("type",[Ji,td,Do,ko,Xi,Fo,Uo,qn,Kn,Lo,No,Bo,Go,Zi,Ho]);import{z as g_}from"zod";import{z as hn}from"zod";function ea(r){return hn.object({key:hn.string(),testId:hn.string().optional(),moduleId:hn.string().optional(),organizationId:hn.string(),value:r})}function ta(r){return ea(r).extend({uniqueKey:hn.string()})}function zs(r){return hn.record(hn.string(),ta(r))}var It={type:!0,cache:!0},Wo=g_.discriminatedUnion("type",[Qi.pick(It),Ji.pick(It),Do.pick(It),ko.pick(It),Ho.pick(It),Xi.pick(It),Fo.pick(It),Uo.pick(It),qn.pick(It),Kn.pick(It),Lo.pick(It),No.pick(It),Bo.pick(It),Go.pick(It),Zi.pick(It)]),od=Object.values(et).filter(r=>Wo.options.some(e=>e.shape.type.safeParse(r).success));Vo.options.forEach(r=>{if("target"in r.shape&&!od.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function id(r){return od.includes(r.type)}var Sf=ea(Wo),yf=ta(Wo),QV=zs(Wo);import{v4 as Q$}from"uuid";import{z as T}from"zod";var Ef=Symbol("Let zodToJsonSchema decide on which parser to use");var bf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Tf=r=>typeof r=="string"?{...bf,name:r}:{...bf,...r};var vf=r=>{let e=Tf(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ad(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function pe(r,e,t,n,o){r[e]=t,ad(r,e,n,o)}var Hs=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as me}from"zod";function Fe(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?Hs(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as h_}from"zod";function Af(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==h_.ZodAny&&(t.items=J(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&pe(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&pe(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(pe(t,"minItems",r.exactLength.value,r.exactLength.message,e),pe(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function wf(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?pe(t,"minimum",n.value,n.message,e):pe(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),pe(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?pe(t,"maximum",n.value,n.message,e):pe(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),pe(t,"maximum",n.value,n.message,e));break;case"multipleOf":pe(t,"multipleOf",n.value,n.message,e);break}return t}function Cf(){return{type:"boolean"}}function Gs(r,e){return J(r.type._def,e)}var Rf=(r,e)=>J(r.innerType._def,e);function sd(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>sd(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return f_(r,e)}}var f_=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":pe(t,"minimum",n.value,n.message,e);break;case"max":pe(t,"maximum",n.value,n.message,e);break}return t};function xf(r,e){return{...J(r.innerType._def,e),default:r.defaultValue()}}function Mf(r,e){return e.effectStrategy==="input"?J(r.schema._def,e):Fe(e)}function _f(r){return{type:"string",enum:Array.from(r.values)}}var S_=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Pf(r,e){let t=[J(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(S_(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function If(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as ra}from"zod";var ld,fr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ld===void 0&&(ld=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ld),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Vs(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":pe(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":pe(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Sr(t,"email",n.message,e);break;case"format:idn-email":Sr(t,"idn-email",n.message,e);break;case"pattern:zod":Ot(t,fr.email,n.message,e);break}break;case"url":Sr(t,"uri",n.message,e);break;case"uuid":Sr(t,"uuid",n.message,e);break;case"regex":Ot(t,n.regex,n.message,e);break;case"cuid":Ot(t,fr.cuid,n.message,e);break;case"cuid2":Ot(t,fr.cuid2,n.message,e);break;case"startsWith":Ot(t,RegExp(`^${cd(n.value,e)}`),n.message,e);break;case"endsWith":Ot(t,RegExp(`${cd(n.value,e)}$`),n.message,e);break;case"datetime":Sr(t,"date-time",n.message,e);break;case"date":Sr(t,"date",n.message,e);break;case"time":Sr(t,"time",n.message,e);break;case"duration":Sr(t,"duration",n.message,e);break;case"length":pe(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),pe(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ot(t,RegExp(cd(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Sr(t,"ipv4",n.message,e),n.version!=="v4"&&Sr(t,"ipv6",n.message,e);break}case"base64url":Ot(t,fr.base64url,n.message,e);break;case"jwt":Ot(t,fr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ot(t,fr.ipv4Cidr,n.message,e),n.version!=="v4"&&Ot(t,fr.ipv6Cidr,n.message,e);break}case"emoji":Ot(t,fr.emoji(),n.message,e);break;case"ulid":{Ot(t,fr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Sr(t,"binary",n.message,e);break}case"contentEncoding:base64":{pe(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ot(t,fr.base64,n.message,e);break}}break}case"nanoid":Ot(t,fr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function cd(r,e){return e.patternStrategy==="escape"?b_(r):r}var y_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b_(r){let e="";for(let t=0;t<r.length;t++)y_.has(r[t])||(e+="\\"),e+=r[t];return e}function Sr(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):pe(r,"format",e,t,n)}function Ot(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Of(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):pe(r,"pattern",Of(e,n),t,n)}function Of(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){s?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],s=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
2
|
+
var EM=Object.defineProperty;var We=(r,e)=>()=>(r&&(e=r(r=0)),e);var TM=(r,e)=>{for(var t in e)EM(r,t,{get:e[t],enumerable:!0})};var TE,vE=We(()=>{"use strict";TE=typeof globalThis=="object"?globalThis:global});var AE=We(()=>{"use strict";vE()});var wE=We(()=>{"use strict";AE()});var en,Pm=We(()=>{"use strict";en="1.9.0"});function dN(r){var e=new Set([r]),t=new Set,n=r.match(CE);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(s){return t.add(s),!1}function a(s){return e.add(s),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var l=c.match(CE);if(!l)return i(c);var u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||o.major!==u.major?i(c):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(c):i(c):o.minor<=u.minor?a(c):i(c)}}var CE,RE,xE=We(()=>{"use strict";Pm();CE=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;RE=dN(en)});function ci(r,e,t,n){var o;n===void 0&&(n=!1);var i=ka[Da]=(o=ka[Da])!==null&&o!==void 0?o:{version:en};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!==en){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+en);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+en+"."),!0}function tn(r){var e,t,n=(e=ka[Da])===null||e===void 0?void 0:e.version;if(!(!n||!RE(n)))return(t=ka[Da])===null||t===void 0?void 0:t[r]}function ui(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+en+".");var t=ka[Da];t&&delete t[r]}var mN,Da,ka,Ua=We(()=>{"use strict";wE();Pm();xE();mN=en.split(".")[0],Da=Symbol.for("opentelemetry.js.api."+mN),ka=TE});function Fa(r,e,t){var n=tn("diag");if(n)return t.unshift(e),n[r].apply(n,gN([],pN(t),!1))}var pN,gN,ME,_E=We(()=>{"use strict";Ua();pN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gN=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))},ME=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 Fa("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fa("verbose",this._namespace,e)},r}()});var Ue,Bl=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"})(Ue||(Ue={}))});function PE(r,e){r<Ue.NONE?r=Ue.NONE:r>Ue.ALL&&(r=Ue.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",Ue.ERROR),warn:t("warn",Ue.WARN),info:t("info",Ue.INFO),debug:t("debug",Ue.DEBUG),verbose:t("verbose",Ue.VERBOSE)}}var IE=We(()=>{"use strict";Bl()});var hN,fN,SN,kr,Ba=We(()=>{"use strict";_E();IE();Bl();Ua();hN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},fN=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))},SN="diag",kr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=tn("diag");if(s)return s[o].apply(s,fN([],hN(i),!1))}}var t=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:Ue.INFO}),o===t){var l=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=l.stack)!==null&&a!==void 0?a:l.message),!1}typeof i=="number"&&(i={logLevel:i});var u=tn("diag"),d=PE((s=i.logLevel)!==null&&s!==void 0?s:Ue.INFO,o);if(u&&!i.suppressOverrideMessage){var m=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+m),d.warn("Current logger will overwrite one already registered from "+m)}return ci("diag",d,t,!0)};t.setLogger=n,t.disable=function(){ui(SN,t)},t.createComponentLogger=function(o){return new ME(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 OE,LE=We(()=>{"use strict";OE=Symbol("BaggageEntryMetadata")});function Im(r){return typeof r!="string"&&(yN.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:OE,toString:function(){return r}}}var yN,NE=We(()=>{"use strict";Ba();LE();yN=kr.instance()});function Om(r){return Symbol.for(r)}var bN,Lm,Nm=We(()=>{"use strict";bN=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}(),Lm=new bN});function Um(){return km}var co,EN,zl,TN,vN,AN,wN,Dm,CN,RN,xN,km,MN,_N,PN,IN,ON,LN,NN,Fm=We(()=>{"use strict";co=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)}}(),EN=function(){function r(){}return r.prototype.createGauge=function(e,t){return _N},r.prototype.createHistogram=function(e,t){return PN},r.prototype.createCounter=function(e,t){return MN},r.prototype.createUpDownCounter=function(e,t){return IN},r.prototype.createObservableGauge=function(e,t){return LN},r.prototype.createObservableCounter=function(e,t){return ON},r.prototype.createObservableUpDownCounter=function(e,t){return NN},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),zl=function(){function r(){}return r}(),TN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(zl),vN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(zl),AN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(zl),wN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(zl),Dm=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),CN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dm),RN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dm),xN=function(r){co(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Dm),km=new EN,MN=new TN,_N=new AN,PN=new wN,IN=new vN,ON=new CN,LN=new RN,NN=new xN});var jt,DE=We(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(jt||(jt={}))});var DN,kN,kE,UE=We(()=>{"use strict";Nm();DN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},kN=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))},kE=function(){function r(){}return r.prototype.active=function(){return Lm},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,kN([n],DN(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var UN,FN,Bm,BN,FE,BE=We(()=>{"use strict";UE();Ua();Ba();UN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},FN=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))},Bm="context",BN=new kE,FE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return ci(Bm,e,kr.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,FN([e,t,n],UN(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return tn(Bm)||BN},r.prototype.disable=function(){this._getContextManager().disable(),ui(Bm,kr.instance())},r}()});var di,zE=We(()=>{"use strict";BE();di=FE.getInstance()});var H,HE=We(()=>{"use strict";Ba();H=kr.instance()});var zN,GE,VE=We(()=>{"use strict";Fm();zN=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return km},r}(),GE=new zN});var zm,WE,jE=We(()=>{"use strict";VE();Ua();Ba();zm="metrics",WE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return ci(zm,e,kr.instance())},r.prototype.getMeterProvider=function(){return tn(zm)||GE},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){ui(zm,kr.instance())},r}()});var Hl,$E=We(()=>{"use strict";jE();Hl=WE.getInstance()});var Me=We(()=>{"use strict";NE();Nm();Bl();Fm();DE();zE();HE();$E()});import{Argument as Lh,Command as jG,Option as $G}from"@commander-js/extra-typings";import I0 from"appium";import{execSync as O0}from"child_process";import{z as qu}from"zod";var rV=qu.object({input:qu.string(),agentConfigVersion:qu.string().optional()});import{z as st}from"zod";var iV=st.object({srcs:st.array(st.string()),urls:st.array(st.string()),desiredSrc:st.string().optional(),desiredUrl:st.string().optional()}),kh=st.object({srcRegex:st.string().optional(),urlRegex:st.string().optional()}),Uh=st.object({x:st.number(),y:st.number(),correlation:st.number()}),aV=st.object({searchImageBase64String:st.string(),pageImageBase64String:st.string(),id:st.string().uuid(),timeoutMs:st.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as vM}from"zod-openapi";vM(L);var dn=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(dn||{}),AM=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),Ku=L.object({result:L.number(),traceId:L.string()}).array(),Ls=L.object({type:L.literal("GCS_TRACES"),traces:Ku}),un=(o=>(o.Precise="precise",o.Narrow="narrow",o.Unspecific="broad",o.Irrelevant="irrelevant",o))(un||{}),Fh=L.object({attributes:L.record(L.string(),L.string()).optional(),text:L.string().optional(),position:L.object({x1:L.number(),y1:L.number(),x2:L.number(),y2:L.number(),tolerance:L.nativeEnum(un)}).optional(),shape:L.object({width:L.number(),height:L.number(),tolerance:L.nativeEnum(un)}).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),wM=L.object({selectors:L.string().array(),requirements:Fh.optional()}),mn=L.object({id:L.number().int(),dataMomenticId:L.number().int().optional(),selector:L.string().optional(),hybridSelector:L.object({textContent:L.string().nullish(),attributes:L.record(L.string(),L.string().optional()),tagName:L.string(),expandShadowRoot:L.boolean().optional(),classNames:L.string().array(),nthChild:L.number()}).array().optional(),generatedSelectors:L.string().array().optional(),requirements:Fh.optional(),additionalElements:wM.array().optional(),role:L.string().optional(),name:L.string().optional(),numChildren:L.number().optional(),content:L.string().optional(),pathFromRoot:L.string().optional(),serializedHtml:L.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:L.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:L.string().url().optional(),boundingBox:L.object({x:L.number().optional(),y:L.number().optional(),width:L.number(),height:L.number()}).describe("css pixel bounding box").optional(),frameCache:AM.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(dn).optional(),targetUpdateTime:L.string().optional(),targetUpdateLoggerTags:L.record(L.string(),L.string()).optional(),cacheResolutionUpdateSource:L.string().optional(),cacheResolutionUpdateTime:L.string().optional(),cacheResolutionUpdateLoggerTags:L.record(L.string(),L.string()).optional(),memory:Ls.optional()}).openapi({ref:"ElementTargetCache"});function Ns(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var CM=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),RM=L.object({x:L.number(),y:L.number()}),xM=L.object({type:L.literal("coordinates"),pixels:RM}).openapi({ref:"CoordinatesTarget"});function pn(r){return r.type==="description"}function xr(r){return r.type==="coordinates"}var At=L.discriminatedUnion("type",[CM,xM]).openapi({ref:"ElementTarget"});function Yu(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Bh(r){return Ls.safeParse(r).success}import{v4 as Ee}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as FM}from"zod-openapi";import{z as ce}from"zod";import{extendZodWithOpenApi as MM}from"zod-openapi";import{z as Ki}from"zod";import zh from"zod";var qi=zh.object({updatedAt:zh.coerce.date().optional()});var Xu=Ki.object({result:Ki.boolean(),traceId:Ki.string()}).array(),Ju=Ki.object({type:Ki.literal("GCS_TRACES"),traces:Xu}),Qu=qi.extend({memory:Ju.optional()});MM(ce);var Hh=ce.object({thoughts:ce.string(),result:ce.boolean(),relevantElements:ce.array(ce.number()).optional(),updatedMemory:Xu.optional()}),Kt=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Kt||{});var _M=ce.object({type:ce.literal("ELEMENT_NAME"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),value:ce.string()}).openapi({ref:"ElementNameAssertion"}),PM=ce.object({type:ce.literal("ELEMENT_STYLE"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),property:ce.string(),value:ce.string()}).openapi({ref:"ElementStyleAssertion"}),IM=ce.object({type:ce.literal("ELEMENT_CONTENT"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),value:ce.string()}).openapi({ref:"ElementContentAssertion"}),OM=ce.object({type:ce.literal("ELEMENT_ATTRIBUTE"),negated:ce.boolean().optional(),operation:ce.nativeEnum(Kt),attr:ce.string(),value:ce.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Mr=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Mr||{});var LM=ce.object({type:ce.literal("ELEMENT_EXISTENCE"),negated:ce.boolean().optional(),condition:ce.nativeEnum(Mr).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Ds=ce.discriminatedUnion("type",[IM,OM,LM,_M,PM]).openapi({ref:"ManualElementAssertion"});var NM=ce.object({type:ce.literal("CONTENT"),negated:ce.boolean().optional(),value:ce.string()}).openapi({ref:"PageContentAssertion"}),Gh=ce.discriminatedUnion("type",[NM]).openapi({ref:"ManualPageAssertion"});import Pt from"zod";var Zu=Pt.discriminatedUnion("type",[Pt.object({type:Pt.literal("SUBSTRING"),url:Pt.string()}),Pt.object({type:Pt.literal("GLOB"),glob:Pt.string()}),Pt.object({type:Pt.literal("REGEX"),regex:Pt.string()}),Pt.object({type:Pt.literal("DOMAIN"),domain:Pt.string()})]),Yi=Pt.object({urlMatcher:Zu,method:Pt.string().optional()});import{z as ie}from"zod";var DM=ie.object({type:ie.literal("json"),content:ie.string().describe("The JSON content to send in the request body")}),kM=ie.object({type:ie.literal("form-urlencoded"),content:ie.record(ie.string(),ie.string()).describe("The form fields to send in the request body")}),UM=ie.discriminatedUnion("type",[DM,kM]),$n=ie.object({url:ie.string(),method:ie.union([ie.literal("GET"),ie.literal("POST"),ie.literal("PUT"),ie.literal("DELETE"),ie.literal("PATCH")]),headers:ie.record(ie.string(),ie.string()).optional(),params:ie.record(ie.string(),ie.string()).optional(),body:UM.optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),Vh=ie.object({url:ie.string(),headers:ie.record(ie.string(),ie.string()).optional(),query:ie.string(),variables:ie.string().optional(),timeout:ie.number().int().optional().describe("Max seconds to wait for the request to complete")}),ks=ie.object({code:ie.string(),fragment:ie.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:ie.union([ie.literal("NODE"),ie.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:ie.number().int().max(60).optional().describe("Max seconds for the code to complete")});var et=($=>($.AI_EXTRACT="AI_EXTRACT",$.AI_ASSERTION="AI_ASSERTION",$.AUTH_LOAD="AUTH_LOAD",$.AUTH_SAVE="AUTH_SAVE",$.BLUR="BLUR",$.CAPTCHA="CAPTCHA",$.CLICK="CLICK",$.COOKIE="COOKIE",$.COPY="COPY",$.DIALOG="DIALOG",$.DRAG="DRAG",$.ELEMENT_CHECK="ELEMENT_CHECK",$.FILE_UPLOAD="FILE_UPLOAD",$.FOCUS="FOCUS",$.GO_BACK="GO_BACK",$.GO_FORWARD="GO_FORWARD",$.HOVER="HOVER",$.JAVASCRIPT="JAVASCRIPT",$.LOCAL_STORAGE="LOCAL_STORAGE",$.MOUSE_DRAG="MOUSE_DRAG",$.NAVIGATE="NAVIGATE",$.NEW_TAB="NEW_TAB",$.PAGE_CHECK="PAGE_CHECK",$.PASTE="PASTE",$.PRESS="PRESS",$.KEY_DOWN="KEY_DOWN",$.KEY_UP="KEY_UP",$.REFRESH="REFRESH",$.REQUEST="REQUEST",$.GRAPHQL_REQUEST="GRAPHQL_REQUEST",$.SCROLL_DOWN="SCROLL_DOWN",$.SCROLL_UP="SCROLL_UP",$.SCROLL_LEFT="SCROLL_LEFT",$.SCROLL_RIGHT="SCROLL_RIGHT",$.SELECT_OPTION="SELECT_OPTION",$.SWITCH_TAB="TAB",$.TYPE="TYPE",$.VISUAL_DIFF="VISUAL_DIFF",$.WAIT="WAIT",$.WAIT_FOR_URL="WAIT_FOR_URL",$.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="SUCCESS",$))(et||{});FM(y);var X=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),Yt=y.object({useSelector:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Xt=qi.extend({target:mn}).optional().openapi({ref:"SingleTargetCache"});function Wh(r){return Xt.safeParse(r).success}var Us=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),jh=X.merge(Us).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),Fs=Yt.merge(y.object({cache:Xt})),qn=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Kn=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Lo=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),No=X.merge(Fs.merge(y.object({target:At.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),FV=y.discriminatedUnion("type",[qn,Kn,Lo,No]).openapi({ref:"AllScrollCommands"}),BM=X.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),$h=X.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),zM=y.object({caseInsensitive:y.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:y.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:y.number().int().optional().describe("Max seconds to wait for the URL to match")}),qh=X.extend({type:y.literal("WAIT_FOR_URL"),matcher:Zu}).merge(zM).openapi({ref:"WaitUrlCommand"}),Kh=X.merge(Us).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Yh=X.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Xh=X.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),HM=X.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),GM=X.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),td=X.merge(Yt).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Jh=X.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),Qh=X.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),Zh=X.merge(ks).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Do=X.merge(Yt).extend({type:y.literal("CLICK"),target:At,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForDownload:y.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:y.number().optional(),downloadTimeoutMs:y.number().optional(),cache:Xt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),ef=qi.extend({fromTarget:mn.optional(),toTarget:mn.optional()}),ko=X.merge(Yt).merge(y.object({type:y.literal("DRAG"),fromTarget:At,toTarget:At,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:ef.optional()})).openapi({ref:"DragCommand"}),Uo=X.merge(Yt).merge(y.object({type:y.literal("MOUSE_DRAG"),target:At.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:Xt})).openapi({ref:"MouseDragCommand"}),Fo=X.merge(Yt).merge(y.object({type:y.literal("HOVER"),target:At,cache:Xt})).openapi({ref:"HoverCommand"}),Xi=X.merge(Yt).merge(y.object({type:y.literal("FOCUS"),target:At,cache:Xt})).openapi({ref:"FocusCommand"}),Ji=X.merge(Yt).extend({type:y.literal("BLUR"),target:At.optional(),cache:Xt}).openapi({ref:"BlurCommand"}),VM=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),WM=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),jM=X.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[VM,WM]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),tf=y.discriminatedUnion("type",[y.object({type:y.literal("VALUE"),value:y.string()}),y.object({type:y.literal("LABEL"),label:y.string()}),y.object({type:y.literal("INDEX"),index:y.coerce.string()})]),Bo=X.merge(Yt).extend({type:y.literal("SELECT_OPTION"),target:At,cache:Xt,choice:tf.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),rd=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),Qi=X.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:rd.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Qu.optional()})).openapi({ref:"AIAssertionCommand"}),zt=5,zo=600,Ho=X.merge(Yt).extend({type:y.literal("ELEMENT_CHECK"),target:At,assertion:Ds,cache:Xt.or(Qu).optional(),timeout:y.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),rf=X.extend({type:y.literal("PAGE_CHECK"),assertion:Gh,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),nf=X.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})).openapi({ref:"AIExtractCommand"}),$M=y.object({clearContent:y.boolean().optional(),forceClearContent:y.boolean().optional(),delay:y.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:y.boolean().optional(),pressEnter:y.boolean().optional(),relativePosition:y.object({x:y.number(),y:y.number()}).optional()}),of=25,Go=X.merge(Yt).merge($M).extend({type:y.literal("TYPE"),target:At.optional(),value:y.string(),cache:Xt}).openapi({ref:"TypeCommand"}),af=X.merge(y.object({type:y.literal("PRESS"),value:y.string(),repeat:y.number().optional(),convertMeta:y.boolean().optional(),delayMs:y.number().optional()})).openapi({ref:"PressCommand"}),sf=X.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),lf=X.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),qM=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),KM=y.object({type:y.literal("REGEX"),pattern:y.string()}),YM=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),XM=y.discriminatedUnion("type",[qM,KM,YM]),JM=X.merge(Us).merge(y.object({type:y.literal("TAB"),action:XM})).openapi({ref:"TabCommand"}),cf=X.merge(Us).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),QM=X.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),uf=X.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),df=X.extend({type:y.literal("REQUEST")}).merge($n).openapi({ref:"RequestCommand"}),mf=X.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Vh).openapi({ref:"GraphQLRequestCommand"}),pf=X.merge(y.object({type:y.literal("SUCCESS"),condition:Qi.optional()})).openapi({ref:"SuccessCommand"}),gf=X.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),ZM=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),Zi=X.merge(Yt).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:At.optional(),screenshot:ZM.optional(),cache:Xt})).openapi({ref:"VisualDiffCommand"}),e_=X.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Yi,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),t_=X.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),r_=X.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Yi,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),n_=X.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),o_=X.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Yi.optional()})).openapi({ref:"SetHeaderCommand"}),i_=X.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Yi,responseGenerator:y.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:y.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:y.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"})),a_=X.merge(y.object({type:y.literal("REMOVE_ROUTE_MOCK"),key:y.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),s_=X.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),l_=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],BV=[...l_,"DRAG"],c_=y.discriminatedUnion("type",[Do,Go,af,sf,lf,Bo,jh,Kn,qn,Qi,Yh,Fo,$h]),u_=y.discriminatedUnion("type",[...c_.options,ko]),d_=y.discriminatedUnion("type",[...u_.options]),hf=y.discriminatedUnion("type",[...d_.options,pf]),nd=y.discriminatedUnion("type",[pf,Do,Go,af,sf,lf,Bo,jh,Kn,qn,Qi,Yh,Fo,$h,Zh,Ho,rf,cf,qh,nf,Jh,Xh,uf,ko,Uo,Qh,Kh,df,mf]),m_=y.discriminatedUnion("type",[nf,GM,HM,td,QM,Jh,BM,Ho,jM,Xh,Zh,uf,Uo,cf,rf,Qh,Kh,df,mf,Lo,No,JM,Zi,Xi,Ji,qh,e_,t_,r_,n_,o_,i_,a_,s_]),Vo=y.discriminatedUnion("type",[...hf.options,...m_.options]).openapi({ref:"Command"}),Bs=y.discriminatedUnion("type",[...hf.options,gf]),zV=y.discriminatedUnion("type",[...nd.options,gf]);function Kr(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 ff(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 p_}from"zod";var jV=p_.discriminatedUnion("type",[Ji,td,Do,ko,Xi,Fo,Uo,qn,Kn,Lo,No,Bo,Go,Zi,Ho]);import{z as g_}from"zod";import{z as hn}from"zod";function ea(r){return hn.object({key:hn.string(),testId:hn.string().optional(),moduleId:hn.string().optional(),organizationId:hn.string(),value:r})}function ta(r){return ea(r).extend({uniqueKey:hn.string()})}function zs(r){return hn.record(hn.string(),ta(r))}var It={type:!0,cache:!0},Wo=g_.discriminatedUnion("type",[Qi.pick(It),Ji.pick(It),Do.pick(It),ko.pick(It),Ho.pick(It),Xi.pick(It),Fo.pick(It),Uo.pick(It),qn.pick(It),Kn.pick(It),Lo.pick(It),No.pick(It),Bo.pick(It),Go.pick(It),Zi.pick(It)]),od=Object.values(et).filter(r=>Wo.options.some(e=>e.shape.type.safeParse(r).success));Vo.options.forEach(r=>{if("target"in r.shape&&!od.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function id(r){return od.includes(r.type)}var Sf=ea(Wo),yf=ta(Wo),ZV=zs(Wo);import{v4 as Z$}from"uuid";import{z as T}from"zod";var Ef=Symbol("Let zodToJsonSchema decide on which parser to use");var bf={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Tf=r=>typeof r=="string"?{...bf,name:r}:{...bf,...r};var vf=r=>{let e=Tf(r),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function ad(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function pe(r,e,t,n,o){r[e]=t,ad(r,e,n,o)}var Hs=(r,e)=>{let t=0;for(;t<r.length&&t<e.length&&r[t]===e[t];t++);return[(r.length-t).toString(),...e.slice(t)].join("/")};import{ZodFirstPartyTypeKind as me}from"zod";function Fe(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?Hs(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as h_}from"zod";function Af(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==h_.ZodAny&&(t.items=J(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&pe(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&pe(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(pe(t,"minItems",r.exactLength.value,r.exactLength.message,e),pe(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function wf(r,e){let t={type:"integer",format:"int64"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?pe(t,"minimum",n.value,n.message,e):pe(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),pe(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?pe(t,"maximum",n.value,n.message,e):pe(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),pe(t,"maximum",n.value,n.message,e));break;case"multipleOf":pe(t,"multipleOf",n.value,n.message,e);break}return t}function Cf(){return{type:"boolean"}}function Gs(r,e){return J(r.type._def,e)}var Rf=(r,e)=>J(r.innerType._def,e);function sd(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>sd(r,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return f_(r,e)}}var f_=(r,e)=>{let t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(let n of r.checks)switch(n.kind){case"min":pe(t,"minimum",n.value,n.message,e);break;case"max":pe(t,"maximum",n.value,n.message,e);break}return t};function xf(r,e){return{...J(r.innerType._def,e),default:r.defaultValue()}}function Mf(r,e){return e.effectStrategy==="input"?J(r.schema._def,e):Fe(e)}function _f(r){return{type:"string",enum:Array.from(r.values)}}var S_=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function Pf(r,e){let t=[J(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(r.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return t.forEach(i=>{if(S_(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let a=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:s,...c}=i;a=c}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function If(r,e){let t=typeof r.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(r.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[r.value]}:{type:t==="bigint"?"integer":t,const:r.value}}import{ZodFirstPartyTypeKind as ra}from"zod";var ld,fr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ld===void 0&&(ld=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ld),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Vs(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":pe(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":pe(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Sr(t,"email",n.message,e);break;case"format:idn-email":Sr(t,"idn-email",n.message,e);break;case"pattern:zod":Ot(t,fr.email,n.message,e);break}break;case"url":Sr(t,"uri",n.message,e);break;case"uuid":Sr(t,"uuid",n.message,e);break;case"regex":Ot(t,n.regex,n.message,e);break;case"cuid":Ot(t,fr.cuid,n.message,e);break;case"cuid2":Ot(t,fr.cuid2,n.message,e);break;case"startsWith":Ot(t,RegExp(`^${cd(n.value,e)}`),n.message,e);break;case"endsWith":Ot(t,RegExp(`${cd(n.value,e)}$`),n.message,e);break;case"datetime":Sr(t,"date-time",n.message,e);break;case"date":Sr(t,"date",n.message,e);break;case"time":Sr(t,"time",n.message,e);break;case"duration":Sr(t,"duration",n.message,e);break;case"length":pe(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),pe(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ot(t,RegExp(cd(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Sr(t,"ipv4",n.message,e),n.version!=="v4"&&Sr(t,"ipv6",n.message,e);break}case"base64url":Ot(t,fr.base64url,n.message,e);break;case"jwt":Ot(t,fr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ot(t,fr.ipv4Cidr,n.message,e),n.version!=="v4"&&Ot(t,fr.ipv6Cidr,n.message,e);break}case"emoji":Ot(t,fr.emoji(),n.message,e);break;case"ulid":{Ot(t,fr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Sr(t,"binary",n.message,e);break}case"contentEncoding:base64":{pe(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ot(t,fr.base64,n.message,e);break}}break}case"nanoid":Ot(t,fr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function cd(r,e){return e.patternStrategy==="escape"?b_(r):r}var y_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function b_(r){let e="";for(let t=0;t<r.length;t++)y_.has(r[t])||(e+="\\"),e+=r[t];return e}function Sr(r,e,t,n){r.format||r.anyOf?.some(o=>o.format)?(r.anyOf||(r.anyOf=[]),r.format&&(r.anyOf.push({format:r.format,...r.errorMessage&&n.errorMessages&&{errorMessage:{format:r.errorMessage.format}}}),delete r.format,r.errorMessage&&(delete r.errorMessage.format,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.anyOf.push({format:e,...t&&n.errorMessages&&{errorMessage:{format:t}}})):pe(r,"format",e,t,n)}function Ot(r,e,t,n){r.pattern||r.allOf?.some(o=>o.pattern)?(r.allOf||(r.allOf=[]),r.pattern&&(r.allOf.push({pattern:r.pattern,...r.errorMessage&&n.errorMessages&&{errorMessage:{pattern:r.errorMessage.pattern}}}),delete r.pattern,r.errorMessage&&(delete r.errorMessage.pattern,Object.keys(r.errorMessage).length===0&&delete r.errorMessage)),r.allOf.push({pattern:Of(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):pe(r,"pattern",Of(e,n),t,n)}function Of(r,e){if(!e.applyRegexFlags||!r.flags)return r.source;let t={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=t.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(i){o+=n[c],i=!1;continue}if(t.i){if(a){if(n[c].match(/[a-z]/)){s?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],s=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(t.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
3
3
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
4
4
|
]))`;continue}}if(t.s&&n[c]==="."){o+=a?`${n[c]}\r
|
|
5
5
|
`:`[${n[c]}\r
|
|
6
6
|
]`;continue}o+=n[c],n[c]==="\\"?i=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o}function Ws(r,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&r.keyType?._def.typeName===ra.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:J(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Fe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:J(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===ra.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=Vs(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===ra.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===ra.ZodBranded&&r.keyType._def.type._def.typeName===ra.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=Gs(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function Lf(r,e){if(e.mapStrategy==="record")return Ws(r,e);let t=J(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Fe(e),n=J(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Fe(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function Nf(r){let e=r.values,n=Object.keys(r.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Df(r){return r.target==="openAi"?void 0:{not:Fe({...r,currentPath:[...r.currentPath,"not"]})}}function kf(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var na={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ff(r,e){if(e.target==="openApi3")return Uf(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in na&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=na[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(t.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=t.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===t.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:t.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(t.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Uf(r,e)}var Uf=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>J(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return t.length?{anyOf:t}:void 0};function Bf(r,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(r.innerType._def.typeName)&&(!r.innerType._def.checks||!r.innerType._def.checks.length))return e.target==="openApi3"?{type:na[r.innerType._def.typeName],nullable:!0}:{type:[na[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=J(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=J(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function zf(r,e){let t={type:"number"};if(!r.checks)return t;for(let n of r.checks)switch(n.kind){case"int":t.type="integer",ad(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?pe(t,"minimum",n.value,n.message,e):pe(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),pe(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?pe(t,"maximum",n.value,n.message,e):pe(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),pe(t,"maximum",n.value,n.message,e));break;case"multipleOf":pe(t,"multipleOf",n.value,n.message,e);break}return t}function Hf(r,e){let t=e.target==="openAi",n={type:"object",properties:{}},o=[],i=r.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let l=T_(c);l&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=J(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||o.push(s))}o.length&&(n.required=o);let a=E_(r,e);return a!==void 0&&(n.additionalProperties=a),n}function E_(r,e){if(r.catchall._def.typeName!=="ZodNever")return J(r.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(r.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function T_(r){try{return r.isOptional()}catch{return!0}}var Gf=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return J(r.innerType._def,e);let t=J(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Fe(e)},t]}:Fe(e)};var Vf=(r,e)=>{if(e.pipeStrategy==="input")return J(r.in._def,e);if(e.pipeStrategy==="output")return J(r.out._def,e);let t=J(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=J(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function Wf(r,e){return J(r.type._def,e)}function jf(r,e){let n={type:"array",uniqueItems:!0,items:J(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&pe(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&pe(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function $f(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>J(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:J(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>J(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function qf(r){return{not:Fe(r)}}function Kf(r){return Fe(r)}var Yf=(r,e)=>J(r.innerType._def,e);var Xf=(r,e,t)=>{switch(e){case me.ZodString:return Vs(r,t);case me.ZodNumber:return zf(r,t);case me.ZodObject:return Hf(r,t);case me.ZodBigInt:return wf(r,t);case me.ZodBoolean:return Cf();case me.ZodDate:return sd(r,t);case me.ZodUndefined:return qf(t);case me.ZodNull:return kf(t);case me.ZodArray:return Af(r,t);case me.ZodUnion:case me.ZodDiscriminatedUnion:return Ff(r,t);case me.ZodIntersection:return Pf(r,t);case me.ZodTuple:return $f(r,t);case me.ZodRecord:return Ws(r,t);case me.ZodLiteral:return If(r,t);case me.ZodEnum:return _f(r);case me.ZodNativeEnum:return Nf(r);case me.ZodNullable:return Bf(r,t);case me.ZodOptional:return Gf(r,t);case me.ZodMap:return Lf(r,t);case me.ZodSet:return jf(r,t);case me.ZodLazy:return()=>r.getter()._def;case me.ZodPromise:return Wf(r,t);case me.ZodNaN:case me.ZodNever:return Df(t);case me.ZodEffects:return Mf(r,t);case me.ZodAny:return Fe(t);case me.ZodUnknown:return Kf(t);case me.ZodDefault:return xf(r,t);case me.ZodBranded:return Gs(r,t);case me.ZodReadonly:return Yf(r,t);case me.ZodCatch:return Rf(r,t);case me.ZodPipeline:return Vf(r,t);case me.ZodFunction:case me.ZodVoid:case me.ZodSymbol:return;default:return(n=>{})(e)}};function J(r,e,t=!1){let n=e.seen.get(r);if(e.override){let s=e.override?.(r,e,n,t);if(s!==Ef)return s}if(n&&!t){let s=v_(n,e);if(s!==void 0)return s}let o={def:r,path:e.currentPath,jsonSchema:void 0};e.seen.set(r,o);let i=Xf(r,r.typeName,e),a=typeof i=="function"?J(i(),e):i;if(a&&A_(r,e,a),e.postProcess){let s=e.postProcess(a,r,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var v_=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:Hs(e.currentPath,r.path)};case"none":case"seen":return r.path.length<e.currentPath.length&&r.path.every((t,n)=>e.currentPath[n]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Fe(e)):e.$refStrategy==="seen"?Fe(e):void 0}},A_=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var oa=(r,e)=>{let t=vf(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:J(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??Fe(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=J(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??Fe(t),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),t.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[t.openAiAnyTypeName]||(n[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));let s=o===void 0?n?{...i,[t.definitionPath]:n}:i:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,o].join("/"),[t.definitionPath]:{...n,[o]:i}};return t.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};import{z as _r}from"zod";import{extendZodWithOpenApi as w_}from"zod-openapi";w_(_r);var Ce=(m=>(m.AI_PROVIDER="AIProviderError",m.USER_INFRA="UserInfrastructureError",m.ACTION_FAILURE="ActionFailureError",m.ASSERTION_FAILURE="AssertionFailureError",m.CONFIG_ERROR="UserConfigurationError",m.SETUP_FAILURE="SetupFailureError",m.TEARDOWN_FAILURE="TeardownFailureError",m.WEB_AGENT_PLATFORM="InternalWebAgentError",m.UNKNOWN_PLATFORM="InternalPlatformError",m.JOB_TIMEOUT="JobTimeoutError",m.CONCURRENCY_ERROR="ConcurrencyError",m.UNKNOWN="UnknownError",m))(Ce||{});var ud=_r.object({reason:_r.nativeEnum(Ce),previousStepsDescription:_r.array(_r.string()).optional(),summary:_r.string(),rootCause:_r.string().optional()}).openapi({ref:"TestResultClassification"}),js=_r.object({errorMessage:_r.string(),errorStack:_r.string().optional(),classification:ud.optional()}).openapi({ref:"TestFailureDetails"});var $s=class extends Error{constructor(e,t={}){super(e,t),this.name="ValidationError"}};var ia=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var R=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(Ce))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}}},fn=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Sn=class extends Error{constructor(e,t={}){super(e,t),this.name="NoMatchingElementError"}},Pr=class extends Error{decisions;cacheMissReason;constructor(e,t,n,o={}){super(e,o),this.decisions=t,this.name="NoElementsFoundUsingCacheError",this.cacheMissReason=n}toString(){return`${this.message}
|
|
7
7
|
Decisions:
|
|
8
8
|
${this.decisions.map(e=>e.toString()).join(`
|
|
9
|
-
`)}`}};function Jf(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function dd(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 Ir=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},qs=class extends Ir{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Ks=class extends Ir{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function md(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}var pd="Element to be clicked has no bounding box";function Qf(r){return r instanceof Error?r.message.startsWith(pd):!1}function gd(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 hd(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 aa=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var C_={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds.",DRAG:"Drag an element from one location and drop it onto another element.",JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body.",GRAPHQL_REQUEST:"Make a GraphQL request to a specified URL. Provide the GraphQL query (or mutation), optional variables JSON, and any required headers. Use this for GraphQL APIs instead of REQUEST."};nd.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!C_[e])throw new Error(`Command type ${e} is missing a description`)});var Zf=T.object({type:T.literal("CLICK"),description:T.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:T.boolean().or(T.null()),rightClick:T.boolean().or(T.null())}),eS=T.object({type:T.literal("TYPE"),description:T.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:T.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:T.boolean().or(T.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:T.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),tS=T.object({type:T.literal("GO_BACK")}),R_=T.object({type:T.literal("GO_FORWARD")}),x_=T.object({type:T.literal("LOCAL_STORAGE"),key:T.string().describe("The localStorage key to set or get."),value:T.string().describe("The value to store in localStorage. If reading, this can be empty.")}),rS=T.object({type:T.literal("PRESS"),keys:T.array(T.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),nS=T.object({type:T.literal("SELECT_OPTION"),description:T.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:T.discriminatedUnion("type",[T.object({type:T.literal("VALUE"),value:T.string()}),T.object({type:T.literal("LABEL"),label:T.string()}),T.object({type:T.literal("INDEX"),index:T.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),oS=T.object({type:T.literal("NAVIGATE"),url:T.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),iS=T.object({type:T.literal("SCROLL"),y:T.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),aS=T.object({type:T.literal("WAIT"),timeout:T.number().describe("The number of seconds to wait.")}),sS=T.object({type:T.literal("AI_ASSERTION"),assertion:T.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:T.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),lS=T.object({type:T.literal("HOVER"),description:T.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),M_=T.object({type:T.literal("COPY"),value:T.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),__=T.object({type:T.literal("PASTE")}),P_=T.object({type:T.literal("REFRESH")}),I_=T.object({type:T.literal("REQUEST"),url:T.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:T.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:T.record(T.string(),T.string()).or(T.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:T.record(T.string(),T.string()).or(T.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:T.string().or(T.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:T.number().int().or(T.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),O_=T.object({type:T.literal("GRAPHQL_REQUEST"),url:T.string().describe("The URL of the GraphQL endpoint. Can be a full URL or relative path."),headers:T.record(T.string(),T.string()).or(T.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),query:T.string().describe("The GraphQL query or mutation string. Include any required fields and arguments."),variables:T.string().or(T.null()).describe("Optional JSON string of variables to pass with the GraphQL request."),timeout:T.number().int().or(T.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),cS=T.object({type:T.literal("DRAG"),fromDescription:T.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:T.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:T.number().positive().or(T.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),L_=T.object({type:T.literal("MOUSE_DRAG"),description:T.string().or(T.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:T.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:T.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),N_=T.object({type:T.literal("JAVASCRIPT"),code:T.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:T.union([T.literal("NODE"),T.literal("BROWSER")]).or(T.null()).describe("Execution environment. Default is NODE."),timeout:T.number().or(T.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),D_=T.object({type:T.literal("AI_EXTRACT"),goal:T.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:T.string().or(T.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:T.string().or(T.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:T.string().or(T.null()).describe("URL or URL regex for the iframe to extract data from.")}),k_=T.object({type:T.literal("ELEMENT_CHECK"),description:T.string().describe("Description of the element to check."),assertionType:T.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:T.string().or(T.null()).describe("The value to check against (required for CONTENT assertions)."),negated:T.boolean().or(T.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),U_=T.object({type:T.literal("PAGE_CHECK"),value:T.string().describe("The text content to check for on the page."),negated:T.boolean().or(T.null()).describe("If true, checks that the content is NOT present."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),F_=T.object({type:T.literal("NEW_TAB"),url:T.string().describe("The URL to open in the new tab.")}),B_=T.object({type:T.literal("WAIT_FOR_URL"),matcher:T.discriminatedUnion("type",[T.object({type:T.literal("SUBSTRING"),url:T.string()}),T.object({type:T.literal("GLOB"),glob:T.string()}),T.object({type:T.literal("REGEX"),regex:T.string()}),T.object({type:T.literal("DOMAIN"),domain:T.string()})]).describe("How to match the URL."),caseInsensitive:T.boolean().or(T.null()),negated:T.boolean().or(T.null()).describe("Wait for the URL to NOT match instead."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the URL.")}),fd=T.object({type:T.literal("SUCCESS")}),Sd=T.object({type:T.literal("FAILURE")}),uS=T.discriminatedUnion("type",[Zf,eS,rS,nS,oS,iS,aS,sS,lS,tS]),z_=T.discriminatedUnion("type",[...uS.options,cS]),Xs=T.discriminatedUnion("type",[Zf,eS,rS,nS,oS,iS,aS,sS,lS,tS,cS,N_,k_,U_,F_,B_,D_,M_,R_,x_,L_,__,P_,I_,O_]),sq=oa(Xs),lq=T.discriminatedUnion("type",[...Xs.options,fd,Sd]),cq=oa(T.discriminatedUnion("type",[...uS.options,fd,Sd])),uq=oa(T.discriminatedUnion("type",[...z_.options,fd,Sd])),dq=T.object({command:T.unknown(),thoughts:T.string()});import{z as yd}from"zod";import{extendZodWithOpenApi as V_}from"zod-openapi";import{z as dS}from"zod";import{extendZodWithOpenApi as H_}from"zod-openapi";import{z as Yn}from"zod";var Jt=Yn.object({index:Yn.number().optional().describe("global index within a test (in-order traversal)"),id:Yn.string(),skipped:Yn.boolean().optional(),envKey:Yn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Yn.boolean().optional(),retries:Yn.number().optional()});H_(dS);var G_=Jt.extend({type:dS.literal("PRESET_ACTION")}),Qt=G_.extend({command:Vo}).openapi({ref:"PresetAction"});V_(yd);var Xn=Jt.extend({type:yd.literal("AI_ACTION"),text:yd.string(),steps:Qt.array().optional()}).openapi({ref:"AIAction"});import{z as Lt}from"zod";import{z as Js}from"zod";import{extendZodWithOpenApi as W_}from"zod-openapi";W_(Js);var jo=Jt.extend({type:Js.literal("AI_ACTION_DYNAMIC"),text:Js.string(),retries:Js.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as mS}from"zod";var bd=Jt.extend({type:mS.literal("CONDITIONAL"),skipped:mS.boolean().optional()});import{z as ge}from"zod";var j_=ge.object({cacheKey:ge.string(),cacheExpiryMs:ge.number()}),Ed=Jt.extend({id:ge.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ge.record(ge.string()).optional(),cacheConfig:j_.optional()}),Yr=Ed.extend({type:ge.literal("MODULE"),moduleId:ge.string().uuid()}),$_=ge.union([Yr.pick({type:!0,moduleId:!0}),ge.record(ge.unknown())]),q_=ge.object({type:ge.literal("URL_REGEX"),regex:ge.string()}),K_=ge.object({type:ge.literal("PAGE_CHECK"),substring:ge.string()}),Td=ge.object({cacheInvalidation:ge.discriminatedUnion("type",[K_,q_]).optional()}),Zt=ge.object({moduleId:ge.string().uuid(),name:ge.string(),description:ge.string().nullish(),enabled:ge.boolean().nullish(),parameters:ge.string().array().nullish(),defaultParameters:ge.record(ge.string(),ge.string()).nullish(),parameterEnums:ge.record(ge.string(),ge.string().array()).nullish(),defaultCacheKey:ge.string().nullish(),defaultCacheTtl:ge.number().nullish(),defaultCacheAllInvocations:ge.boolean().nullish(),autoAuth:ge.boolean().nullish(),advanced:Td.nullish()});import{z as er}from"zod";var pS=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(pS||{});var Y_=er.discriminatedUnion("type",[er.object({type:er.literal("NAVIGATE_URL"),url:er.string().url()}),er.object({type:er.literal("GO_TO_SECTION_START")})]),X_=er.object({trigger:er.nativeEnum(pS).optional(),attempts:er.number().int().optional(),restartBehavior:Y_}),sa=Jt.extend({type:er.literal("SECTION"),description:er.string().describe("user provided goal of what the section should accomplish"),plan:er.string().array().optional(),autohealingConfig:X_.optional()});var gS=Zt.merge(Ed).extend({type:Lt.literal("RESOLVED_MODULE"),steps:Lt.lazy(()=>lt.array())}),vd=Zt.extend({steps:Lt.lazy(()=>lt.array())}),Ad=sa.extend({steps:Lt.lazy(()=>Nt.array())}),J_=sa.extend({steps:Lt.lazy(()=>lt.array())}),$o=bd.extend({blocks:Lt.object({assertion:Lt.lazy(()=>Qt),steps:Lt.lazy(()=>Nt.array())}).array(),elseSteps:Lt.lazy(()=>Nt.array().optional())}),Q_=bd.extend({blocks:Lt.object({assertion:Lt.lazy(()=>Qt),steps:Lt.lazy(()=>lt.array())}).array(),elseSteps:Lt.lazy(()=>lt.array().optional())}),Nt=Lt.discriminatedUnion("type",[Qt,Xn,jo,Yr,$o,Ad]),lt=Lt.discriminatedUnion("type",[Qt,Xn,jo,gS,Q_,J_]);import{z as tr}from"zod";var Z_=tr.object({steps:Nt.array(),beforeSteps:Nt.array().nullish(),afterSteps:Nt.array().nullish()}),Jn=tr.object({steps:lt.array(),beforeSteps:lt.array().nullish(),afterSteps:lt.array().nullish()}),Qn=tr.object({steps:tr.record(tr.string(),tr.unknown()).array(),beforeSteps:tr.record(tr.string(),tr.unknown()).array().nullish(),afterSteps:tr.record(tr.string(),tr.unknown()).array().nullish()});var yn="1.0.22",Zn="0.0.2";import{z as wt}from"zod";import{z as eo}from"zod";var eP=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Xr=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 qo=eo.string().min(1).max(255).superRefine((r,e)=>{try{la(r)}catch(t){return e.addIssue({code:eo.ZodIssueCode.custom,message:t.message,fatal:!0}),eo.NEVER}});function la(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(eP))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Qs=eo.preprocess(r=>r===null?"":r,eo.union([eo.string().url(),eo.literal("")])).optional();var tP=["AI_EXTRACT","JAVASCRIPT","REQUEST","GRAPHQL_REQUEST","AUTH_SAVE","COPY"],rP=wt.object({id:wt.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:qo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:wt.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."),nP=wt.object({selector:rP,inputs:wt.record(wt.string()).or(wt.null())}),xK=wt.object({type:wt.literal("PRESET_ACTION"),action:Xs,envKey:wt.string().or(wt.null()).describe(`key in the environment to save the result of this step to. Only use this for ${tP.join(" or ")} steps.`)}),MK=wt.object({type:wt.literal("MODULE"),module:nP}),_K=wt.object({type:wt.literal("AI_ACTION_DYNAMIC"),text:wt.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var hS=I.object({phrase:I.string()}),wd=I.object({thoughts:I.string().optional(),result:I.union([I.literal("NOT_FOUND"),I.string(),I.number(),I.array(I.unknown()),I.record(I.unknown(),I.unknown()),I.unknown()])}),u2=I.object({text:I.string()}),oP=I.boolean().or(I.nativeEnum(un)).transform(r=>!(!r||r==="irrelevant")),fS=I.object({attributes:I.array(I.string()).nullish(),text:oP.nullish(),position:I.nativeEnum(un).nullish(),shape:I.nativeEnum(un).nullish()}),iP=I.object({id:I.number().int(),requirements:fS}),aP=iP.array(),SS=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:Ku.optional(),requirements:fS.nullish().transform(r=>{if(r!==null)return r}),additionalElements:aP.nullish().transform(r=>{if(r!==null)return r})});var Cd=(g=>(g.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",g.FEW_WORDS="FEW_WORDS",g.STYLE_TAG="STYLE_TAG",g.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",g.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",g.NONE="NONE",g.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",g.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",g.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",g.PREFER_ASSERTION="PREFER_ASSERTION",g.HTML_ELEMENTS="HTML_ELEMENTS",g.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",g.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",g))(Cd||{}),yS=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(yS||{});var bS=I.object({thoughts:I.string(),category:I.nativeEnum(Cd)}),ES=I.object({thoughts:I.string(),category:I.nativeEnum(yS)}),sP=I.discriminatedUnion("op",[I.object({op:I.literal("replace"),path:I.string(),value:I.string()}),I.object({op:I.literal("add"),path:I.string(),value:I.string()}),I.object({op:I.literal("remove"),path:I.string()})]),d2=I.object({thoughts:I.string(),patches:sP.array()}),lP=[I.literal("add"),I.literal("replace"),I.literal("remove")],cP=I.object({op:I.union(lP),path:I.string(),value:lt.optional()}),TS=I.object({patches:cP.array(),thoughts:I.string()}),vS=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(vS||{}),AS=I.object({thoughts:I.string(),scenario:I.nativeEnum(vS),instructions:I.string().nullish()}),wS=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),m2=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),p2=I.object({observations:I.string(),reasoning:I.string(),command:Bs});var Rd=I.object({summary:I.string(),reasoning:I.string(),evaluation:I.discriminatedUnion("type",[I.object({type:I.literal("DONE")}),I.object({type:I.literal("RIGHT_TRACK")}),I.object({type:I.literal("WRONG_TRACK"),feedback:I.string()}),I.object({type:I.literal("IMPOSSIBLE")})])}),uP=I.object({startId:I.number().int(),endId:I.number().int()}),CS=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(CS||{}),RS=I.object({categoryThoughts:I.string(),category:I.nativeEnum(CS),relevantSections:uP.array()}),Jr=I.boolean().nullish().transform(r=>r??!1),xS=I.object({thoughts:I.string().optional(),isPageReady:Jr,descriptionLabels:I.object({usesTextContent:Jr,usesAppearance:Jr,usesPosition:Jr,usesRelativeElements:Jr,usesSingleQuotes:Jr,isAmbiguous:Jr,targetDoesNotExist:Jr,usesIcon:Jr}).optional()});import{z as P}from"zod";import*as oe from"zod";var b2=oe.object({thoughts:oe.string().optional().describe("only provided if a description was provided"),target:mn.optional().describe("only provided if a description was provided"),pageState:oe.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:oe.object({label:oe.string(),value:oe.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:oe.object({data:oe.string(),height:oe.number().int(),width:oe.number().int()}).optional().describe("only provided if returnScreenshot is true")}),MS=oe.union([oe.literal("ELEMENT_CHECK"),oe.literal("NEGATED_CHECK"),oe.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),oe.literal("SELECT_OPTION"),oe.literal("TYPE")]);function ca(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 ua=(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))(ua||{}),Ko=oe.object({matched:oe.boolean(),reason:oe.string().optional().describe("Human understandable description"),logs:oe.string().array().optional().describe("Logs for debugging")}),dP=Ko.extend({type:oe.literal("USER_SELECTOR")}),mP=Ko.extend({type:oe.literal("CSS_SELECTOR"),selectors:oe.string().array()}),pP=Ko.extend({type:oe.literal("HYBRID_SELECTOR")}),gP=Ko.extend({type:oe.literal("HTML_DISTANCE"),distance:oe.number().optional(),closestElement:oe.string().optional(),savedElement:oe.string().optional()}),hP=Ko.extend({type:oe.literal("TEMPLATE_MATCHING"),elementImageUrl:oe.string().url()}),fP=Ko.extend({type:oe.literal("AUTO_FRAME"),logs:oe.string().array().optional()}),_S=oe.discriminatedUnion("type",[dP,mP,pP,gP,hP,fP]);import{z as ga}from"zod";import{z as xP}from"zod";import*as V from"zod";import{extendZodWithOpenApi as bP}from"zod-openapi";import{cloneDeep as P2}from"lodash-es";import O2 from"truncate-json";import*as no from"zod";import{extendZodWithOpenApi as yP}from"zod-openapi";import{z as Ct}from"zod";import{z as ne}from"zod";var xd=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.union([ne.boolean(),ne.literal("always")]).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 PS=1e4,IS=6e4,SP=ne.object({server:ne.string(),username:ne.string().optional(),password:ne.string().optional()}),to=xd.extend({pageLoadTimeoutMs:ne.number().optional().refine(r=>r===void 0||r<=IS&&r>=-1,{message:`Page load timeout must be between 0 and ${IS/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<=PS&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${PS/1e3} seconds`}),localChromeExtensionPaths:ne.string().array().optional(),extraHeaders:ne.record(ne.string(),ne.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:ne.record(ne.string(),ne.record(ne.string(),ne.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:ne.string().optional(),disableGpu:ne.boolean().optional(),disableBrowserMonitoring:ne.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),disableConsoleLogs:ne.boolean().optional().describe("Disable console log recording in the run viewer."),disableNetworkLogs:ne.boolean().optional().describe("Disable network request recording in the run viewer."),bustCacheOnBoundingBoxChange:ne.boolean().optional().describe("This setting is deprecated. Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree: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."),proxy:SP.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency."),disableFullStory:ne.boolean().optional().describe("Disable FullStory, a third-party analytics tool that can significantly impact browser performance. This can be useful for testing sites that use FullStory.")});var Md="BASE_URL";var ro="ENV_NAME",Yo="TEST_NAME",C2={[Md]:"https://www.google.com"},OS=Ct.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),LS=Ct.object({name:Ct.string(),variables:Ct.record(Ct.string().describe("variable name"),Ct.string().describe("variable value"))}),NS=Ct.object({name:Ct.string(),variables:Ct.record(Ct.string().describe("variable name"),Ct.unknown().describe("variable value")),browser:to.optional()});var R2=Ct.object({name:Ct.string(),variables:Ct.record(Ct.string().describe("variable name"),Ct.unknown().describe("variable value"))});yP(no);var _d=no.object({env:no.record(no.unknown())}).openapi({ref:"TestContextSnapshot"});var Ke=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ke||{}),Pd=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Pd||{});bP(V);var Id=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()}),EP=Id.extend({viewport:V.object({height:V.number(),width:V.number()}).nullish(),status:V.nativeEnum(Pd),message:V.string().optional(),elementInteracted:V.string().optional()}),oo=Id.extend({status:V.nativeEnum(Ke),message:V.string().optional(),data:V.unknown().optional(),beforeTestContext:_d.optional(),afterTestContext:_d.optional(),failureReason:V.nativeEnum(Ce).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"}),DS=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(DS||{}),Zs=oo.merge(Qt).extend({results:EP.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(()=>mt.array()).optional(),failureRecoveryStatus:V.object({type:V.nativeEnum(DS),message:V.string()}).optional()}),TP=oo.merge(Xn).extend({results:V.lazy(()=>Zs.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),vP=oo.merge(jo).extend({results:V.lazy(()=>Zs.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),AP=oo.merge(Yr).extend({moduleName:V.string().optional(),results:V.lazy(()=>mt.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),wP=oo.merge($o).extend({assertionResult:Zs.optional(),results:V.lazy(()=>mt.array()).describe("results for the block actually executed"),previousAttempts:V.lazy(()=>mt.array()).optional()}),CP=oo.merge(sa).extend({results:V.lazy(()=>mt.array()),healingAttempts:V.lazy(()=>mt.array().array()).optional(),previousAttempts:V.lazy(()=>mt.array()).optional()}),mt=V.discriminatedUnion("type",[TP,vP,Zs,AP,wP,CP]),K2=oo.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),RP=Id.extend({index:V.number().optional(),userFacingStepReference:V.string().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)}),el=RP.extend({beforeScreenshot:V.string().optional(),afterScreenshot:V.string().optional()});var Od=xP.object({results:mt.array().describe("main results"),beforeResults:mt.array().optional(),afterResults:mt.array().optional()}),da=Od.partial();import{z as F}from"zod";import{extendZodWithOpenApi as NP}from"zod-openapi";var Xo=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Xo||{});import{isValidCron as MP}from"cron-validator";import{z as ae}from"zod";import{z as Ld}from"zod";var bn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(bn||{});var tl=Ld.object({width:Ld.number().min(200).max(1e4),height:Ld.number().min(200).max(1e4)}),kS={"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}},tY=Object.keys(kS);var En=kS["Desktop Large"],US="en-us",FS="America/Los_Angeles";var rl={latitude:37.7749,longitude:-122.4194};var BS=["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 zS=1e4,_P=to.extend({browserType:ae.nativeEnum(bn).optional(),slowMoMs:ae.number().optional().refine(r=>r===void 0||r<=zS&&r>=-1,{message:`Slow motion must be between 0 and ${zS} milliseconds`}),basicAuthorization:ae.object({username:ae.string().optional(),password:ae.string().optional()}).optional(),geolocation:ae.object({latitude:ae.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ae.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ae.boolean().optional(),locale:ae.string().optional(),timezone:ae.enum(BS).optional(),colorScheme:ae.enum(["light","dark"]).optional()});var Nd=ae.object({useMemory:ae.boolean().optional(),failureRecovery:ae.boolean().optional().describe("undefined means inherit org settings")}),PP=Nd.extend({disableAICaching:ae.boolean().optional(),failureRecoveryInstructions:ae.string().optional()}),IP=ae.object({viewport:tl.optional()}),ma=IP.merge(PP).merge(_P),Jo=ae.object({cron:ae.string().refine(r=>MP(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ae.boolean().default(!1),env:ae.string().optional(),timeZone:ae.string().default("America/Los_Angeles"),jobKey:ae.string().optional()}),Qo=ae.object({onSuccess:ae.boolean().default(!1),failureMessage:ae.string().optional(),onFailure:ae.boolean().default(!0),successMessage:ae.string().optional()}),OP=ae.object({name:ae.string(),required:ae.boolean().optional(),defaultValue:ae.string().describe("this is not optional because we need a value when the editor is first loaded")}),nl=OP.array(),LP=ae.object({name:ae.string(),value:ae.string()}),HS=LP.array(),ol=ae.object({name:ae.string(),default:ae.boolean().optional(),fixtures:OS.array().optional()});NP(F);var rr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Re=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(Re||{}),il=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(il||{});var tt=F.string().pipe(F.coerce.date()).or(F.date()),pa=F.object({id:F.string(),runKey:F.string(),organizationId:F.string(),executionType:F.nativeEnum(Xo).optional().default("WEB"),createdAt:tt,createdBy:F.string(),flake:F.boolean().nullish(),scheduledAt:tt.or(F.null()),startedAt:tt.or(F.null()),updatedAt:tt.nullish(),finishedAt:tt.or(F.null()),resolvedBaseUrl:F.string().nullish(),environmentName:F.string().nullish(),gitBranchName:F.string().nullish(),githubRepository:F.string().nullish(),gitlabProjectPath:F.string().nullish(),labels:F.array(F.string()).optional(),gitOriginUrl:F.string().nullish(),gitCommitSha:F.string().nullish(),gitCommitShaShort:F.string().nullish(),gitCommitAuthorName:F.string().nullish(),cliVersion:F.string().nullish(),section:F.nativeEnum(il).nullish(),status:F.nativeEnum(Re),trigger:F.nativeEnum(rr),attempts:F.number(),runAttempts:F.array(F.object({id:F.string(),status:F.nativeEnum(Re),startedAt:tt.or(F.null()),finishedAt:tt.or(F.null())})).optional(),videos:F.array(F.string()).optional(),failureReason:F.nativeEnum(Ce).nullish(),failureDetails:js.nullish(),failureRecoveryDetails:F.object({attempts:F.number()}).nullish(),pipelineId:F.string().nullish(),resolvedInputs:F.record(F.string(),F.string()).nullish(),quarantined:F.boolean().nullish().default(!1),quarantinedReason:F.string().nullish(),localTestId:F.string().nullish(),testId:F.string().nullish(),testName:F.string().nullish(),description:F.string().nullish(),test:F.object({name:F.string(),id:F.string()}).nullish().default(null),suiteId:F.string().nullish()}).openapi({ref:"RunMetadata"}),DP={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},al=pa.pick({...DP,test:!0}),GS=pa.omit({failureReason:!0,failureDetails:!0,test:!0}),Dd=pa.extend({stepsSnapshot:F.array(F.record(F.unknown())).nullish(),resolvedInputs:F.record(F.string(),F.string()).nullish(),test:F.object({name:F.string(),id:F.string(),description:F.string().nullish(),baseUrl:F.string().nullish(),advanced:ma.nullish()}).nullish()}).merge(Od);var kP=ga.object({id:ga.string().uuid(),startedAt:tt.or(ga.null()),finishedAt:tt.or(ga.null()),status:ga.nativeEnum(Re)}).merge(da),AY=kP.array();import{z as rt}from"zod";var UP=rt.object({id:rt.string(),status:rt.nativeEnum(Re),trigger:rt.nativeEnum(rr),createdAt:tt,startedAt:tt.nullish(),finishedAt:tt.nullish(),gitCommitSha:rt.string().nullish(),gitCommitShaShort:rt.string().nullish(),gitCommitTimestamp:tt.nullish(),gitBranchName:rt.string().nullish(),gitOriginUrl:rt.string().nullish(),gitCommitMessage:rt.string().nullish(),gitCommitAuthorName:rt.string().nullish(),githubRepository:rt.string().nullish(),gitlabProjectPath:rt.string().nullish(),pipelineId:rt.string().nullish(),cliVersion:rt.string().nullish(),labels:rt.string().array().optional(),suite:rt.object({id:rt.string(),name:rt.string()}).nullish(),runs:rt.object({status:rt.nativeEnum(Re)}).array()}).openapi({ref:"RunGroup"}),VS=UP.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:al.array()});import{z as pt}from"zod";var FP=pt.object({type:pt.literal("TARGETING"),name:pt.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:_S.array(),pageState:pt.string().optional(),targetSource:pt.nativeEnum(dn).optional(),targetUpdateTime:pt.string().optional()}),BP=pt.object({type:pt.literal("AI_LOCATION"),matched:pt.boolean(),pageState:pt.string().optional(),ragUsed:pt.boolean().optional(),thoughts:pt.string().optional()}),zP=pt.object({type:pt.literal("ASSERTION"),relevantElementsSerialized:pt.string().array().optional(),pageState:pt.string().optional(),ragUsed:pt.boolean().optional()}),HP=pt.discriminatedUnion("type",[FP,BP,zP]);import{z as Je}from"zod";var GP=Je.object({id:Je.string(),name:Je.string()}),UY=GP.merge(Je.object({createdAt:tt,createdBy:Je.string(),schedule:Jo,notification:Qo,environment:Je.object({name:Je.string()}).nullish(),beforeTests:Je.object({id:Je.string()}).array().nullish(),afterTests:Je.object({id:Je.string()}).array().nullish()})),WS=Je.object({id:Je.string().uuid(),orgId:Je.string(),createdAt:tt,startedAt:tt.or(Je.null()),finishedAt:tt.or(Je.null()),status:Je.nativeEnum(Re),trigger:Je.nativeEnum(rr),suite:Je.object({id:Je.string(),name:Je.string()}).nullish(),runs:pa.array()}),FY=WS.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),jS=WS.extend({runs:al.array()});import{z as nr}from"zod";import{cloneDeep as HY}from"lodash-es";import{z as Te}from"zod";var qY=Te.object({thoughts:Te.string(),subGoals:Te.object({instruction:Te.string()}).array()}),KY=Te.object({thoughts:Te.string(),newPlanMarkdown:Te.string()}),YY=Te.object({thoughts:Te.string(),correct:Te.boolean(),failedActionIndex:Te.number().optional()}),VP=Te.object({type:Te.literal("PLANNING"),beforePlan:Te.string(),goalDecision:Te.string(),thoughts:Te.string()}),WP=Te.object({type:Te.literal("RUNNING"),stepDisplayName:Te.string(),status:Te.nativeEnum(Ke),results:mt.array()}),jP=Te.object({type:Te.literal("REVISING"),beforePlan:Te.string(),afterPlan:Te.string(),errString:Te.string(),diffs:Te.string(),thoughts:Te.string()}),$P=Te.object({type:Te.literal("SYSTEM"),message:Te.string()}),qP=Te.discriminatedUnion("type",[VP,WP,jP,$P]),$S=qP.array();var eX=nr.object({id:nr.string(),scheduledAt:nr.coerce.date().nullable(),startedAt:nr.coerce.date().nullable(),finishedAt:nr.coerce.date().nullable(),status:nr.nativeEnum(Re),history:$S.nullable(),testPlan:nr.object({id:nr.string(),name:nr.string()}).nullable(),test:nr.object({id:nr.string(),name:nr.string()}).nullable()});import{z as Dt}from"zod";var kd=Dt.object({content:Dt.string(),ids:Dt.string().array(),tokenLength:Dt.number()}),KP=Dt.object({chunks:kd.array()}),SX=Dt.object({ids:Dt.string().array(),score:Dt.number(),tokenLength:Dt.number()}),yX=KP.extend({description:Dt.string().describe("Input to pass to RAG engine"),tokenLimit:Dt.number()}),qS=Dt.object({ids:Dt.number().array()}),KS=Dt.object({indices:Dt.number().array()});var ft=P.object({disableCache:P.boolean().optional(),useMemory:P.boolean().optional(),clientMode:P.enum(["interactive","runner"]).optional(),loggerTags:P.record(P.string(),P.string()).optional(),langfuseSessionId:P.string().optional(),agentConfigVersion:P.string().optional()}),RX=ft.extend({chunks:kd.array(),description:P.string().describe("Input to pass to AI"),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),softTokenLimit:P.number(),hardTokenLimit:P.number(),callId:P.string().optional()}),YP=P.object({screenshotBase64AfterCommand:P.string(),urlAfterCommand:P.string(),serializedCommand:P.string(),elementInteracted:P.string().optional(),thoughts:P.string().optional()}),YS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),source:MS.optional().catch(void 0),memory:P.discriminatedUnion("type",[Ls,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional()}),XS=P.object({target:P.string().or(P.number()),browserState:P.string().optional(),screenshot:P.string().optional(),boundingBox:P.object({x:P.number(),y:P.number(),height:P.number(),width:P.number()}).optional()}),JS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string().optional(),returnSchema:P.string().optional()}),XP=P.literal("NEGATED_CHECK"),QS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),url:P.string(),contextChoice:rd.optional(),memory:P.discriminatedUnion("type",[Ju,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional(),source:XP.optional()}),ZS=P.object({command:Vo}),ey=P.object({message:P.string()}),Ud=P.object({goal:P.string(),browserState:P.string(),startingScreenshot:P.string().optional(),screenshot:P.string(),url:P.string(),history:YP.array(),actionHint:P.string().optional(),lastError:P.string().optional()}),ty=P.object({results:el.array(),errorMessage:P.string(),errorStack:P.string().optional()}),ry=P.object({results:el.array(),goal:P.string(),errorMessage:P.string()}),ny=P.object({failedResults:el.array(),nextStepsSerialized:P.string().array(),currentUrl:P.string(),currentPageState:P.string(),currentScreenshot:P.string(),customInstructions:P.string().optional(),testDescription:P.string().optional()}),xX=P.object({description:P.string(),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),excerpt:P.string()}),oy=P.object({type:P.string(),browserContext:P.string(),currentStep:P.string(),screenshot:P.string()}),iy=P.object({description:P.string(),browserState:P.string(),screenshot:P.string()});import{z as ha}from"zod";var PX=ha.object({goal:ha.string()}),ay=ha.object({keywords:ha.array(ha.string())});import{z as Fd}from"zod";var sl=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(sl||{}),LX=Fd.nativeEnum(sl),JP=Fd.enum(["v1","v2","v3"]),NX=JP.or(Fd.string().describe("for people with special configurations"));var sy={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v3"};import{z as Be}from"zod";var ly=Be.object({attributesRequired:Be.array(Be.string()).optional(),textRequired:Be.boolean().optional(),boundsRequired:Be.boolean().optional()}),cy=Be.object({id:Be.number(),thoughts:Be.string(),inWebview:Be.boolean().optional(),requirements:ly.optional(),additionalElements:Be.object({id:Be.number(),requirements:ly}).array().optional()}),uy=Be.object({description:Be.string(),screenXml:Be.string(),screenshot:Be.string()}),dy=Be.object({assertion:Be.string(),screenXml:Be.string(),screenshot:Be.string()}),my=Be.object({thoughts:Be.string(),result:Be.boolean(),relevantElements:Be.array(Be.number()).optional()});import{z as io}from"zod";var py=io.object({id:io.string().uuid(),skipped:io.boolean().optional(),envKey:io.string().optional().describe("key in the environment to save the result of this step to")}),Bd=py.merge($n).extend({type:io.literal("REQUEST")}),zd=py.merge(ks).extend({type:io.literal("JAVASCRIPT")}),Hd=io.discriminatedUnion("type",[zd,Bd]);import{z as or}from"zod";var gy=or.object({id:or.string(),name:qo,description:or.string().optional().nullish(),baseUrl:Qs.nullish(),schemaVersion:or.string(),advanced:or.unknown().optional(),retries:or.number(),envs:or.array(ol).nullish(),parameters:nl.nullish()}),QP=or.object({createdAt:or.coerce.date(),updatedAt:or.coerce.date(),schedule:Jo.nullish(),notification:Qo.nullish(),createdBy:or.string(),organizationId:or.string()}),ZP=gy.merge(QP),o5=ZP.extend({steps:Hd.array()}),i5=gy.extend({steps:Hd.array()});import{z as Ht}from"zod";var hy=Ht.object({startedAt:Ht.coerce.date(),finishedAt:Ht.coerce.date(),status:Ht.nativeEnum(Ke),message:Ht.string().optional(),data:Ht.unknown().optional()}),eI=hy.merge(zd).extend({type:Ht.literal("JAVASCRIPT")}),tI=hy.merge(Bd).extend({type:Ht.literal("REQUEST")}),rI=Ht.discriminatedUnion("type",[eI,tI]),fy=Ht.object({startedAt:Ht.coerce.date(),finishedAt:Ht.coerce.date().nullish(),status:Ht.nativeEnum(Re),results:rI.array(),failureReason:Ht.string().nullish(),failureDetails:js.nullish()});import{z as Gt}from"zod";var nI=Gt.object({id:Gt.string(),organizationId:Gt.string(),createdAt:Gt.coerce.date(),updatedAt:Gt.coerce.date(),createdBy:Gt.string(),scheduledAt:Gt.coerce.date().nullish(),startedAt:Gt.coerce.date().nullish(),finishedAt:Gt.coerce.date().nullish(),status:Gt.nativeEnum(Re),trigger:Gt.nativeEnum(rr),results:fy.array().nullish(),apiTestName:Gt.string().nullish(),apiTestPath:Gt.string().nullish(),apiTestId:Gt.string().nullish()}),h5=nI.pick({status:!0,startedAt:!0,finishedAt:!0});var fa=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(fa||{}),Sy=3;function oI(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Gd(r){if(!oI(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 Vd(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return Sy;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 ll=class{trackStepExecution(){}async flush(){}};import{parseString as iI,splitCookiesString as aI}from"set-cookie-parser";import{z as we}from"zod";var Wd=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 cl(r,e){let t=[],n=aI(r);for(let o of n){let i=iI(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=Wd.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,m]=u.split("=");if(!d||!m)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...s,name:d,value:m})}}return t}var sI=we.object({origin:we.string(),localStorage:we.array(we.object({name:we.string(),value:we.string()}))}),lI=we.object({entries:we.record(we.string(),we.array(we.tuple([we.unknown(),we.unknown()]))),version:we.number().optional()}),yy=we.object({cookies:Wd.array().optional(),origins:sI.array().optional(),idb:we.record(we.string(),lI).optional().describe("key is db name")});function ul(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Wd.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{v4 as Zo}from"uuid";import ue from"zod";import{v4 as F5}from"uuid";import{z as B}from"zod";import*as z from"zod";var by=z.discriminatedUnion("type",[z.object({type:z.literal("SCREEN")}),z.object({type:z.literal("OPEN_APP")}),z.object({type:z.literal("OPEN_WEBVIEW")})]),Sa=z.object({type:z.literal("description"),description:z.string()}),Ey=z.object({type:z.literal("CUSTOM_COORDINATES"),startX:z.number().describe("Starting X coordinate in pixels"),startY:z.number().describe("Starting Y coordinate in pixels"),deltaPixels:z.number().describe("Number of pixels to scroll in the specified direction")}),jd=z.discriminatedUnion("type",[...by.options,z.object({type:z.literal("CUSTOM"),target:Sa}),Ey]);var cI=z.object({type:z.literal("coordinates"),xPercent:z.number(),yPercent:z.number()}),dl=z.discriminatedUnion("type",[Sa,cI]),Ty=z.object({requiredText:z.string().optional(),requiredAttributes:z.record(z.string(),z.string()).optional(),requiredBounds:z.boolean().optional()}),uI=z.object({xPath:z.string(),requirements:Ty.optional()}),dI=z.object({type:z.literal("CUSTOM"),target:Sa,cache:z.lazy(()=>vy).optional()}),mI=z.object({pixelDelta:z.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:z.union([by,dI,Ey]),direction:z.enum(["up","down"])}),vy=z.object({type:z.literal("NATIVE"),bounds:z.number().array(),resolvedDescription:z.string(),xPath:z.string(),elementOnlySerializedXml:z.string(),scrollDetails:mI.optional(),requirements:Ty.optional(),requiredRelatedElements:uI.array().optional(),memory:z.never().optional()}),pI=z.object({type:z.literal("WEBVIEW"),resolvedDescription:z.string(),xPath:z.string(),browserCache:mn.optional(),memory:z.never().optional()}),ml=z.union([vy,pI]);var Qr=(v=>(v.AI_CHECK="AI_CHECK",v.TAP="TAP",v.TYPE="TYPE",v.PRESS="PRESS",v.PRESS_KEYBOARD="PRESS_KEYBOARD",v.OPEN_APP="OPEN_APP",v.KILL_APP="KILL_APP",v.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",v.SWIPE="SWIPE",v.SCROLL_TO="SCROLL_TO",v.SCREEN_CHECK="SCREEN_CHECK",v.ELEMENT_CHECK="ELEMENT_CHECK",v.JAVASCRIPT="JAVASCRIPT",v.REQUEST="REQUEST",v.WAIT="WAIT",v.ADD_FILE="ADD_FILE",v.INSTALL_APP="INSTALL_APP",v.UNINSTALL_APP="UNINSTALL_APP",v.ADB="ADB",v.STATE="STATE",v))(Qr||{}),ya=(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))(ya||{}),qd=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(qd||{}),gI=B.object({updatedAt:B.coerce.date().optional()}),nt=B.object({id:B.string().uuid(),disableCache:B.boolean().optional()}),hI=nt.extend({type:B.literal("STATE")}),fI=nt.extend({type:B.literal("KILL_APP")}),ba=gI.extend({target:ml}),SI=nt.extend({type:B.literal("AI_CHECK"),assertion:B.string(),timeoutSecs:B.number().optional()}),Kd=nt.extend({type:B.literal("TAP"),target:dl,cache:ba.optional(),longPress:B.boolean().optional(),longPressDurationMs:B.number().optional(),doubleTap:B.boolean().optional(),doubleTapDelayMs:B.number().optional(),relativePosition:B.object({x:B.number(),y:B.number()}).optional()}),Yd=nt.extend({type:B.literal("TYPE"),target:dl.optional(),cache:ba.optional(),keyPressDelayMs:B.number().optional(),text:B.string(),clearContent:B.boolean().optional(),forceClearContent:B.boolean().optional()});var yI=nt.extend({type:B.literal("PRESS"),key:B.nativeEnum(ya),longPress:B.boolean().optional()}),bI=nt.extend({type:B.literal("PRESS_KEYBOARD"),key:B.nativeEnum(qd)}),EI=nt.extend({type:B.literal("OPEN_APP"),packageName:B.string(),activityName:B.string().optional(),intentExtras:B.string().optional()}),TI=nt.extend({type:B.literal("OPEN_NOTIFICATION_DRAWER")}),Xd=nt.extend({type:B.literal("SWIPE"),direction:B.enum(["up","down","left","right"]),scrollableElement:jd,cache:ba.optional(),viewportPercent:B.number().optional(),durationMs:B.number().optional()}),Jd=nt.extend({type:B.literal("SCROLL_TO"),target:Sa,direction:B.enum(["down","up"]),scrollableElement:jd,scrollStepPercent:B.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.8 (80%)."),cache:ba.optional()});var vI=B.object({type:B.literal("CONTENT"),negated:B.boolean().optional(),value:B.string()}),AI=nt.extend({type:B.literal("SCREEN_CHECK"),assertion:vI,timeout:B.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}),Qd=nt.extend({type:B.literal("ELEMENT_CHECK"),target:dl,cache:ba.optional(),assertion:Ds,timeout:B.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}),wI=nt.extend({type:B.literal("JAVASCRIPT"),code:B.string(),timeout:B.number().int().max(60).optional().describe("Max seconds for the code to complete")}),CI=nt.extend({type:B.literal("REQUEST")}).merge($n),RI=nt.extend({type:B.literal("WAIT"),timeoutSecs:B.number()}),xI=nt.extend({type:B.literal("ADB"),command:B.string(),jsonArgs:B.string().optional()}),MI=nt.extend({type:B.literal("ADD_FILE"),file:B.string(),storageLocation:B.string()}),_I=B.string().trim(),PI=nt.extend({type:B.literal("INSTALL_APP"),uri:_I}),II=nt.extend({type:B.literal("UNINSTALL_APP"),packageName:B.string()}),Ay=B.discriminatedUnion("type",[SI,Kd,Yd,yI,EI,TI,bI,Xd,Jd,AI,Qd,wI,CI,RI,MI,PI,II,fI,xI,hI]);var pl=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var OI=["SCREEN","OPEN_APP","OPEN_WEBVIEW","CUSTOM"],Cy=ue.object({type:ue.enum(OI).describe("Where to interact. SCREEN = entire device (use for system surfaces like the notification bar or quick settings), OPEN_APP = current foreground app, OPEN_WEBVIEW = active webview (only if a webview is present and there is high confidence that the element is inside it), CUSTOM = explicitly describe the container if and only if NONE of the above fit."),description:ue.string().or(ue.null()).describe("Description of the container to interact with. This is only used if the container type is CUSTOM.")}),LI=ue.object({type:ue.literal("TAP"),description:ue.string().describe("Description of the element to tap."),longPress:ue.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:ue.boolean().describe("Whether to tap twice in quick succession."),relativePosition:ue.null().or(ue.object({x:ue.number(),y:ue.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner.")}).describe(`
|
|
9
|
+
`)}`}};function Jf(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function dd(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 Ir=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},qs=class extends Ir{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Ks=class extends Ir{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function md(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}var pd="Element to be clicked has no bounding box";function Qf(r){return r instanceof Error?r.message.startsWith(pd):!1}function gd(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 hd(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 aa=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var C_={CLICK:"Click on an element on the page.",TYPE:"Focus the element then type the specified text into an input on the page.",PRESS:"Press one or more keyboard keys.",KEY_DOWN:"Hold down one or more keyboard keys.",KEY_UP:"Release one or more keyboard keys.",SELECT_OPTION:"Choose an option from a native <select> component. Never use this command for non <select> elements. Instead, use a series of CLICK commands for those.",NAVIGATE:"Go to the specified fully qualified URL.",SCROLL_UP:"Scroll up.",SCROLL_DOWN:"Scroll down.",GO_BACK:"Go back to the previous page.",HOVER:"Hover over an element.",AI_ASSERTION:"Verify a statement about the current page, retrying until it is true. Only generate an assertion if the goal includes language like 'check that', 'verify that', etc..",WAIT:"Wait a fixed amount of seconds.",DRAG:"Drag an element from one location and drop it onto another element.",JAVASCRIPT:"Execute JavaScript code in NODE or BROWSER environment.",ELEMENT_CHECK:"Perform a manual assertion on a specific element.",PAGE_CHECK:"Perform a manual case sensitive assertion on the page's html.",NEW_TAB:"Open a new browser tab with the specified URL.",WAIT_FOR_URL:"Wait for the URL to match a pattern.",AI_EXTRACT:"Extract data from the page and optionally store it in an environment variable.",COPY:"Copy the specified text value to the browser clipboard.",GO_FORWARD:"Navigate forward to the next page in the browser history (if available). Only use this after having navigated back with GO_BACK. Do not use this to navigate to a different page - use NAVIGATE instead.",LOCAL_STORAGE:"Set or get a value in the browser's localStorage. Use this to store data that persists across page reloads or to read stored values.",MOUSE_DRAG:"Drag the mouse from a starting point (or element) in a specific direction by pixel amounts. Prefer using DRAG (drag and drop between elements) instead unless the user explicitly requests dragging in a direction or by pixels. Use this when dragging needs to move a specific distance rather than to a target element.",PASTE:"Paste the contents of the browser clipboard into the currently focused element. Use this after copying text with COPY or when pasting content that was previously copied.",REFRESH:"Reload the current page. Use this to refresh the page content or retry a failed operation.",REQUEST:"Make an HTTP API request to a specified URL. Use this to interact with REST APIs, send data to a server, or retrieve data from an endpoint. Supports GET, POST, PUT, DELETE, and PATCH methods with custom headers, query parameters, and request body.",GRAPHQL_REQUEST:"Make a GraphQL request to a specified URL. Provide the GraphQL query (or mutation), optional variables JSON, and any required headers. Use this for GraphQL APIs instead of REQUEST."};nd.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!C_[e])throw new Error(`Command type ${e} is missing a description`)});var Zf=T.object({type:T.literal("CLICK"),description:T.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:T.boolean().or(T.null()),rightClick:T.boolean().or(T.null())}),eS=T.object({type:T.literal("TYPE"),description:T.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:T.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:T.boolean().or(T.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:T.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),tS=T.object({type:T.literal("GO_BACK")}),R_=T.object({type:T.literal("GO_FORWARD")}),x_=T.object({type:T.literal("LOCAL_STORAGE"),key:T.string().describe("The localStorage key to set or get."),value:T.string().describe("The value to store in localStorage. If reading, this can be empty.")}),rS=T.object({type:T.literal("PRESS"),keys:T.array(T.string()).describe('The keys to press. Only use key names supported by the Playwright press method, such as "a", "ArrowLeft", "Meta", "Control", and "Enter". Multiple keys will be pressed together. Do not suggest platform-specific key combinations, such as CTRL+C.')}),nS=T.object({type:T.literal("SELECT_OPTION"),description:T.string().describe("Description of the <select> element to choose from. Only use this command to interact with native HTML <select> elements. You must use CLICK to select from any other HTML element, such as <input>, <div>, or custom elements."),option:T.discriminatedUnion("type",[T.object({type:T.literal("VALUE"),value:T.string()}),T.object({type:T.literal("LABEL"),label:T.string()}),T.object({type:T.literal("INDEX"),index:T.string().describe("Zero-based index of the option within the select.")})]).describe("Which option to select. Choose 1 of 3 strategies for selecting. By value is exactly matching the 'value' attribute. By label is exactly matching the 'label' attribute. By index is using the zero-based index of the option within the select.")}),oS=T.object({type:T.literal("NAVIGATE"),url:T.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),iS=T.object({type:T.literal("SCROLL"),y:T.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),aS=T.object({type:T.literal("WAIT"),timeout:T.number().describe("The number of seconds to wait.")}),sS=T.object({type:T.literal("AI_ASSERTION"),assertion:T.string().describe("The assertion to verify. This should be a statement verifiable based on the current page HTML or screenshot. Be specific enough that the assertion is not ambiguous or open to interpretation. Make sure the assertion aligns with what the user intends to verify."),timeout:T.number().describe("The max amount of seconds to wait for the assertion to be true. Respect user wishes but allow no more than 60. If unspecified, choose 5 for quick checks like form status, 10 for page loads, and 30 for actions that explicitly trigger a long time, like image generation.")}),lS=T.object({type:T.literal("HOVER"),description:T.string().describe("Description of the element to hover over. Prefer elements that have visible bounding boxes according to the screenshot, element class attribute, or child contents.")}),M_=T.object({type:T.literal("COPY"),value:T.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),__=T.object({type:T.literal("PASTE")}),P_=T.object({type:T.literal("REFRESH")}),I_=T.object({type:T.literal("REQUEST"),url:T.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:T.enum(["GET","POST","PUT","DELETE","PATCH"]).describe("The HTTP method to use. GET for retrieving data, POST for creating resources, PUT for updating resources, DELETE for removing resources, PATCH for partial updates."),headers:T.record(T.string(),T.string()).or(T.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:T.record(T.string(),T.string()).or(T.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:T.string().or(T.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:T.number().int().or(T.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),O_=T.object({type:T.literal("GRAPHQL_REQUEST"),url:T.string().describe("The URL of the GraphQL endpoint. Can be a full URL or relative path."),headers:T.record(T.string(),T.string()).or(T.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),query:T.string().describe("The GraphQL query or mutation string. Include any required fields and arguments."),variables:T.string().or(T.null()).describe("Optional JSON string of variables to pass with the GraphQL request."),timeout:T.number().int().or(T.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),cS=T.object({type:T.literal("DRAG"),fromDescription:T.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:T.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:T.number().positive().or(T.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),L_=T.object({type:T.literal("MOUSE_DRAG"),description:T.string().or(T.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:T.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:T.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:T.number().int().positive().or(T.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),N_=T.object({type:T.literal("JAVASCRIPT"),code:T.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:T.union([T.literal("NODE"),T.literal("BROWSER")]).or(T.null()).describe("Execution environment. Default is NODE."),timeout:T.number().or(T.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),D_=T.object({type:T.literal("AI_EXTRACT"),goal:T.string().describe("Description of what data to extract from the page. Be specific about what you want to extract and where to find it."),schema:T.string().or(T.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:T.string().or(T.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:T.string().or(T.null()).describe("URL or URL regex for the iframe to extract data from.")}),k_=T.object({type:T.literal("ELEMENT_CHECK"),description:T.string().describe("Description of the element to check."),assertionType:T.enum(["EXISTS","VISIBLE","CONTENT_CONTAINS","CONTENT_EQUALS"]).describe("The type of assertion. EXISTS checks if element exists, VISIBLE checks if visible, CONTENT_CONTAINS checks if text contains value, CONTENT_EQUALS checks if text equals value."),value:T.string().or(T.null()).describe("The value to check against (required for CONTENT assertions)."),negated:T.boolean().or(T.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),U_=T.object({type:T.literal("PAGE_CHECK"),value:T.string().describe("The text content to check for on the page."),negated:T.boolean().or(T.null()).describe("If true, checks that the content is NOT present."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the assertion to be true.")}),F_=T.object({type:T.literal("NEW_TAB"),url:T.string().describe("The URL to open in the new tab.")}),B_=T.object({type:T.literal("WAIT_FOR_URL"),matcher:T.discriminatedUnion("type",[T.object({type:T.literal("SUBSTRING"),url:T.string()}),T.object({type:T.literal("GLOB"),glob:T.string()}),T.object({type:T.literal("REGEX"),regex:T.string()}),T.object({type:T.literal("DOMAIN"),domain:T.string()})]).describe("How to match the URL."),caseInsensitive:T.boolean().or(T.null()),negated:T.boolean().or(T.null()).describe("Wait for the URL to NOT match instead."),timeout:T.number().or(T.null()).describe("Max seconds to wait for the URL.")}),fd=T.object({type:T.literal("SUCCESS")}),Sd=T.object({type:T.literal("FAILURE")}),uS=T.discriminatedUnion("type",[Zf,eS,rS,nS,oS,iS,aS,sS,lS,tS]),z_=T.discriminatedUnion("type",[...uS.options,cS]),Xs=T.discriminatedUnion("type",[Zf,eS,rS,nS,oS,iS,aS,sS,lS,tS,cS,N_,k_,U_,F_,B_,D_,M_,R_,x_,L_,__,P_,I_,O_]),lq=oa(Xs),cq=T.discriminatedUnion("type",[...Xs.options,fd,Sd]),uq=oa(T.discriminatedUnion("type",[...uS.options,fd,Sd])),dq=oa(T.discriminatedUnion("type",[...z_.options,fd,Sd])),mq=T.object({command:T.unknown(),thoughts:T.string()});import{z as yd}from"zod";import{extendZodWithOpenApi as V_}from"zod-openapi";import{z as dS}from"zod";import{extendZodWithOpenApi as H_}from"zod-openapi";import{z as Yn}from"zod";var Jt=Yn.object({index:Yn.number().optional().describe("global index within a test (in-order traversal)"),id:Yn.string(),skipped:Yn.boolean().optional(),envKey:Yn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Yn.boolean().optional(),retries:Yn.number().optional()});H_(dS);var G_=Jt.extend({type:dS.literal("PRESET_ACTION")}),Qt=G_.extend({command:Vo}).openapi({ref:"PresetAction"});V_(yd);var Xn=Jt.extend({type:yd.literal("AI_ACTION"),text:yd.string(),steps:Qt.array().optional()}).openapi({ref:"AIAction"});import{z as Lt}from"zod";import{z as Js}from"zod";import{extendZodWithOpenApi as W_}from"zod-openapi";W_(Js);var jo=Jt.extend({type:Js.literal("AI_ACTION_DYNAMIC"),text:Js.string(),retries:Js.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as mS}from"zod";var bd=Jt.extend({type:mS.literal("CONDITIONAL"),skipped:mS.boolean().optional()});import{z as ge}from"zod";var j_=ge.object({cacheKey:ge.string(),cacheExpiryMs:ge.number()}),Ed=Jt.extend({id:ge.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ge.record(ge.string()).optional(),cacheConfig:j_.optional()}),Yr=Ed.extend({type:ge.literal("MODULE"),moduleId:ge.string().uuid()}),$_=ge.union([Yr.pick({type:!0,moduleId:!0}),ge.record(ge.unknown())]),q_=ge.object({type:ge.literal("URL_REGEX"),regex:ge.string()}),K_=ge.object({type:ge.literal("PAGE_CHECK"),substring:ge.string()}),Td=ge.object({cacheInvalidation:ge.discriminatedUnion("type",[K_,q_]).optional()}),Zt=ge.object({moduleId:ge.string().uuid(),name:ge.string(),description:ge.string().nullish(),enabled:ge.boolean().nullish(),parameters:ge.string().array().nullish(),defaultParameters:ge.record(ge.string(),ge.string()).nullish(),parameterEnums:ge.record(ge.string(),ge.string().array()).nullish(),defaultCacheKey:ge.string().nullish(),defaultCacheTtl:ge.number().nullish(),defaultCacheAllInvocations:ge.boolean().nullish(),autoAuth:ge.boolean().nullish(),advanced:Td.nullish()});import{z as er}from"zod";var pS=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(pS||{});var Y_=er.discriminatedUnion("type",[er.object({type:er.literal("NAVIGATE_URL"),url:er.string().url()}),er.object({type:er.literal("GO_TO_SECTION_START")})]),X_=er.object({trigger:er.nativeEnum(pS).optional(),attempts:er.number().int().optional(),restartBehavior:Y_}),sa=Jt.extend({type:er.literal("SECTION"),description:er.string().describe("user provided goal of what the section should accomplish"),plan:er.string().array().optional(),autohealingConfig:X_.optional()});var gS=Zt.merge(Ed).extend({type:Lt.literal("RESOLVED_MODULE"),steps:Lt.lazy(()=>lt.array())}),vd=Zt.extend({steps:Lt.lazy(()=>lt.array())}),Ad=sa.extend({steps:Lt.lazy(()=>Nt.array())}),J_=sa.extend({steps:Lt.lazy(()=>lt.array())}),$o=bd.extend({blocks:Lt.object({assertion:Lt.lazy(()=>Qt),steps:Lt.lazy(()=>Nt.array())}).array(),elseSteps:Lt.lazy(()=>Nt.array().optional())}),Q_=bd.extend({blocks:Lt.object({assertion:Lt.lazy(()=>Qt),steps:Lt.lazy(()=>lt.array())}).array(),elseSteps:Lt.lazy(()=>lt.array().optional())}),Nt=Lt.discriminatedUnion("type",[Qt,Xn,jo,Yr,$o,Ad]),lt=Lt.discriminatedUnion("type",[Qt,Xn,jo,gS,Q_,J_]);import{z as tr}from"zod";var Z_=tr.object({steps:Nt.array(),beforeSteps:Nt.array().nullish(),afterSteps:Nt.array().nullish()}),Jn=tr.object({steps:lt.array(),beforeSteps:lt.array().nullish(),afterSteps:lt.array().nullish()}),Qn=tr.object({steps:tr.record(tr.string(),tr.unknown()).array(),beforeSteps:tr.record(tr.string(),tr.unknown()).array().nullish(),afterSteps:tr.record(tr.string(),tr.unknown()).array().nullish()});var yn="1.0.22",Zn="0.0.2";import{z as wt}from"zod";import{z as eo}from"zod";var eP=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Xr=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 qo=eo.string().min(1).max(255).superRefine((r,e)=>{try{la(r)}catch(t){return e.addIssue({code:eo.ZodIssueCode.custom,message:t.message,fatal:!0}),eo.NEVER}});function la(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(eP))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Qs=eo.preprocess(r=>r===null?"":r,eo.union([eo.string().url(),eo.literal("")])).optional();var tP=["AI_EXTRACT","JAVASCRIPT","REQUEST","GRAPHQL_REQUEST","AUTH_SAVE","COPY"],rP=wt.object({id:wt.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:qo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:wt.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."),nP=wt.object({selector:rP,inputs:wt.record(wt.string()).or(wt.null())}),MK=wt.object({type:wt.literal("PRESET_ACTION"),action:Xs,envKey:wt.string().or(wt.null()).describe(`key in the environment to save the result of this step to. Only use this for ${tP.join(" or ")} steps.`)}),_K=wt.object({type:wt.literal("MODULE"),module:nP}),PK=wt.object({type:wt.literal("AI_ACTION_DYNAMIC"),text:wt.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var hS=I.object({phrase:I.string()}),wd=I.object({thoughts:I.string().optional(),result:I.union([I.literal("NOT_FOUND"),I.string(),I.number(),I.array(I.unknown()),I.record(I.unknown(),I.unknown()),I.unknown()])}),d2=I.object({text:I.string()}),oP=I.boolean().or(I.nativeEnum(un)).transform(r=>!(!r||r==="irrelevant")),fS=I.object({attributes:I.array(I.string()).nullish(),text:oP.nullish(),position:I.nativeEnum(un).nullish(),shape:I.nativeEnum(un).nullish()}),iP=I.object({id:I.number().int(),requirements:fS}),aP=iP.array(),SS=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:Ku.optional(),requirements:fS.nullish().transform(r=>{if(r!==null)return r}),additionalElements:aP.nullish().transform(r=>{if(r!==null)return r})});var Cd=(g=>(g.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",g.FEW_WORDS="FEW_WORDS",g.STYLE_TAG="STYLE_TAG",g.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",g.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",g.NONE="NONE",g.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",g.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",g.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",g.PREFER_ASSERTION="PREFER_ASSERTION",g.HTML_ELEMENTS="HTML_ELEMENTS",g.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",g.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",g))(Cd||{}),yS=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(yS||{});var bS=I.object({thoughts:I.string(),category:I.nativeEnum(Cd)}),ES=I.object({thoughts:I.string(),category:I.nativeEnum(yS)}),sP=I.discriminatedUnion("op",[I.object({op:I.literal("replace"),path:I.string(),value:I.string()}),I.object({op:I.literal("add"),path:I.string(),value:I.string()}),I.object({op:I.literal("remove"),path:I.string()})]),m2=I.object({thoughts:I.string(),patches:sP.array()}),lP=[I.literal("add"),I.literal("replace"),I.literal("remove")],cP=I.object({op:I.union(lP),path:I.string(),value:lt.optional()}),TS=I.object({patches:cP.array(),thoughts:I.string()}),vS=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(vS||{}),AS=I.object({thoughts:I.string(),scenario:I.nativeEnum(vS),instructions:I.string().nullish()}),wS=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),p2=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),g2=I.object({observations:I.string(),reasoning:I.string(),command:Bs});var Rd=I.object({summary:I.string(),reasoning:I.string(),evaluation:I.discriminatedUnion("type",[I.object({type:I.literal("DONE")}),I.object({type:I.literal("RIGHT_TRACK")}),I.object({type:I.literal("WRONG_TRACK"),feedback:I.string()}),I.object({type:I.literal("IMPOSSIBLE")})])}),uP=I.object({startId:I.number().int(),endId:I.number().int()}),CS=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(CS||{}),RS=I.object({categoryThoughts:I.string(),category:I.nativeEnum(CS),relevantSections:uP.array()}),Jr=I.boolean().nullish().transform(r=>r??!1),xS=I.object({thoughts:I.string().optional(),isPageReady:Jr,descriptionLabels:I.object({usesTextContent:Jr,usesAppearance:Jr,usesPosition:Jr,usesRelativeElements:Jr,usesSingleQuotes:Jr,isAmbiguous:Jr,targetDoesNotExist:Jr,usesIcon:Jr}).optional()});import{z as P}from"zod";import*as oe from"zod";var E2=oe.object({thoughts:oe.string().optional().describe("only provided if a description was provided"),target:mn.optional().describe("only provided if a description was provided"),pageState:oe.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:oe.object({label:oe.string(),value:oe.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:oe.object({data:oe.string(),height:oe.number().int(),width:oe.number().int()}).optional().describe("only provided if returnScreenshot is true")}),MS=oe.union([oe.literal("ELEMENT_CHECK"),oe.literal("NEGATED_CHECK"),oe.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),oe.literal("SELECT_OPTION"),oe.literal("TYPE")]);function ca(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 ua=(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))(ua||{}),Ko=oe.object({matched:oe.boolean(),reason:oe.string().optional().describe("Human understandable description"),logs:oe.string().array().optional().describe("Logs for debugging")}),dP=Ko.extend({type:oe.literal("USER_SELECTOR")}),mP=Ko.extend({type:oe.literal("CSS_SELECTOR"),selectors:oe.string().array()}),pP=Ko.extend({type:oe.literal("HYBRID_SELECTOR")}),gP=Ko.extend({type:oe.literal("HTML_DISTANCE"),distance:oe.number().optional(),closestElement:oe.string().optional(),savedElement:oe.string().optional()}),hP=Ko.extend({type:oe.literal("TEMPLATE_MATCHING"),elementImageUrl:oe.string().url()}),fP=Ko.extend({type:oe.literal("AUTO_FRAME"),logs:oe.string().array().optional()}),_S=oe.discriminatedUnion("type",[dP,mP,pP,gP,hP,fP]);import{z as ga}from"zod";import{z as xP}from"zod";import*as V from"zod";import{extendZodWithOpenApi as bP}from"zod-openapi";import{cloneDeep as I2}from"lodash-es";import L2 from"truncate-json";import*as no from"zod";import{extendZodWithOpenApi as yP}from"zod-openapi";import{z as Ct}from"zod";import{z as ne}from"zod";var xd=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.union([ne.boolean(),ne.literal("always")]).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 PS=1e4,IS=6e4,SP=ne.object({server:ne.string(),username:ne.string().optional(),password:ne.string().optional()}),to=xd.extend({pageLoadTimeoutMs:ne.number().optional().refine(r=>r===void 0||r<=IS&&r>=-1,{message:`Page load timeout must be between 0 and ${IS/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<=PS&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${PS/1e3} seconds`}),localChromeExtensionPaths:ne.string().array().optional(),extraHeaders:ne.record(ne.string(),ne.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:ne.record(ne.string(),ne.record(ne.string(),ne.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:ne.string().optional(),disableGpu:ne.boolean().optional(),disableBrowserMonitoring:ne.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),disableConsoleLogs:ne.boolean().optional().describe("Disable console log recording in the run viewer."),disableNetworkLogs:ne.boolean().optional().describe("Disable network request recording in the run viewer."),bustCacheOnBoundingBoxChange:ne.boolean().optional().describe("This setting is deprecated. Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree: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."),proxy:SP.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency."),disableFullStory:ne.boolean().optional().describe("Disable FullStory, a third-party analytics tool that can significantly impact browser performance. This can be useful for testing sites that use FullStory.")});var Md="BASE_URL";var ro="ENV_NAME",Yo="TEST_NAME",R2={[Md]:"https://www.google.com"},OS=Ct.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),LS=Ct.object({name:Ct.string(),variables:Ct.record(Ct.string().describe("variable name"),Ct.string().describe("variable value"))}),NS=Ct.object({name:Ct.string(),variables:Ct.record(Ct.string().describe("variable name"),Ct.unknown().describe("variable value")),browser:to.optional()});var x2=Ct.object({name:Ct.string(),variables:Ct.record(Ct.string().describe("variable name"),Ct.unknown().describe("variable value"))});yP(no);var _d=no.object({env:no.record(no.unknown())}).openapi({ref:"TestContextSnapshot"});var Ke=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ke||{}),Pd=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Pd||{});bP(V);var Id=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()}),EP=Id.extend({viewport:V.object({height:V.number(),width:V.number()}).nullish(),status:V.nativeEnum(Pd),message:V.string().optional(),elementInteracted:V.string().optional()}),oo=Id.extend({status:V.nativeEnum(Ke),message:V.string().optional(),data:V.unknown().optional(),beforeTestContext:_d.optional(),afterTestContext:_d.optional(),failureReason:V.nativeEnum(Ce).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"}),DS=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(DS||{}),Zs=oo.merge(Qt).extend({results:EP.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(()=>mt.array()).optional(),failureRecoveryStatus:V.object({type:V.nativeEnum(DS),message:V.string()}).optional()}),TP=oo.merge(Xn).extend({results:V.lazy(()=>Zs.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),vP=oo.merge(jo).extend({results:V.lazy(()=>Zs.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),AP=oo.merge(Yr).extend({moduleName:V.string().optional(),results:V.lazy(()=>mt.array()),previousAttempts:V.lazy(()=>mt.array()).optional()}),wP=oo.merge($o).extend({assertionResult:Zs.optional(),results:V.lazy(()=>mt.array()).describe("results for the block actually executed"),previousAttempts:V.lazy(()=>mt.array()).optional()}),CP=oo.merge(sa).extend({results:V.lazy(()=>mt.array()),healingAttempts:V.lazy(()=>mt.array().array()).optional(),previousAttempts:V.lazy(()=>mt.array()).optional()}),mt=V.discriminatedUnion("type",[TP,vP,Zs,AP,wP,CP]),Y2=oo.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),RP=Id.extend({index:V.number().optional(),userFacingStepReference:V.string().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)}),el=RP.extend({beforeScreenshot:V.string().optional(),afterScreenshot:V.string().optional()});var Od=xP.object({results:mt.array().describe("main results"),beforeResults:mt.array().optional(),afterResults:mt.array().optional()}),da=Od.partial();import{z as F}from"zod";import{extendZodWithOpenApi as NP}from"zod-openapi";var Xo=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Xo||{});import{isValidCron as MP}from"cron-validator";import{z as ae}from"zod";import{z as Ld}from"zod";var bn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(bn||{});var tl=Ld.object({width:Ld.number().min(200).max(1e4),height:Ld.number().min(200).max(1e4)}),kS={"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}},rY=Object.keys(kS);var En=kS["Desktop Large"],US="en-us",FS="America/Los_Angeles";var rl={latitude:37.7749,longitude:-122.4194};var BS=["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 zS=1e4,_P=to.extend({browserType:ae.nativeEnum(bn).optional(),slowMoMs:ae.number().optional().refine(r=>r===void 0||r<=zS&&r>=-1,{message:`Slow motion must be between 0 and ${zS} milliseconds`}),basicAuthorization:ae.object({username:ae.string().optional(),password:ae.string().optional()}).optional(),geolocation:ae.object({latitude:ae.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ae.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ae.boolean().optional(),locale:ae.string().optional(),timezone:ae.enum(BS).optional(),colorScheme:ae.enum(["light","dark"]).optional()});var Nd=ae.object({useMemory:ae.boolean().optional(),failureRecovery:ae.boolean().optional().describe("undefined means inherit org settings")}),PP=Nd.extend({disableAICaching:ae.boolean().optional(),failureRecoveryInstructions:ae.string().optional()}),IP=ae.object({viewport:tl.optional()}),ma=IP.merge(PP).merge(_P),Jo=ae.object({cron:ae.string().refine(r=>MP(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ae.boolean().default(!1),env:ae.string().optional(),timeZone:ae.string().default("America/Los_Angeles"),jobKey:ae.string().optional()}),Qo=ae.object({onSuccess:ae.boolean().default(!1),failureMessage:ae.string().optional(),onFailure:ae.boolean().default(!0),successMessage:ae.string().optional()}),OP=ae.object({name:ae.string(),required:ae.boolean().optional(),defaultValue:ae.string().describe("this is not optional because we need a value when the editor is first loaded")}),nl=OP.array(),LP=ae.object({name:ae.string(),value:ae.string()}),HS=LP.array(),ol=ae.object({name:ae.string(),default:ae.boolean().optional(),fixtures:OS.array().optional()});NP(F);var rr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},Re=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(Re||{}),il=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(il||{});var tt=F.string().pipe(F.coerce.date()).or(F.date()),pa=F.object({id:F.string(),runKey:F.string(),organizationId:F.string(),executionType:F.nativeEnum(Xo).optional().default("WEB"),createdAt:tt,createdBy:F.string(),flake:F.boolean().nullish(),scheduledAt:tt.or(F.null()),startedAt:tt.or(F.null()),updatedAt:tt.nullish(),finishedAt:tt.or(F.null()),resolvedBaseUrl:F.string().nullish(),environmentName:F.string().nullish(),gitBranchName:F.string().nullish(),githubRepository:F.string().nullish(),gitlabProjectPath:F.string().nullish(),labels:F.array(F.string()).optional(),gitOriginUrl:F.string().nullish(),gitCommitSha:F.string().nullish(),gitCommitShaShort:F.string().nullish(),gitCommitAuthorName:F.string().nullish(),cliVersion:F.string().nullish(),section:F.nativeEnum(il).nullish(),status:F.nativeEnum(Re),trigger:F.nativeEnum(rr),attempts:F.number(),runAttempts:F.array(F.object({id:F.string(),status:F.nativeEnum(Re),startedAt:tt.or(F.null()),finishedAt:tt.or(F.null())})).optional(),videos:F.array(F.string()).optional(),failureReason:F.nativeEnum(Ce).nullish(),failureDetails:js.nullish(),failureRecoveryDetails:F.object({attempts:F.number()}).nullish(),pipelineId:F.string().nullish(),resolvedInputs:F.record(F.string(),F.string()).nullish(),quarantined:F.boolean().nullish().default(!1),quarantinedReason:F.string().nullish(),localTestId:F.string().nullish(),testId:F.string().nullish(),testName:F.string().nullish(),description:F.string().nullish(),test:F.object({name:F.string(),id:F.string()}).nullish().default(null),suiteId:F.string().nullish()}).openapi({ref:"RunMetadata"}),DP={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},al=pa.pick({...DP,test:!0}),GS=pa.omit({failureReason:!0,failureDetails:!0,test:!0}),Dd=pa.extend({stepsSnapshot:F.array(F.record(F.unknown())).nullish(),resolvedInputs:F.record(F.string(),F.string()).nullish(),test:F.object({name:F.string(),id:F.string(),description:F.string().nullish(),baseUrl:F.string().nullish(),advanced:ma.nullish()}).nullish()}).merge(Od);var kP=ga.object({id:ga.string().uuid(),startedAt:tt.or(ga.null()),finishedAt:tt.or(ga.null()),status:ga.nativeEnum(Re)}).merge(da),wY=kP.array();import{z as rt}from"zod";var UP=rt.object({id:rt.string(),status:rt.nativeEnum(Re),trigger:rt.nativeEnum(rr),createdAt:tt,startedAt:tt.nullish(),finishedAt:tt.nullish(),gitCommitSha:rt.string().nullish(),gitCommitShaShort:rt.string().nullish(),gitCommitTimestamp:tt.nullish(),gitBranchName:rt.string().nullish(),gitOriginUrl:rt.string().nullish(),gitCommitMessage:rt.string().nullish(),gitCommitAuthorName:rt.string().nullish(),githubRepository:rt.string().nullish(),gitlabProjectPath:rt.string().nullish(),pipelineId:rt.string().nullish(),cliVersion:rt.string().nullish(),labels:rt.string().array().optional(),suite:rt.object({id:rt.string(),name:rt.string()}).nullish(),runs:rt.object({status:rt.nativeEnum(Re)}).array()}).openapi({ref:"RunGroup"}),VS=UP.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:al.array()});import{z as pt}from"zod";var FP=pt.object({type:pt.literal("TARGETING"),name:pt.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:_S.array(),pageState:pt.string().optional(),targetSource:pt.nativeEnum(dn).optional(),targetUpdateTime:pt.string().optional()}),BP=pt.object({type:pt.literal("AI_LOCATION"),matched:pt.boolean(),pageState:pt.string().optional(),ragUsed:pt.boolean().optional(),thoughts:pt.string().optional()}),zP=pt.object({type:pt.literal("ASSERTION"),relevantElementsSerialized:pt.string().array().optional(),pageState:pt.string().optional(),ragUsed:pt.boolean().optional()}),HP=pt.discriminatedUnion("type",[FP,BP,zP]);import{z as Je}from"zod";var GP=Je.object({id:Je.string(),name:Je.string()}),FY=GP.merge(Je.object({createdAt:tt,createdBy:Je.string(),schedule:Jo,notification:Qo,environment:Je.object({name:Je.string()}).nullish(),beforeTests:Je.object({id:Je.string()}).array().nullish(),afterTests:Je.object({id:Je.string()}).array().nullish()})),WS=Je.object({id:Je.string().uuid(),orgId:Je.string(),createdAt:tt,startedAt:tt.or(Je.null()),finishedAt:tt.or(Je.null()),status:Je.nativeEnum(Re),trigger:Je.nativeEnum(rr),suite:Je.object({id:Je.string(),name:Je.string()}).nullish(),runs:pa.array()}),BY=WS.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),jS=WS.extend({runs:al.array()});import{z as nr}from"zod";import{cloneDeep as GY}from"lodash-es";import{z as Te}from"zod";var KY=Te.object({thoughts:Te.string(),subGoals:Te.object({instruction:Te.string()}).array()}),YY=Te.object({thoughts:Te.string(),newPlanMarkdown:Te.string()}),XY=Te.object({thoughts:Te.string(),correct:Te.boolean(),failedActionIndex:Te.number().optional()}),VP=Te.object({type:Te.literal("PLANNING"),beforePlan:Te.string(),goalDecision:Te.string(),thoughts:Te.string()}),WP=Te.object({type:Te.literal("RUNNING"),stepDisplayName:Te.string(),status:Te.nativeEnum(Ke),results:mt.array()}),jP=Te.object({type:Te.literal("REVISING"),beforePlan:Te.string(),afterPlan:Te.string(),errString:Te.string(),diffs:Te.string(),thoughts:Te.string()}),$P=Te.object({type:Te.literal("SYSTEM"),message:Te.string()}),qP=Te.discriminatedUnion("type",[VP,WP,jP,$P]),$S=qP.array();var tX=nr.object({id:nr.string(),scheduledAt:nr.coerce.date().nullable(),startedAt:nr.coerce.date().nullable(),finishedAt:nr.coerce.date().nullable(),status:nr.nativeEnum(Re),history:$S.nullable(),testPlan:nr.object({id:nr.string(),name:nr.string()}).nullable(),test:nr.object({id:nr.string(),name:nr.string()}).nullable()});import{z as Dt}from"zod";var kd=Dt.object({content:Dt.string(),ids:Dt.string().array(),tokenLength:Dt.number()}),KP=Dt.object({chunks:kd.array()}),yX=Dt.object({ids:Dt.string().array(),score:Dt.number(),tokenLength:Dt.number()}),bX=KP.extend({description:Dt.string().describe("Input to pass to RAG engine"),tokenLimit:Dt.number()}),qS=Dt.object({ids:Dt.number().array()}),KS=Dt.object({indices:Dt.number().array()});var ft=P.object({disableCache:P.boolean().optional(),useMemory:P.boolean().optional(),clientMode:P.enum(["interactive","runner"]).optional(),loggerTags:P.record(P.string(),P.string()).optional(),langfuseSessionId:P.string().optional(),agentConfigVersion:P.string().optional()}),xX=ft.extend({chunks:kd.array(),description:P.string().describe("Input to pass to AI"),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),softTokenLimit:P.number(),hardTokenLimit:P.number(),callId:P.string().optional()}),YP=P.object({screenshotBase64AfterCommand:P.string(),urlAfterCommand:P.string(),serializedCommand:P.string(),elementInteracted:P.string().optional(),thoughts:P.string().optional()}),YS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),source:MS.optional().catch(void 0),memory:P.discriminatedUnion("type",[Ls,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional()}),XS=P.object({target:P.string().or(P.number()),browserState:P.string().optional(),screenshot:P.string().optional(),boundingBox:P.object({x:P.number(),y:P.number(),height:P.number(),width:P.number()}).optional()}),JS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string().optional(),returnSchema:P.string().optional()}),XP=P.literal("NEGATED_CHECK"),QS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),url:P.string(),contextChoice:rd.optional(),memory:P.discriminatedUnion("type",[Ju,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional(),source:XP.optional()}),ZS=P.object({command:Vo}),ey=P.object({message:P.string()}),Ud=P.object({goal:P.string(),browserState:P.string(),startingScreenshot:P.string().optional(),screenshot:P.string(),url:P.string(),history:YP.array(),actionHint:P.string().optional(),lastError:P.string().optional()}),ty=P.object({results:el.array(),errorMessage:P.string(),errorStack:P.string().optional()}),ry=P.object({results:el.array(),goal:P.string(),errorMessage:P.string()}),ny=P.object({failedResults:el.array(),nextStepsSerialized:P.string().array(),currentUrl:P.string(),currentPageState:P.string(),currentScreenshot:P.string(),customInstructions:P.string().optional(),testDescription:P.string().optional()}),MX=P.object({description:P.string(),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),excerpt:P.string()}),oy=P.object({type:P.string(),browserContext:P.string(),currentStep:P.string(),screenshot:P.string()}),iy=P.object({description:P.string(),browserState:P.string(),screenshot:P.string()});import{z as ha}from"zod";var IX=ha.object({goal:ha.string()}),ay=ha.object({keywords:ha.array(ha.string())});import{z as Fd}from"zod";var sl=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(sl||{}),NX=Fd.nativeEnum(sl),JP=Fd.enum(["v1","v2","v3"]),DX=JP.or(Fd.string().describe("for people with special configurations"));var sy={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v3"};import{z as Be}from"zod";var ly=Be.object({attributesRequired:Be.array(Be.string()).optional(),textRequired:Be.boolean().optional(),boundsRequired:Be.boolean().optional()}),cy=Be.object({id:Be.number(),thoughts:Be.string(),inWebview:Be.boolean().optional(),requirements:ly.optional(),additionalElements:Be.object({id:Be.number(),requirements:ly}).array().optional()}),uy=Be.object({description:Be.string(),screenXml:Be.string(),screenshot:Be.string()}),dy=Be.object({assertion:Be.string(),screenXml:Be.string(),screenshot:Be.string()}),my=Be.object({thoughts:Be.string(),result:Be.boolean(),relevantElements:Be.array(Be.number()).optional()});import{z as io}from"zod";var py=io.object({id:io.string().uuid(),skipped:io.boolean().optional(),envKey:io.string().optional().describe("key in the environment to save the result of this step to")}),Bd=py.merge($n).extend({type:io.literal("REQUEST")}),zd=py.merge(ks).extend({type:io.literal("JAVASCRIPT")}),Hd=io.discriminatedUnion("type",[zd,Bd]);import{z as or}from"zod";var gy=or.object({id:or.string(),name:qo,description:or.string().optional().nullish(),baseUrl:Qs.nullish(),schemaVersion:or.string(),advanced:or.unknown().optional(),retries:or.number(),envs:or.array(ol).nullish(),parameters:nl.nullish()}),QP=or.object({createdAt:or.coerce.date(),updatedAt:or.coerce.date(),schedule:Jo.nullish(),notification:Qo.nullish(),createdBy:or.string(),organizationId:or.string()}),ZP=gy.merge(QP),i5=ZP.extend({steps:Hd.array()}),a5=gy.extend({steps:Hd.array()});import{z as Ht}from"zod";var hy=Ht.object({startedAt:Ht.coerce.date(),finishedAt:Ht.coerce.date(),status:Ht.nativeEnum(Ke),message:Ht.string().optional(),data:Ht.unknown().optional()}),eI=hy.merge(zd).extend({type:Ht.literal("JAVASCRIPT")}),tI=hy.merge(Bd).extend({type:Ht.literal("REQUEST")}),rI=Ht.discriminatedUnion("type",[eI,tI]),fy=Ht.object({startedAt:Ht.coerce.date(),finishedAt:Ht.coerce.date().nullish(),status:Ht.nativeEnum(Re),results:rI.array(),failureReason:Ht.string().nullish(),failureDetails:js.nullish()});import{z as Gt}from"zod";var nI=Gt.object({id:Gt.string(),organizationId:Gt.string(),createdAt:Gt.coerce.date(),updatedAt:Gt.coerce.date(),createdBy:Gt.string(),scheduledAt:Gt.coerce.date().nullish(),startedAt:Gt.coerce.date().nullish(),finishedAt:Gt.coerce.date().nullish(),status:Gt.nativeEnum(Re),trigger:Gt.nativeEnum(rr),results:fy.array().nullish(),apiTestName:Gt.string().nullish(),apiTestPath:Gt.string().nullish(),apiTestId:Gt.string().nullish()}),f5=nI.pick({status:!0,startedAt:!0,finishedAt:!0});var fa=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(fa||{}),Sy=3;function oI(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Gd(r){if(!oI(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 Vd(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return Sy;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 ll=class{trackStepExecution(){}async flush(){}};import{parseString as iI,splitCookiesString as aI}from"set-cookie-parser";import{z as we}from"zod";var Wd=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 cl(r,e){let t=[],n=aI(r);for(let o of n){let i=iI(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let u=i.sameSite.trim().toLowerCase();if(u==="strict")a="Strict";else if(u==="lax")a="Lax";else if(u==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${u}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=Wd.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(s);let c=[s.name,...Object.keys(s)].map(u=>u.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let u of l){let[d,m]=u.split("=");if(!d||!m)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...s,name:d,value:m})}}return t}var sI=we.object({origin:we.string(),localStorage:we.array(we.object({name:we.string(),value:we.string()}))}),lI=we.object({entries:we.record(we.string(),we.array(we.tuple([we.unknown(),we.unknown()]))),version:we.number().optional()}),yy=we.object({cookies:Wd.array().optional(),origins:sI.array().optional(),idb:we.record(we.string(),lI).optional().describe("key is db name")});function ul(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Wd.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{v4 as Zo}from"uuid";import ue from"zod";import{v4 as B5}from"uuid";import{z as B}from"zod";import*as z from"zod";var by=z.discriminatedUnion("type",[z.object({type:z.literal("SCREEN")}),z.object({type:z.literal("OPEN_APP")}),z.object({type:z.literal("OPEN_WEBVIEW")})]),Sa=z.object({type:z.literal("description"),description:z.string()}),Ey=z.object({type:z.literal("CUSTOM_COORDINATES"),startX:z.number().describe("Starting X coordinate in pixels"),startY:z.number().describe("Starting Y coordinate in pixels"),deltaPixels:z.number().describe("Number of pixels to scroll in the specified direction")}),jd=z.discriminatedUnion("type",[...by.options,z.object({type:z.literal("CUSTOM"),target:Sa}),Ey]);var cI=z.object({type:z.literal("coordinates"),xPercent:z.number(),yPercent:z.number()}),dl=z.discriminatedUnion("type",[Sa,cI]),Ty=z.object({requiredText:z.string().optional(),requiredAttributes:z.record(z.string(),z.string()).optional(),requiredBounds:z.boolean().optional()}),uI=z.object({xPath:z.string(),requirements:Ty.optional()}),dI=z.object({type:z.literal("CUSTOM"),target:Sa,cache:z.lazy(()=>vy).optional()}),mI=z.object({pixelDelta:z.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:z.union([by,dI,Ey]),direction:z.enum(["up","down"])}),vy=z.object({type:z.literal("NATIVE"),bounds:z.number().array(),resolvedDescription:z.string(),xPath:z.string(),elementOnlySerializedXml:z.string(),scrollDetails:mI.optional(),requirements:Ty.optional(),requiredRelatedElements:uI.array().optional(),memory:z.never().optional()}),pI=z.object({type:z.literal("WEBVIEW"),resolvedDescription:z.string(),xPath:z.string(),browserCache:mn.optional(),memory:z.never().optional()}),ml=z.union([vy,pI]);var Qr=(v=>(v.AI_CHECK="AI_CHECK",v.TAP="TAP",v.TYPE="TYPE",v.PRESS="PRESS",v.PRESS_KEYBOARD="PRESS_KEYBOARD",v.OPEN_APP="OPEN_APP",v.KILL_APP="KILL_APP",v.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",v.SWIPE="SWIPE",v.SCROLL_TO="SCROLL_TO",v.SCREEN_CHECK="SCREEN_CHECK",v.ELEMENT_CHECK="ELEMENT_CHECK",v.JAVASCRIPT="JAVASCRIPT",v.REQUEST="REQUEST",v.WAIT="WAIT",v.ADD_FILE="ADD_FILE",v.INSTALL_APP="INSTALL_APP",v.UNINSTALL_APP="UNINSTALL_APP",v.ADB="ADB",v.STATE="STATE",v))(Qr||{}),ya=(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))(ya||{}),qd=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(qd||{}),gI=B.object({updatedAt:B.coerce.date().optional()}),nt=B.object({id:B.string().uuid(),disableCache:B.boolean().optional()}),hI=nt.extend({type:B.literal("STATE")}),fI=nt.extend({type:B.literal("KILL_APP")}),ba=gI.extend({target:ml}),SI=nt.extend({type:B.literal("AI_CHECK"),assertion:B.string(),timeoutSecs:B.number().optional()}),Kd=nt.extend({type:B.literal("TAP"),target:dl,cache:ba.optional(),longPress:B.boolean().optional(),longPressDurationMs:B.number().optional(),doubleTap:B.boolean().optional(),doubleTapDelayMs:B.number().optional(),relativePosition:B.object({x:B.number(),y:B.number()}).optional()}),Yd=nt.extend({type:B.literal("TYPE"),target:dl.optional(),cache:ba.optional(),keyPressDelayMs:B.number().optional(),text:B.string(),clearContent:B.boolean().optional(),forceClearContent:B.boolean().optional()});var yI=nt.extend({type:B.literal("PRESS"),key:B.nativeEnum(ya),longPress:B.boolean().optional()}),bI=nt.extend({type:B.literal("PRESS_KEYBOARD"),key:B.nativeEnum(qd)}),EI=nt.extend({type:B.literal("OPEN_APP"),packageName:B.string(),activityName:B.string().optional(),intentExtras:B.string().optional()}),TI=nt.extend({type:B.literal("OPEN_NOTIFICATION_DRAWER")}),Xd=nt.extend({type:B.literal("SWIPE"),direction:B.enum(["up","down","left","right"]),scrollableElement:jd,cache:ba.optional(),viewportPercent:B.number().optional(),durationMs:B.number().optional()}),Jd=nt.extend({type:B.literal("SCROLL_TO"),target:Sa,direction:B.enum(["down","up"]),scrollableElement:jd,scrollStepPercent:B.number().min(.1).max(1).optional().describe("How much of the container height to scroll at each step (0.1 to 1.0). Default is 0.8 (80%)."),cache:ba.optional()});var vI=B.object({type:B.literal("CONTENT"),negated:B.boolean().optional(),value:B.string()}),AI=nt.extend({type:B.literal("SCREEN_CHECK"),assertion:vI,timeout:B.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}),Qd=nt.extend({type:B.literal("ELEMENT_CHECK"),target:dl,cache:ba.optional(),assertion:Ds,timeout:B.number().int().min(0).max(zo).optional().describe("max seconds to wait for the assertion to be true")}),wI=nt.extend({type:B.literal("JAVASCRIPT"),code:B.string(),timeout:B.number().int().max(60).optional().describe("Max seconds for the code to complete")}),CI=nt.extend({type:B.literal("REQUEST")}).merge($n),RI=nt.extend({type:B.literal("WAIT"),timeoutSecs:B.number()}),xI=nt.extend({type:B.literal("ADB"),command:B.string(),jsonArgs:B.string().optional()}),MI=nt.extend({type:B.literal("ADD_FILE"),file:B.string(),storageLocation:B.string()}),_I=B.string().trim(),PI=nt.extend({type:B.literal("INSTALL_APP"),uri:_I}),II=nt.extend({type:B.literal("UNINSTALL_APP"),packageName:B.string()}),Ay=B.discriminatedUnion("type",[SI,Kd,Yd,yI,EI,TI,bI,Xd,Jd,AI,Qd,wI,CI,RI,MI,PI,II,fI,xI,hI]);var pl=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var OI=["SCREEN","OPEN_APP","OPEN_WEBVIEW","CUSTOM"],Cy=ue.object({type:ue.enum(OI).describe("Where to interact. SCREEN = entire device (use for system surfaces like the notification bar or quick settings), OPEN_APP = current foreground app, OPEN_WEBVIEW = active webview (only if a webview is present and there is high confidence that the element is inside it), CUSTOM = explicitly describe the container if and only if NONE of the above fit."),description:ue.string().or(ue.null()).describe("Description of the container to interact with. This is only used if the container type is CUSTOM.")}),LI=ue.object({type:ue.literal("TAP"),description:ue.string().describe("Description of the element to tap."),longPress:ue.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:ue.boolean().describe("Whether to tap twice in quick succession."),relativePosition:ue.null().or(ue.object({x:ue.number(),y:ue.number()})).describe("Specific position to tap within the bounding box of the element, specified in pixels. E.g. 0,0 is the top left corner.")}).describe(`
|
|
10
10
|
Tap on an element on the screen.
|
|
11
11
|
`),NI=ue.object({type:ue.literal("PRESS"),key:ue.nativeEnum(ya)}).describe(`
|
|
12
12
|
Press a button on the device. Some buttons are physical (volume) while others are virtual (Back/Home/App Switcher).
|
|
@@ -16,15 +16,15 @@ ${this.decisions.map(e=>e.toString()).join(`
|
|
|
16
16
|
Swipe in a direction within a container (screen/app/webview).
|
|
17
17
|
`),FI=ue.object({type:ue.literal("SCROLL_TO"),targetDescription:ue.string().describe("Description of the element or text to scroll to inside the container. Scrolling up will bring you up in the page, and vice versa."),direction:ue.enum(["down","up"]).describe("Direction to scroll while searching for the target."),container:Cy,scrollStepPercent:ue.number().min(.1).max(1).nullish().describe("How much of the container height to scroll at each step (0.1 - 1). Defaults to 0.8 when omitted.")}).describe(`
|
|
18
18
|
Scroll within a container until the described target is visible. Scrolling up or down will scroll until it finds it or can't scroll anymore. There is no need to repeat the same scroll to command in the same direction multiple times in a row. If a scroll fails, we do not restore the position automatically.
|
|
19
|
-
`),Zd=ue.discriminatedUnion("type",[LI,NI,DI,kI,UI,FI]),wy=r=>{switch(r.type){case"SCREEN":return{type:"SCREEN"};case"OPEN_APP":return{type:"OPEN_APP"};case"OPEN_WEBVIEW":return{type:"OPEN_WEBVIEW"};case"CUSTOM":if(!r.description)throw new $s("Description is required when container type is CUSTOM.");return{type:"CUSTOM",target:{type:"description",description:r.description}};default:{let e=r;throw new Error("Unreachable")}}},Ry=r=>{let e=Zd.parse(r);switch(e.type){case"TAP":return{id:Zo(),type:"TAP",target:{type:"description",description:e.description},longPress:e.longPress??void 0,doubleTap:e.doubleTap??void 0,relativePosition:e.relativePosition??void 0};case"PRESS":return{id:Zo(),...e};case"AI_CHECK":return{id:Zo(),...e};case"TYPE":return{id:Zo(),type:"TYPE",text:e.text,keyPressDelayMs:e.keyPressDelayMs??void 0,clearContent:e.clearContent??void 0};case"SWIPE":return{id:Zo(),type:"SWIPE",direction:e.direction,scrollableElement:wy(e.container),viewportPercent:e.viewportPercent??void 0,durationMs:e.durationMs??void 0};case"SCROLL_TO":return{id:Zo(),type:"SCROLL_TO",target:{type:"description",description:e.targetDescription},direction:e.direction,scrollableElement:wy(e.container),scrollStepPercent:e.scrollStepPercent??void 0};default:{let t=e;throw new Error("Unreachable")}}};import BI from"zod";var Ea={type:!0,cache:!0},Tn=BI.discriminatedUnion("type",[Qd.pick(Ea),Kd.pick(Ea),Yd.pick(Ea),Xd.pick(Ea),Jd.pick(Ea)]),zI=Object.values(Qr).filter(r=>Tn.options.some(e=>e.shape.type.safeParse(r).success));function gl(r){return zI.includes(r.type)}var xy=ea(Tn),My=ta(Tn),i3=zs(Tn);import _y from"zod";var hl=(t=>(t.US_WEST_1="us-west1",t.EU_NORTH_1="eu-north1",t))(hl||{}),fl=(e=>(e.LOCAL="local",e))(fl||{}),Py=_y.nativeEnum(hl).or(_y.nativeEnum(fl)),Ta=(t=>(t.ANDROID_14="14",t.ANDROID_15="15",t))(Ta||{});var Iy="14";import{cloneDeep as va}from"lodash-es";import Oy from"truncate-json";var HI="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",GI=[ro,Yo],Ly=[ro,Yo],ei=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[ro],o=e.env[Yo],i={};for(let[s,c]of Object.entries(e.env))Ly.includes(s)||(t??{})[s]===void 0&&(i[s]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=va(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){GI.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[ro]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return va(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Ly.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,HI]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Oy(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Oy(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=va(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(ro,e.envName),e.testName&&this.setMomenticSystemVariable(Yo,e.testName)}getDynamicVariablesCopy(){return va(this.env)}getVariablesFromEnvironmentCopy(){return va(this.varsFromMomenticEnvironment)}};import ot from"zod";import{z as br}from"zod";import{z as ze}from"zod";var yr=ze.object({id:ze.string(),name:qo,baseUrl:Qs,description:ze.string().optional().nullish(),schemaVersion:ze.string(),advanced:ma,retries:ze.number(),envs:ze.array(ol).nullish(),parameters:nl.nullish(),disabled:ze.boolean().optional(),labels:ze.array(ze.string()).optional().catch([])}),S3=ze.enum(["INHERIT","ENABLED","DISABLED"]);var VI=ma.extend({failureRecovery:ze.boolean().or(ze.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:ze.boolean().or(ze.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var y3=yr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:VI}),b3=yr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),WI=ze.object({labels:ze.array(ze.string()).optional(),outputs:HS.nullish()}),ti=yr.merge(WI),jI=ze.object({createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string().nullable(),schedule:Jo,notification:Qo,createdBy:ze.string(),organizationId:ze.string(),folderId:ze.string().nullable().optional()}),$I=yr.merge(jI),E3=$I.merge(Jn),Sl=yr.merge(Jn),T3=yr.merge(Qn);var qI="test",KI="module",YI="mobile-test",XI="mobile-module";var Ie=(o=>(o.TEST=`momentic/${qI}`,o.MODULE=`momentic/${KI}`,o.MOBILE_TEST=`momentic/${YI}`,o.MOBILE_MODULE=`momentic/${XI}`,o))(Ie||{}),M3=yr.merge(Qn),Ny=Zt.extend({steps:br.array(br.record(br.string(),br.unknown())),schemaVersion:br.string()}),_3=Ny.extend({fileType:br.literal(Ie.MODULE)}),P3=br.object({test:br.string().describe("YAML for the test, including metadata and steps"),modules:br.record(br.string(),br.string()).describe("Map of module name to YAML for the module")});var em=ot.object({parameterNames:ot.string().array(),defaultParameters:ot.record(ot.string(),ot.string()).optional(),parameterEnums:ot.record(ot.string(),ot.string().array()).optional()}),JI=ot.object({moduleId:ot.string().uuid(),name:ot.string(),description:ot.string().nullish(),parameters:em.optional(),enabled:ot.boolean().nullish(),schemaVersion:ot.string()}),Aa=JI.omit({name:!0}),yl=Aa.extend({steps:ot.array(ot.record(ot.string(),ot.unknown()))}),Dy=ot.object({fileType:ot.literal(Ie.MOBILE_MODULE)}).merge(yl);import St from"zod";var kt=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(kt||{}),wa=St.object({id:St.string().uuid(),envKey:St.string().optional(),skipped:St.boolean().optional(),retries:St.number().optional()}),Ca=wa.extend({type:St.literal("MOBILE_PRESET_STEP"),command:Ay,keyPressDelayMs:St.number().optional()}),ri=St.object({moduleId:St.string(),inputs:St.record(St.string(),St.string()).optional()}),Ra=wa.merge(ri.extend({type:St.literal("MOBILE_MODULE_STEP")})),F3=ri.extend({steps:St.lazy(()=>ir.array())}),xa=wa.extend({type:St.literal("MOBILE_AI_ACTION_STEP"),text:St.string()}),ir=St.discriminatedUnion("type",[Ca,Ra,xa]);import Oe from"zod";import Ma from"zod";var Zr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Zr||{}),tm=ri.extend({steps:Ma.lazy(()=>ni.array()),description:Ma.string().optional(),name:Ma.string().describe("name of the module"),parameters:em.optional()}),QI=wa.merge(tm).extend({type:Ma.literal("RESOLVED_MOBILE_MODULE")}),ni=Ma.discriminatedUnion("type",[QI,Ca,xa]);function ky(r){return Object.values(Zr).includes(r)||Object.values(kt).includes(r)}var ZI=Oe.object({disableMomenticAccessibilityTree:Oe.boolean().optional(),autoGrantPermissions:Oe.boolean().optional()}),rm=ZI.extend({region:Py.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:Oe.object({androidVersion:Oe.nativeEnum(Ta).optional()}).optional(),localEmulatorSettings:Oe.object({avdId:Oe.string()}).optional(),geolocation:Oe.object({latitude:Oe.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Oe.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional()}),_a=Oe.object({retries:Oe.number().optional().describe("number of retries to run"),defaultChannel:Oe.string().optional().describe("default channel to use"),defaultTag:Oe.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Oe.string().optional(),defaultApkFilePath:Oe.string().trim().min(1,"APK file path must not be empty.").optional().describe("APK to install when using the emulator in the local region."),emulator:rm.optional()}),Er=Oe.object({id:Oe.string().uuid(),description:Oe.string(),schemaVersion:Oe.string(),settings:_a.optional()}),nm=Er.extend({fileType:Oe.literal(Ie.MOBILE_TEST)}),eO=Er.merge(Oe.object({steps:Oe.array(ir)})),t4=nm.merge(eO),r4=Oe.object({name:Oe.string(),steps:Oe.array(ir).optional(),settings:_a.optional()}),tO=Er.extend({steps:ni.array()});import ve from"zod";var ao=ve.object({startTime:ve.number(),endTime:ve.number().optional(),durationMs:ve.number().optional(),error:ve.string().optional(),result:ve.unknown().optional(),attributes:ve.record(ve.string(),ve.unknown())});var rO=ao.extend({type:ve.literal("SECTION"),name:ve.string(),subSpans:ve.lazy(()=>om.array())}),nO=ao.extend({type:ve.literal("AI_LOCATOR_CALL"),result:ve.object({id:ve.number(),thoughts:ve.string()}).optional()}),oO=ao.extend({type:ve.literal("AI_ASSERTION_CALL"),result:ve.object({thoughts:ve.string(),result:ve.boolean()}).optional()}),iO=ao.extend({type:ve.literal("TARGET_RESOLUTION"),result:ve.object({serializedElement:ve.string()}).optional()}),aO=ao.extend({type:ve.literal("EMULATOR_INTERACTION"),name:ve.string(),withinWebview:ve.boolean().optional()}),sO=ao.extend({type:ve.literal("EMULATOR_READ_STATE"),name:ve.string()}),lO=ao.extend({type:ve.literal("GENERIC"),name:ve.string()}),om=ve.discriminatedUnion("type",[rO,nO,oO,iO,aO,sO,lO]);import Rt from"zod";var im=Rt.object({message:Rt.string().optional(),startTime:Rt.number(),endTime:Rt.number(),status:Rt.nativeEnum(Ke),trace:Rt.unknown(),beforeSnapshot:Rt.string().optional(),afterSnapshot:Rt.string().optional(),data:Rt.unknown().optional().describe("output data from the step")}),cO=im.merge(Ca).extend({previousAttempts:Rt.lazy(()=>Ut.array()).optional()}),uO=im.merge(Ra).extend({steps:Rt.lazy(()=>Ut.array()),name:Rt.string().optional(),previousAttempts:Rt.lazy(()=>Ut.array()).optional()}),dO=im.merge(xa).extend({steps:Rt.lazy(()=>Ut.array()),previousAttempts:Rt.lazy(()=>Ut.array()).optional()}),Ut=Rt.discriminatedUnion("type",[cO,uO,dO]);import{parse as g4}from"date-fns";var U4=new Set(Object.values(et));var mO={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",CONDITIONAL:"Conditional",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},F4={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],CONDITIONAL:["conditional","if","else","elif","branch"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},B4={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of an AI Check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},z4={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",SCROLL_TO:"Scroll to",SCREEN_CHECK:"Screen check",ELEMENT_CHECK:"Element check",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",UNINSTALL_APP:"Uninstall app",ADB:"ADB command",STATE:"Debug state"},H4={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator (local emulator only).",UNINSTALL_APP:"Uninstall an APK from the connected emulator (local emulator only).",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Ask AI to verify whether something is true on the screen."};import pO from"semver";import{z as gO}from"zod";var j4=gO.string().refine(r=>pO.valid(r),{message:"must be a valid semver string"});import{Faker as K4,en as Y4}from"@faker-js/faker";import{z as D}from"zod";var J4=D.object({body:D.string(),to:D.string(),from:D.string()}),Q4=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()}),Z4=D.object({to:D.string().email(),from:D.string(),subject:D.string(),body:D.string(),html:D.string().optional()}),eJ=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()}),tJ=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 bl=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(bl||{}),Uy=D.object({body:D.string().nullish(),status:D.number().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}),hO=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(),fO=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(),Fy=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()}),rJ=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:hO,response:fO,additionalBindings:D.record(D.string(),D.unknown()).optional()}),timeoutMs:D.number().optional(),disallowVariableUpdates:D.boolean().optional(),responseSerialization:D.nativeEnum(bl).optional()}),vn=15e3;import*as xt from"zod";import{extendZodWithOpenApi as SO}from"zod-openapi";SO(xt);var yO=xt.object({url:xt.string(),lineNumber:xt.number(),columnNumber:xt.number()}).openapi({ref:"CodeLocation"}),El=xt.object({timestamp:xt.number(),text:xt.string(),type:xt.string(),tabIndex:xt.number(),args:xt.unknown().array().optional(),url:xt.string().optional(),location:yO.optional()}).openapi({ref:"ConsoleLog"}),By=El.array(),bO=By.array();import*as am from"zod";import{extendZodWithOpenApi as EO}from"zod-openapi";EO(am);var TO=am.object({logsPerPage:El.array().array()}).openapi({ref:"DebugData"});import{z as M}from"zod";var vO=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),AO=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),wO=M.object({onContentLoad:M.number().optional(),onLoad:M.number().optional(),comment:M.string().optional()}),sm=M.object({startedDateTime:M.string(),id:M.string(),title:M.string().optional(),pageTimings:wO,comment:M.string().optional()}),CO=M.array(sm),RO=M.object({name:M.string(),value:M.string(),path:M.string().optional(),domain:M.string().optional(),expires:M.string().optional(),httpOnly:M.boolean().optional(),secure:M.boolean().optional(),comment:M.string().optional()}),Hy=M.array(RO),xO=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),Gy=M.array(xO),MO=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),_O=M.array(MO),PO=M.object({name:M.string(),value:M.string().optional(),fileName:M.string().optional(),contentType:M.string().optional(),comment:M.string().optional()}),IO=M.array(PO),OO=M.object({mimeType:M.string(),params:IO,text:M.string(),comment:M.string().optional(),_redactedReason:M.string().optional()}),LO=M.object({method:M.string(),url:M.string(),httpVersion:M.string().optional(),cookies:Hy,headers:Gy,queryString:_O,postData:OO.optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional()}),NO=M.object({size:M.number().optional(),compression:M.number().optional(),mimeType:M.string().optional(),text:M.string().optional(),encoding:M.string().optional(),comment:M.string().optional(),_redactedReason:M.string().optional()}),DO=M.object({status:M.number(),statusText:M.string(),httpVersion:M.string().optional(),cookies:Hy,headers:Gy,content:NO,redirectURL:M.string().optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional(),_mocked:M.boolean().optional()}),zy=M.object({expires:M.string().optional(),lastAccess:M.string(),eTag:M.string(),hitCount:M.number(),comment:M.string().optional()}),kO=M.object({beforeRequest:zy.optional(),afterRequest:zy.optional(),comment:M.string().optional()}),UO=M.object({blocked:M.number().optional(),dns:M.number().optional(),connect:M.number().optional(),send:M.number(),wait:M.number(),receive:M.number(),ssl:M.number().optional(),comment:M.string().optional()}),lm=M.object({pageref:M.string().optional(),startedDateTime:M.string(),time:M.number().optional(),request:LO,response:DO.optional(),cache:kO.optional(),timings:UO,serverIPAddress:M.string().optional(),connection:M.string().optional(),comment:M.string().optional(),_resourceType:M.string().optional()}),FO=M.array(lm),BO=M.object({version:M.string().default("1.1"),creator:vO.optional(),browser:AO.optional(),pages:CO.optional(),entries:FO,comment:M.string().optional()}),zO=M.object({log:BO}),hJ=M.record(M.string(),sm),fJ=M.record(M.string(),lm);import{cloneDeep as HO}from"lodash-es";import{z as Or}from"zod";var Wy=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(Wy||{});var Vy=Or.union([Or.string(),Or.number(),Or.boolean(),Or.null(),Or.record(Or.string(),Or.lazy(()=>Vy)),Or.array(Or.lazy(()=>Vy))]),Tl=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=HO(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Wy).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")}},MJ=new Tl({},{});var cm={".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"},jy=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],PJ=Object.keys(cm);import*as $y from"zod";var OJ=$y.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as An}from"zod";var DJ=An.object({id:An.string(),name:An.string(),createdAt:An.coerce.date(),createdBy:An.string(),updatedAt:An.coerce.date(),updatedBy:An.string().nullable(),organizationId:An.string()});import{z as O}from"zod";import wn from"zod";var oi=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 GO=O.array(oi.extend({id:O.string(),name:O.string(),description:O.string().optional(),labels:O.string().array().optional()})),VO=oi.extend({id:O.string(),name:O.string(),description:O.string().optional(),content:vd}),WO=O.array(VO),KJ=O.object({tests:GO,modules:WO,labels:O.string().array()}),YJ=Sl.merge(ti),XJ=O.object({schemaVersion:O.string(),stepLists:Jn}),JJ=ti.partial().merge(yr.pick({id:!0})),jO={name:O.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:O.string().optional(),baseUrl:O.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:O.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:O.nativeEnum(bn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:tl.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:O.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},QJ=O.object(jO),ZJ=Sl.merge(O.object({relativeFilePath:O.string().describe("relative to project root")})),e6=O.object({name:O.string()}),t6=O.object({relativeFilePath:O.string()}),r6=O.object({name:O.string()}),n6=O.object({relativeFilePath:O.string()}),o6=O.object({name:O.string(),description:O.string(),enabled:O.boolean(),steps:O.lazy(()=>lt.array()),testFilePath:O.string().describe("relative to the project root"),folderPath:O.string().optional().describe("user selected folder path")}),i6=O.object({name:O.string(),description:O.string(),enabled:O.boolean()}).partial();var a6=O.array(NS),s6=O.object({defaultEnv:O.string().optional().describe("name of the default env, or undefined to unset")}),l6=O.object({configFilePath:O.string().describe("full path on disk")}),c6=O.string().array(),u6=O.object({message:O.string(),newRelativeTestPath:O.string().optional()}),um=O.object({name:O.string(),absolutePath:O.string(),relativePath:O.string(),pathSegments:O.array(O.string()),isDirectory:O.boolean(),size:O.number(),createdAt:O.coerce.date(),modifiedAt:O.coerce.date(),accessedAt:O.coerce.date()}),qy=O.object({pathSegments:O.array(O.string())}),d6=O.object({absolutePath:O.string(),pathSegments:O.array(O.string()),contents:O.array(um)}),Ky=O.object({pathSegments:O.array(O.string())}),Yy=O.object({pathSegments:O.array(O.string()),newPathSegments:O.array(O.string())}),Xy=O.object({pathSegments:O.array(O.string()),recursive:O.boolean().optional()}),m6=O.object({success:O.boolean(),message:O.string(),pathSegments:O.array(O.string()).optional()}),p6=O.object({gitBranch:O.string(),fileMtime:O.coerce.date(),gitCommitSha:O.string()});var vl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Al=vl.map(r=>`**/${r}/**`),Jy=!0,Lr=!1;import Nr from"chalk";import $O from"safe-stable-stringify";import qO from"truncate-json";import KO from"zod";var so=$O.configure({deterministic:!1});function Qy(r){let e=so(r),{jsonString:t}=qO(e,5e4);return t}var YO=["app","version","env","namespace","host"];function fe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!YO.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Cl=KO.enum(["debug","info","warn","error"]);var Pa={debug:20,info:30,warn:40,error:50},Zy={20:"debug",30:"info",40:"warn",50:"error"},dm=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=Pa[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}`)}}indentMultiline(e,t=" "){return e.split(`
|
|
19
|
+
`),Zd=ue.discriminatedUnion("type",[LI,NI,DI,kI,UI,FI]),wy=r=>{switch(r.type){case"SCREEN":return{type:"SCREEN"};case"OPEN_APP":return{type:"OPEN_APP"};case"OPEN_WEBVIEW":return{type:"OPEN_WEBVIEW"};case"CUSTOM":if(!r.description)throw new $s("Description is required when container type is CUSTOM.");return{type:"CUSTOM",target:{type:"description",description:r.description}};default:{let e=r;throw new Error("Unreachable")}}},Ry=r=>{let e=Zd.parse(r);switch(e.type){case"TAP":return{id:Zo(),type:"TAP",target:{type:"description",description:e.description},longPress:e.longPress??void 0,doubleTap:e.doubleTap??void 0,relativePosition:e.relativePosition??void 0};case"PRESS":return{id:Zo(),...e};case"AI_CHECK":return{id:Zo(),...e};case"TYPE":return{id:Zo(),type:"TYPE",text:e.text,keyPressDelayMs:e.keyPressDelayMs??void 0,clearContent:e.clearContent??void 0};case"SWIPE":return{id:Zo(),type:"SWIPE",direction:e.direction,scrollableElement:wy(e.container),viewportPercent:e.viewportPercent??void 0,durationMs:e.durationMs??void 0};case"SCROLL_TO":return{id:Zo(),type:"SCROLL_TO",target:{type:"description",description:e.targetDescription},direction:e.direction,scrollableElement:wy(e.container),scrollStepPercent:e.scrollStepPercent??void 0};default:{let t=e;throw new Error("Unreachable")}}};import BI from"zod";var Ea={type:!0,cache:!0},Tn=BI.discriminatedUnion("type",[Qd.pick(Ea),Kd.pick(Ea),Yd.pick(Ea),Xd.pick(Ea),Jd.pick(Ea)]),zI=Object.values(Qr).filter(r=>Tn.options.some(e=>e.shape.type.safeParse(r).success));function gl(r){return zI.includes(r.type)}var xy=ea(Tn),My=ta(Tn),a3=zs(Tn);import _y from"zod";var hl=(t=>(t.US_WEST_1="us-west1",t.EU_NORTH_1="eu-north1",t))(hl||{}),fl=(e=>(e.LOCAL="local",e))(fl||{}),Py=_y.nativeEnum(hl).or(_y.nativeEnum(fl)),Ta=(t=>(t.ANDROID_14="14",t.ANDROID_15="15",t))(Ta||{});var Iy="14";import{cloneDeep as va}from"lodash-es";import Oy from"truncate-json";var HI="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",GI=[ro,Yo],Ly=[ro,Yo],ei=class r{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,n={}){return new r({testName:e,envName:t,variablesFromEnvironment:n})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[ro],o=e.env[Yo],i={};for(let[s,c]of Object.entries(e.env))Ly.includes(s)||(t??{})[s]===void 0&&(i[s]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=va(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){GI.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[ro]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return va(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Ly.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,HI]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=Oy(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=Oy(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=va(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(ro,e.envName),e.testName&&this.setMomenticSystemVariable(Yo,e.testName)}getDynamicVariablesCopy(){return va(this.env)}getVariablesFromEnvironmentCopy(){return va(this.varsFromMomenticEnvironment)}};import ot from"zod";import{z as br}from"zod";import{z as ze}from"zod";var yr=ze.object({id:ze.string(),name:qo,baseUrl:Qs,description:ze.string().optional().nullish(),schemaVersion:ze.string(),advanced:ma,retries:ze.number(),envs:ze.array(ol).nullish(),parameters:nl.nullish(),disabled:ze.boolean().optional(),labels:ze.array(ze.string()).optional().catch([])}),y3=ze.enum(["INHERIT","ENABLED","DISABLED"]);var VI=ma.extend({failureRecovery:ze.boolean().or(ze.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:ze.boolean().or(ze.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var b3=yr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:VI}),E3=yr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),WI=ze.object({labels:ze.array(ze.string()).optional(),outputs:HS.nullish()}),ti=yr.merge(WI),jI=ze.object({createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string().nullable(),schedule:Jo,notification:Qo,createdBy:ze.string(),organizationId:ze.string(),folderId:ze.string().nullable().optional()}),$I=yr.merge(jI),T3=$I.merge(Jn),Sl=yr.merge(Jn),v3=yr.merge(Qn);var qI="test",KI="module",YI="mobile-test",XI="mobile-module";var Ie=(o=>(o.TEST=`momentic/${qI}`,o.MODULE=`momentic/${KI}`,o.MOBILE_TEST=`momentic/${YI}`,o.MOBILE_MODULE=`momentic/${XI}`,o))(Ie||{}),_3=yr.merge(Qn),Ny=Zt.extend({steps:br.array(br.record(br.string(),br.unknown())),schemaVersion:br.string()}),P3=Ny.extend({fileType:br.literal(Ie.MODULE)}),I3=br.object({test:br.string().describe("YAML for the test, including metadata and steps"),modules:br.record(br.string(),br.string()).describe("Map of module name to YAML for the module")});var em=ot.object({parameterNames:ot.string().array(),defaultParameters:ot.record(ot.string(),ot.string()).optional(),parameterEnums:ot.record(ot.string(),ot.string().array()).optional()}),JI=ot.object({moduleId:ot.string().uuid(),name:ot.string(),description:ot.string().nullish(),parameters:em.optional(),enabled:ot.boolean().nullish(),schemaVersion:ot.string()}),Aa=JI.omit({name:!0}),yl=Aa.extend({steps:ot.array(ot.record(ot.string(),ot.unknown()))}),Dy=ot.object({fileType:ot.literal(Ie.MOBILE_MODULE)}).merge(yl);import St from"zod";var kt=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(kt||{}),wa=St.object({id:St.string().uuid(),envKey:St.string().optional(),skipped:St.boolean().optional(),retries:St.number().optional()}),Ca=wa.extend({type:St.literal("MOBILE_PRESET_STEP"),command:Ay,keyPressDelayMs:St.number().optional()}),ri=St.object({moduleId:St.string(),inputs:St.record(St.string(),St.string()).optional()}),Ra=wa.merge(ri.extend({type:St.literal("MOBILE_MODULE_STEP")})),B3=ri.extend({steps:St.lazy(()=>ir.array())}),xa=wa.extend({type:St.literal("MOBILE_AI_ACTION_STEP"),text:St.string()}),ir=St.discriminatedUnion("type",[Ca,Ra,xa]);import Oe from"zod";import Ma from"zod";var Zr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Zr||{}),tm=ri.extend({steps:Ma.lazy(()=>ni.array()),description:Ma.string().optional(),name:Ma.string().describe("name of the module"),parameters:em.optional()}),QI=wa.merge(tm).extend({type:Ma.literal("RESOLVED_MOBILE_MODULE")}),ni=Ma.discriminatedUnion("type",[QI,Ca,xa]);function ky(r){return Object.values(Zr).includes(r)||Object.values(kt).includes(r)}var ZI=Oe.object({disableMomenticAccessibilityTree:Oe.boolean().optional(),autoGrantPermissions:Oe.boolean().optional()}),rm=ZI.extend({region:Py.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:Oe.object({androidVersion:Oe.nativeEnum(Ta).optional()}).optional(),localEmulatorSettings:Oe.object({avdId:Oe.string()}).optional(),geolocation:Oe.object({latitude:Oe.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Oe.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional()}),_a=Oe.object({retries:Oe.number().optional().describe("number of retries to run"),defaultChannel:Oe.string().optional().describe("default channel to use"),defaultTag:Oe.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Oe.string().optional(),defaultApkFilePath:Oe.string().trim().min(1,"APK file path must not be empty.").optional().describe("APK to install when using the emulator in the local region."),emulator:rm.optional()}),Er=Oe.object({id:Oe.string().uuid(),description:Oe.string(),schemaVersion:Oe.string(),settings:_a.optional()}),nm=Er.extend({fileType:Oe.literal(Ie.MOBILE_TEST)}),eO=Er.merge(Oe.object({steps:Oe.array(ir)})),r4=nm.merge(eO),n4=Oe.object({name:Oe.string(),steps:Oe.array(ir).optional(),settings:_a.optional()}),tO=Er.extend({steps:ni.array()});import ve from"zod";var ao=ve.object({startTime:ve.number(),endTime:ve.number().optional(),durationMs:ve.number().optional(),error:ve.string().optional(),result:ve.unknown().optional(),attributes:ve.record(ve.string(),ve.unknown())});var rO=ao.extend({type:ve.literal("SECTION"),name:ve.string(),subSpans:ve.lazy(()=>om.array())}),nO=ao.extend({type:ve.literal("AI_LOCATOR_CALL"),result:ve.object({id:ve.number(),thoughts:ve.string()}).optional()}),oO=ao.extend({type:ve.literal("AI_ASSERTION_CALL"),result:ve.object({thoughts:ve.string(),result:ve.boolean()}).optional()}),iO=ao.extend({type:ve.literal("TARGET_RESOLUTION"),result:ve.object({serializedElement:ve.string()}).optional()}),aO=ao.extend({type:ve.literal("EMULATOR_INTERACTION"),name:ve.string(),withinWebview:ve.boolean().optional()}),sO=ao.extend({type:ve.literal("EMULATOR_READ_STATE"),name:ve.string()}),lO=ao.extend({type:ve.literal("GENERIC"),name:ve.string()}),om=ve.discriminatedUnion("type",[rO,nO,oO,iO,aO,sO,lO]);import Rt from"zod";var im=Rt.object({message:Rt.string().optional(),startTime:Rt.number(),endTime:Rt.number(),status:Rt.nativeEnum(Ke),trace:Rt.unknown(),beforeSnapshot:Rt.string().optional(),afterSnapshot:Rt.string().optional(),data:Rt.unknown().optional().describe("output data from the step")}),cO=im.merge(Ca).extend({previousAttempts:Rt.lazy(()=>Ut.array()).optional()}),uO=im.merge(Ra).extend({steps:Rt.lazy(()=>Ut.array()),name:Rt.string().optional(),previousAttempts:Rt.lazy(()=>Ut.array()).optional()}),dO=im.merge(xa).extend({steps:Rt.lazy(()=>Ut.array()),previousAttempts:Rt.lazy(()=>Ut.array()).optional()}),Ut=Rt.discriminatedUnion("type",[cO,uO,dO]);import{parse as h4}from"date-fns";var F4=new Set(Object.values(et));var mO={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",CONDITIONAL:"Conditional",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},B4={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],CONDITIONAL:["conditional","if","else","elif","branch"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},z4={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",CONDITIONAL:"Execute steps based on the outcome of an AI Check",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},H4={AI_CHECK:"AI check",RESOLVED_MOBILE_MODULE:"Module",MOBILE_AI_ACTION_STEP:"AI action",TAP:"Tap",TYPE:"Type",PRESS:"Press button",PRESS_KEYBOARD:"Press keyboard",SWIPE:"Swipe",SCROLL_TO:"Scroll to",SCREEN_CHECK:"Screen check",ELEMENT_CHECK:"Element check",OPEN_APP:"Open app",KILL_APP:"Kill app",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",JAVASCRIPT:"JavaScript",REQUEST:"API request",WAIT:"Wait",ADD_FILE:"Add file",INSTALL_APP:"Install app",UNINSTALL_APP:"Uninstall app",ADB:"ADB command",STATE:"Debug state"},G4={MOBILE_AI_ACTION_STEP:"Ask AI to accomplish a high-level goal by generating other steps.",RESOLVED_MOBILE_MODULE:"A list of steps that can be reused in multiple tests.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a physical button on the device.",PRESS_KEYBOARD:"Press a special key on the keyboard.",SWIPE:"Swipe on the screen.",SCREEN_CHECK:"Assert on the screen content using pre-built conditions.",SCROLL_TO:"Scroll until an element is visible.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",OPEN_APP:"Open an app on the device.",KILL_APP:"Terminate the currently active app and remove it from recents.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",REQUEST:"Make an HTTP request to a URL.",WAIT:"Wait for a specified amount of time.",ADD_FILE:"Add a file to the device's disk.",INSTALL_APP:"Install one or more APKs onto the connected emulator (local emulator only).",UNINSTALL_APP:"Uninstall an APK from the connected emulator (local emulator only).",ADB:"Execute an ADB command on the device.",STATE:"Capture and return emulator state details.",AI_CHECK:"Ask AI to verify whether something is true on the screen."};import pO from"semver";import{z as gO}from"zod";var $4=gO.string().refine(r=>pO.valid(r),{message:"must be a valid semver string"});import{Faker as Y4,en as X4}from"@faker-js/faker";import{z as D}from"zod";var Q4=D.object({body:D.string(),to:D.string(),from:D.string()}),Z4=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()}),eJ=D.object({to:D.string().email(),from:D.string(),subject:D.string(),body:D.string(),html:D.string().optional()}),tJ=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()}),rJ=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 bl=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(bl||{}),Uy=D.object({body:D.string().nullish(),status:D.number().optional(),headers:D.array(D.tuple([D.string(),D.string()])).optional()}),hO=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(),fO=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(),Fy=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()}),nJ=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:hO,response:fO,additionalBindings:D.record(D.string(),D.unknown()).optional()}),timeoutMs:D.number().optional(),disallowVariableUpdates:D.boolean().optional(),responseSerialization:D.nativeEnum(bl).optional()}),vn=15e3;import*as xt from"zod";import{extendZodWithOpenApi as SO}from"zod-openapi";SO(xt);var yO=xt.object({url:xt.string(),lineNumber:xt.number(),columnNumber:xt.number()}).openapi({ref:"CodeLocation"}),El=xt.object({timestamp:xt.number(),text:xt.string(),type:xt.string(),tabIndex:xt.number(),args:xt.unknown().array().optional(),url:xt.string().optional(),location:yO.optional()}).openapi({ref:"ConsoleLog"}),By=El.array(),bO=By.array();import*as am from"zod";import{extendZodWithOpenApi as EO}from"zod-openapi";EO(am);var TO=am.object({logsPerPage:El.array().array()}).openapi({ref:"DebugData"});import{z as M}from"zod";var vO=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),AO=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),wO=M.object({onContentLoad:M.number().optional(),onLoad:M.number().optional(),comment:M.string().optional()}),sm=M.object({startedDateTime:M.string(),id:M.string(),title:M.string().optional(),pageTimings:wO,comment:M.string().optional()}),CO=M.array(sm),RO=M.object({name:M.string(),value:M.string(),path:M.string().optional(),domain:M.string().optional(),expires:M.string().optional(),httpOnly:M.boolean().optional(),secure:M.boolean().optional(),comment:M.string().optional()}),Hy=M.array(RO),xO=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),Gy=M.array(xO),MO=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),_O=M.array(MO),PO=M.object({name:M.string(),value:M.string().optional(),fileName:M.string().optional(),contentType:M.string().optional(),comment:M.string().optional()}),IO=M.array(PO),OO=M.object({mimeType:M.string(),params:IO,text:M.string(),comment:M.string().optional(),_redactedReason:M.string().optional()}),LO=M.object({method:M.string(),url:M.string(),httpVersion:M.string().optional(),cookies:Hy,headers:Gy,queryString:_O,postData:OO.optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional()}),NO=M.object({size:M.number().optional(),compression:M.number().optional(),mimeType:M.string().optional(),text:M.string().optional(),encoding:M.string().optional(),comment:M.string().optional(),_redactedReason:M.string().optional()}),DO=M.object({status:M.number(),statusText:M.string(),httpVersion:M.string().optional(),cookies:Hy,headers:Gy,content:NO,redirectURL:M.string().optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional(),_mocked:M.boolean().optional()}),zy=M.object({expires:M.string().optional(),lastAccess:M.string(),eTag:M.string(),hitCount:M.number(),comment:M.string().optional()}),kO=M.object({beforeRequest:zy.optional(),afterRequest:zy.optional(),comment:M.string().optional()}),UO=M.object({blocked:M.number().optional(),dns:M.number().optional(),connect:M.number().optional(),send:M.number(),wait:M.number(),receive:M.number(),ssl:M.number().optional(),comment:M.string().optional()}),lm=M.object({pageref:M.string().optional(),startedDateTime:M.string(),time:M.number().optional(),request:LO,response:DO.optional(),cache:kO.optional(),timings:UO,serverIPAddress:M.string().optional(),connection:M.string().optional(),comment:M.string().optional(),_resourceType:M.string().optional()}),FO=M.array(lm),BO=M.object({version:M.string().default("1.1"),creator:vO.optional(),browser:AO.optional(),pages:CO.optional(),entries:FO,comment:M.string().optional()}),zO=M.object({log:BO}),fJ=M.record(M.string(),sm),SJ=M.record(M.string(),lm);import{cloneDeep as HO}from"lodash-es";import{z as Or}from"zod";var Wy=(c=>(c.DisableClickhouseCaches="disable_clickhouse_caches",c.ShowZeroOpacityElements="show_zero_opacity_elements",c.VisualActions="visual_actions",c.RagV2="rag_v2",c.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",c.GlobalLocatorRedirect="global_locator_redirect",c.FakerConstantSeed="faker_constant_seed",c.AutoExpandIframes="auto_expand_iframes",c))(Wy||{});var Vy=Or.union([Or.string(),Or.number(),Or.boolean(),Or.null(),Or.record(Or.string(),Or.lazy(()=>Vy)),Or.array(Or.lazy(()=>Vy))]),Tl=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=HO(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(Wy).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")}},_J=new Tl({},{});var cm={".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"},jy=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],IJ=Object.keys(cm);import*as $y from"zod";var LJ=$y.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as An}from"zod";var kJ=An.object({id:An.string(),name:An.string(),createdAt:An.coerce.date(),createdBy:An.string(),updatedAt:An.coerce.date(),updatedBy:An.string().nullable(),organizationId:An.string()});import{z as O}from"zod";import wn from"zod";var oi=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 GO=O.array(oi.extend({id:O.string(),name:O.string(),description:O.string().optional(),labels:O.string().array().optional()})),VO=oi.extend({id:O.string(),name:O.string(),description:O.string().optional(),content:vd}),WO=O.array(VO),YJ=O.object({tests:GO,modules:WO,labels:O.string().array()}),XJ=Sl.merge(ti),JJ=O.object({schemaVersion:O.string(),stepLists:Jn}),QJ=ti.partial().merge(yr.pick({id:!0})),jO={name:O.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:O.string().optional(),baseUrl:O.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:O.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:O.nativeEnum(bn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:tl.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:O.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},ZJ=O.object(jO),e6=Sl.merge(O.object({relativeFilePath:O.string().describe("relative to project root")})),t6=O.object({name:O.string()}),r6=O.object({relativeFilePath:O.string()}),n6=O.object({name:O.string()}),o6=O.object({relativeFilePath:O.string()}),i6=O.object({name:O.string(),description:O.string(),enabled:O.boolean(),steps:O.lazy(()=>lt.array()),testFilePath:O.string().describe("relative to the project root"),folderPath:O.string().optional().describe("user selected folder path")}),a6=O.object({name:O.string(),description:O.string(),enabled:O.boolean()}).partial();var s6=O.array(NS),l6=O.object({defaultEnv:O.string().optional().describe("name of the default env, or undefined to unset")}),c6=O.object({configFilePath:O.string().describe("full path on disk")}),u6=O.string().array(),d6=O.object({message:O.string(),newRelativeTestPath:O.string().optional()}),um=O.object({name:O.string(),absolutePath:O.string(),relativePath:O.string(),pathSegments:O.array(O.string()),isDirectory:O.boolean(),size:O.number(),createdAt:O.coerce.date(),modifiedAt:O.coerce.date(),accessedAt:O.coerce.date()}),qy=O.object({pathSegments:O.array(O.string())}),m6=O.object({absolutePath:O.string(),pathSegments:O.array(O.string()),contents:O.array(um)}),Ky=O.object({pathSegments:O.array(O.string())}),Yy=O.object({pathSegments:O.array(O.string()),newPathSegments:O.array(O.string())}),Xy=O.object({pathSegments:O.array(O.string()),recursive:O.boolean().optional()}),p6=O.object({success:O.boolean(),message:O.string(),pathSegments:O.array(O.string()).optional()}),g6=O.object({gitBranch:O.string(),fileMtime:O.coerce.date(),gitCommitSha:O.string()});var vl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Al=vl.map(r=>`**/${r}/**`),Jy=!0,Lr=!1;import Nr from"chalk";import $O from"safe-stable-stringify";import qO from"truncate-json";import KO from"zod";var so=$O.configure({deterministic:!1});function Qy(r){let e=so(r),{jsonString:t}=qO(e,5e4);return t}var YO=["app","version","env","namespace","host"];function fe(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!YO.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Cl=KO.enum(["debug","info","warn","error"]);var Pa={debug:20,info:30,warn:40,error:50},Zy={20:"debug",30:"info",40:"warn",50:"error"},dm=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=Pa[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}`)}}indentMultiline(e,t=" "){return e.split(`
|
|
20
20
|
`).map((n,o)=>o>0?`${t}${n}`:n).join(`
|
|
21
21
|
`)}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[s,c]of a){let l=c;if(c instanceof Error){l=c.message,console.log(t(` ${s}:`,l)),console.log(t(" stack:",c.stack));let d=Object.entries(c).filter(([m])=>m!=="message"&&m!=="stack");for(let[m,g]of d){if(g instanceof Error){console.log(t(` ${s}.${m}:`,g.message)),g.stack&&console.log(t(` ${s}.${m}.stack:`,g.stack));continue}if(typeof g=="object"&&g!==null){let p=this.indentMultiline(so(g,void 0,2)," ");console.log(t(` ${s}.${m}:`,p));continue}console.log(t(` ${s}.${m}:`,g))}}else typeof c=="object"?(l=so(c,void 0,2),l=this.indentMultiline(l),console.log(t(` ${s}:`,l))):console.log(t(` ${s}:`,l))}}else if(o)for(let a of o){let s=a;typeof a=="object"&&(s=so(a,void 0,2),s=s.split(`
|
|
22
22
|
`).map((c,l)=>l>0?` ${c}`:c).join(`
|
|
23
|
-
`)),console.log(" ",t(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=Pa[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Nr.reset,...e)}info(...e){this.logWithLevel(30,Nr.white,...e)}debug(...e){this.logWithLevel(20,Nr.dim,...e)}warn(...e){this.logWithLevel(40,Nr.yellow,...e)}error(...e){this.logWithLevel(50,Nr.red,...e)}success(...e){this.logWithLevel(1/0,Nr.green,...e)}dimmed(...e){this.logWithLevel(30,Nr.dim,...e)}underline(...e){this.logWithLevel(40,Nr.underline,...e)}bold(...e){this.logWithLevel(40,Nr.bold,...e)}grey(...e){this.logWithLevel(20,Nr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},mm=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},T6=new mm,XO=typeof window>"u"&&typeof process<"u"&&Cl.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Cl.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,C=new dm(XO,{}),Cn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Cn,flush:async()=>{},bindings:()=>({})},wl={},Rl=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=wl[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},wl[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=wl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete wl[e]},n)};import{z as de}from"zod";var JO=de.array(oi.extend({id:de.string(),name:de.string(),description:de.string().optional(),labels:de.string().array().optional()})),QO=de.array(oi.extend({id:de.string(),name:de.string(),description:de.string().optional(),content:tm})),eb=de.object({name:de.string(),description:de.string().optional(),settings:_a.optional(),pathSegments:de.string().array(),defaultEnv:de.string().optional()}),R6=de.object({id:de.string(),fileName:de.string(),fullPath:de.string(),relativeFilePath:de.string().describe("relative to project root")});var tb=de.object({steps:ni.array().optional(),settings:_a.optional()}),x6=de.object({message:de.literal("ok")}),rb=de.object({tag:de.string(),channel:de.string(),filePath:de.string()}),M6=de.object({tests:JO,modules:QO,labels:de.string().array()}),nb=de.object({name:de.string(),description:de.string(),enabled:de.boolean()}).partial(),ob=de.object({name:de.string(),description:de.string(),enabled:de.boolean(),steps:ni.array(),testFilePath:de.string().describe("relative to the project root"),folderPath:de.string().optional().describe("user selected folder path")});import{z as Qe}from"zod";var ib=Qe.object({id:Qe.string(),createdAt:Qe.coerce.date(),createdBy:Qe.string(),organizationId:Qe.string(),name:Qe.string(),description:Qe.string().nullish(),enabled:Qe.boolean(),schemaVersion:Qe.string().describe("Schema version for steps"),parameters:Qe.string().array().nullish().describe("Parameter list"),parameterEnums:Qe.record(Qe.string(),Qe.string().array()).nullish(),defaultParameters:Qe.record(Qe.string(),Qe.string()).nullish(),defaultCacheKey:Qe.string().nullish(),defaultCacheTtl:Qe.number().nullish(),defaultCacheAllInvocations:Qe.boolean().nullish(),autoAuth:Qe.boolean().nullish(),advanced:Td.nullish()}),U6=ib.extend({steps:Qe.lazy(()=>Nt.array())}),F6=5*60*1e3,ZO=Zt.merge(ib.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as H6}from"date-fns-tz";import{z as xe}from"zod";var pm=Nd.extend({aiAction:xe.boolean().optional(),stepLintSuggestions:xe.boolean().optional(),agentConfig:xe.record(xe.string(),xe.string()).optional(),aiFailureAnalysis:xe.boolean().optional(),aiPageFiltering:xe.boolean().optional().describe("rag v2 feature flag")}),eL=xe.object({cliOnly:xe.boolean().optional()}),gm=xe.object({fakerConstantSeed:xe.boolean().optional()}),q6=xe.object({ai:pm.optional(),githubAppInstallationId:xe.number().nullish(),githubAppSummaryMessageEnabled:xe.boolean().nullish(),githubReleaseAppInstallationId:xe.number().nullish(),gitlabAppAccessToken:xe.string().nullish(),gitlabAppBaseUrl:xe.string().nullish(),qaseAccessToken:xe.string().nullish(),testSuggestionsEnabled:xe.boolean().nullish(),browser:xd.optional(),internal:eL.optional(),advanced:gm.optional()}),K6=xe.object({globalOverrides:xe.record(xe.string()).optional(),agentConfig:xe.record(xe.string(),xe.string()).optional()}),Y6=xe.record(xe.string(),xe.string()).nullish();import*as S from"zod";import{z as Ye}from"zod";var hm=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(hm||{});var tL=Ye.object({type:Ye.literal("DESCRIPTION_UPDATE"),thoughts:Ye.string()}),xl=Ye.discriminatedUnion("type",[tL]),rL=Ye.object({testId:Ye.string(),name:Ye.string(),orgId:Ye.string(),runId:Ye.string(),steps:lt.array(),purpose:Ye.nativeEnum(hm),details:xl.or(xl.array()).optional()});var Z6=rL.pick({name:!0,orgId:!0}),nL=Ye.object({id:Ye.string(),name:Ye.string().nullish(),createdAt:Ye.string().pipe(Ye.coerce.date()).or(Ye.date()),organizationId:Ye.string(),schemaVersion:Ye.string(),runId:Ye.string().nullish(),purpose:Ye.nativeEnum(hm),details:xl.or(xl.array()).optional(),applied:Ye.boolean().nullish(),appliedAt:Ye.coerce.date().nullish()}),ab=nL.extend({steps:lt.array()});var Ml="x-momentic-cli-version",sb="x-momentic-client-mode",lb="x-momentic-cli-type",cb="x-momentic-logger-tags",oL="x-momentic-main-branch-name",iL="x-momentic-branch-name",aL="x-momentic-commit-timestamp",sL="x-momentic-last-commit-on-main",lL="x-momentic-last-commit-on-main-timestamp",cL="x-momentic-merged-branch-name",ub="x-momentic-session-id",f8=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),S8=ft.merge(Ud),db=Bs,y8=ft.merge(Ud);var b8=ft.merge(QS).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),fm=Hh,E8=ft.merge(ey),mb=ES,T8=ft.merge(ZS),pb=bS,v8=ft.merge(YS),gb=SS,A8=ft.merge(XS),hb=hS,w8=ft.merge(JS);var C8=ft.merge(oy),R8=ft.merge(iy),x8=S.object({testPaths:S.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:S.string().optional(),all:S.boolean().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional(),testInputMatrix:S.record(S.string(),S.string()).array().optional()}),fb=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var M8=S.string().array(),_8=S.union([S.object({paths:S.string().array().describe("run specific test paths (e.g. todo-test)"),all:S.boolean().describe("run all tests").optional()}),S.object({path:S.string().describe("deprecated; present for backcompat")})]),Sb=S.object({tests:S.record(S.string().describe("Test name"),S.string().describe("Test YAML")),modules:S.record(S.string().describe("Module name"),S.string().describe("Module YAML"))}),uL=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),P8=uL.array(),I8=S.object({testId:S.string(),schemaVersion:S.string()}).merge(Qn);function Sm(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[oL]=encodeURIComponent(e)),t&&(a[iL]=encodeURIComponent(t)),n&&(a[aL]=n.toISOString()),o&&(a[sL]=encodeURIComponent(o)),i&&(a[lL]=i.toISOString()),r.mergedGitBranchName&&(a[cL]=encodeURIComponent(r.mergedGitBranchName)),a}var O8=S.object({entries:S.array(Sf),testId:S.string()}),L8=S.object({entries:S.array(xy),testId:S.string()}),N8=S.object({testId:S.string()});function yb(r){return S.record(S.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 bb=yb(yf),Eb=yb(My),Tb=S.object({trigger:S.nativeEnum(rr),status:S.nativeEnum(Re),startedAt:S.coerce.date().optional(),gitCommitSha:S.string().optional(),gitCommitShaShort:S.string().optional(),gitCommitTimestamp:S.coerce.date().optional(),gitBranchName:S.string().optional(),gitOriginUrl:S.string().optional(),gitCommitMessage:S.string().optional(),gitCommitAuthorName:S.string().optional(),githubRepository:S.string().optional(),gitlabProjectPath:S.string().optional(),pipelineId:S.string().optional(),cliVersion:S.string().optional()}),D8=S.object({id:S.string()}),vb=S.object({status:S.nativeEnum(Re),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),Ab=S.object({stepsSnapshot:S.array(S.record(S.unknown())).optional(),runGroupId:S.string().optional(),testId:S.string(),testName:S.string(),resolvedBaseUrl:S.string().optional(),environmentName:S.string().optional(),labels:S.array(S.string()).optional(),cliVersion:S.string().optional(),trigger:S.nativeEnum(rr),schemaVersion:S.string().optional(),section:S.nativeEnum(il).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),k8=S.object({id:S.string()}),dL=Dd.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),wb=dL.array(),Cb=Dd.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(),U8=S.object({id:S.string()}),Rb=S.object({status:S.nativeEnum(Re),finishedAt:S.coerce.date().optional(),schemaVersion:S.string().optional().default("1.0.19"),results:S.record(S.string(),S.unknown()).array().optional(),beforeResults:S.record(S.string(),S.unknown()).array().optional(),afterResults:S.record(S.string(),S.unknown()).array().optional()}),F8=S.object({screenshot:S.string()}),xb=S.object({key:S.string()}),Mb=S.object({orgId:S.string(),userId:S.string()}),_b=S.array(LS),B8=S.record(S.string(),S.union([S.string(),S.boolean()])),z8=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Pb=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),H8=S.object({suiteRunIds:S.string().array()}),G8=jS.array(),V8=S.object({runGroupIds:S.string().array()}),mL=S.object({uploadUrl:S.string()}),W8=ft.merge(ty),j8=ft.merge(ny),$8=ft.merge(ry),pL=S.object({testId:S.string().optional().default(""),testName:S.string().optional().default(""),suiteId:S.string().optional().default(""),suiteName:S.string().optional().default(""),creditsUsed:S.number().optional()}),gL=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(fa),properties:pL}),q8=gL.array(),Ib=ab.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),K8=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),Ob=GS.array(),Y8=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),Lb=mL.extend({id:S.string()}),X8=S.object({runGroupId:S.string().uuid().optional()}),Nb=S.object({runGroupId:S.string().uuid()}),Db=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),J8=S.object({testId:S.string().uuid(),testName:S.string().optional(),reason:S.string(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Q8=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Z8=ft.merge(uy),e9=ft.merge(dy),t9=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(hl).optional(),osVersion:S.nativeEnum(Ta).optional(),sessionId:S.string().optional()}),kb=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),playwrightServerUrl:S.string().optional(),region:S.string().optional()}),r9=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),Ub=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),Fb=S.object({assets:S.array(S.object({channel:S.string(),tag:S.string(),md5:S.string(),createdAt:S.number().describe("Unix timestamp in milliseconds")}))});import{z as Z}from"zod";var Bb=7,hL=3,i9=Z.object({localTestId:Z.string(),quarantinedAt:Z.date(),quarantinedBy:Z.string().optional(),quarantinedReason:Z.string(),quarantinedByGitEmail:Z.string().optional(),quarantinedByGitName:Z.string().optional(),quarantinedByGitUsername:Z.string().optional()}).or(Z.object({cloudTestId:Z.string(),quarantinedAt:Z.date(),quarantinedBy:Z.string().optional(),quarantinedReason:Z.string(),quarantinedByGitEmail:Z.string().optional(),quarantinedByGitName:Z.string().optional(),quarantinedByGitUsername:Z.string().optional()})),zb=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(zb||{});var ym=Z.object({name:Z.string(),description:Z.string().nullish(),effect:Z.nativeEnum(zb),labels:Z.array(Z.string()).nullish(),githubRepository:Z.string().nullish(),gitlabProjectPath:Z.string().nullish(),gitBranchName:Z.string().nullish(),slackNotificationChannel:Z.string().nullish()}),fL=Z.object({type:Z.literal("LAST_N_RUNS"),lastN:Z.number().min(hL)}),SL=Z.object({type:Z.literal("LAST_N_HOURS"),lastN:Z.number().min(1).max(Bb*24)}),yL=Z.object({type:Z.literal("LAST_N_DAYS"),lastN:Z.number().min(1).max(Bb)}),bm=Z.discriminatedUnion("type",[fL,SL,yL]),bL=Z.object({flakeRateThreshold:Z.number().min(1).max(100),evaluationWindow:bm}),EL=ym.extend({type:Z.literal("FLAKE_RATE"),config:bL}),TL=Z.object({passRateThreshold:Z.number().min(1).max(100),evaluationWindow:bm}),vL=ym.extend({type:Z.literal("PASS_RATE"),config:TL}),AL=Z.object({failureCountThreshold:Z.number().min(0),evaluationWindow:bm}),wL=ym.extend({type:Z.literal("FAILURE_COUNT"),config:AL}),a9=Z.discriminatedUnion("type",[EL,vL,wL]);import{z as Ze}from"zod";var c9=Ze.object({repositoriesIndexed:Ze.boolean(),indexingInProgress:Ze.boolean(),indexesOutdated:Ze.boolean()}),Hb=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(Hb||{}),Gb=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(Gb||{}),u9=Ze.object({name:Ze.string(),status:Ze.nativeEnum(Hb),conclusion:Ze.nativeEnum(Gb).nullable()}),Ia=Ze.object({sha:Ze.string(),message:Ze.string(),author:Ze.object({name:Ze.string().optional(),email:Ze.string().optional(),date:Ze.coerce.date().optional()}),committer:Ze.object({name:Ze.string().optional(),email:Ze.string().optional(),date:Ze.coerce.date().optional()})}),Em=Ze.object({mergedBranch:Ze.string().optional()});import{z as He}from"zod";var Vb=He.object({orgId:He.string(),cacheKeys:He.string().array()}),p9=He.object({keyParams:Vb,clientMetadata:He.string(),lockAcquisitionTimeoutMs:He.number().optional()}),Wb=He.object({acquired:He.boolean(),acquiredByMetadata:He.string(),keyPrefix:He.string()}),g9=He.object({keyPrefix:He.string(),result:He.string(),ttlMs:He.number()}),h9=He.union([He.object({keyPrefix:He.string()}),Vb]),CL=He.object({remainingTtlMs:He.number(),value:He.string().nullish()}),f9=He.object({results:He.record(He.string(),CL),activeLocks:He.string().array()});var S9=5*60*1e3;var T9=90*24*60*60*1e3,v9=7*24*60*60*1e3;import{z as jb}from"zod";var C9=jb.object({quarantineNotifications:jb.string().nullish()});import{z as yt}from"zod";var RL=yt.object({version:yt.string(),json:yt.record(yt.unknown()),hash:yt.string()}),$b=yt.record(yt.unknown()),_9=yt.object({newSvgs:yt.array(RL),metadata:$b.optional()}),xL=yt.object({version:yt.string(),json:yt.record(yt.unknown()).nullish(),hash:yt.string(),description:yt.string().nullish(),metadata:$b.nullish()}),qb=yt.record(yt.string().describe("icon hash"),xL);import{z as je}from"zod";var Tm=je.object({assertion:je.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),ML=je.object({instruction:je.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:Tm.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.")}),Kb=ML.extend({subSteps:je.lazy(()=>Kb.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Yb=je.object({name:je.string().describe("Short name describing the test plan"),description:je.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),Xb=Yb.extend({id:je.string(),createdAt:je.coerce.date(),updatedAt:je.coerce.date(),updatedBy:je.string(),createdBy:je.string(),test:je.object({id:je.string(),name:je.string()}).nullish().transform(r=>r??void 0)}),L9=Xb.extend({testGenRuns:je.tuple([]).or(je.tuple([je.object({id:je.string(),startedAt:je.coerce.date(),status:je.nativeEnum(Re)})]))}),Jb=je.object({preConditions:Tm.array().nullish().transform(r=>r??[]),postConditions:Tm.array().nullish().transform(r=>r??[]),steps:Kb.array().nullish().transform(r=>r??[])}),N9=Xb.extend({plan:Jb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),_L=Yb.extend({plan:Jb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),D9=_L.array().nullish().transform(r=>r??[]);import{validator as PL}from"@exodus/schemasafe";function Qb(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{PL(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var Zb=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var _l=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as Q9}from"zod";var Pl=class{async resolveEntries(){}async saveEntries(){}};import{z as vm}from"zod";var eE=vm.object({parentStepIdChain:vm.array(vm.string()),result:Ut});import{z as Y}from"zod";var IL=Y.object({step:lt,status:Y.nativeEnum(Ke),startedAt:Y.coerce.date(),finishedAt:Y.coerce.date().optional(),healMetadata:Y.object({healType:Y.nativeEnum(ua).or(Y.literal("AI")),healedAt:Y.coerce.date()}).optional(),beforeSnapshotId:Y.string().uuid().optional(),afterSnapshotId:Y.string().uuid().optional(),message:Y.string().optional()}),OL=IL.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),fQ=OL.extend({step:Y.unknown()}),tE="1.0.0",Am=Rb.extend({id:Y.string().uuid().optional(),startedAt:Y.coerce.date(),runAttemptSchemaVersion:Y.string().optional(),schemaVersion:Y.string().optional().default("1.0.19"),results:Y.record(Y.string(),Y.unknown()).array().optional(),beforeResults:Y.record(Y.string(),Y.unknown()).array().optional(),afterResults:Y.record(Y.string(),Y.unknown()).array().optional(),activeVideos:Y.array(Y.object({videoName:Y.string(),timestamp:Y.coerce.date()})).optional()}),rE=Am.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),SQ=Am.merge(da),yQ=rE.merge(da),nE=Y.object({results:Y.array(Ut),beforeResults:Y.array(Ut).optional(),afterResults:Y.array(Ut).optional()}),bQ=Am.merge(nE),EQ=rE.merge(nE),LL=Cb.merge(Ab).extend({executionType:Y.nativeEnum(Xo).optional().default("WEB"),testId:Y.string().uuid(),testDescription:Y.string().optional(),runGroupId:Y.string().uuid(),status:Y.nativeEnum(Re),startedAt:Y.coerce.date(),attempts:Y.number(),failureRecoveryDetails:Y.object({attempts:Y.number()}).optional()}),TQ=LL.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),NL=Tb.merge(vb).extend({id:Y.string().uuid().optional(),startedAt:Y.coerce.date(),cliVersion:Y.string(),labels:Y.string().array().optional().default([])}),Il=NL.extend({updatedAt:Y.coerce.date().optional().transform(r=>r??new Date),finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)});import{confirm as DL,input as kL}from"@inquirer/prompts";import{existsSync as YZ,mkdirSync as XZ,statSync as UL}from"fs";var lo=!!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;var FL=!1,oE=(()=>{try{return UL("/.dockerenv"),!0}catch{return!1}})();async function Ol(r){return lo||FL||oE?!0:(await C.flush(),await new Promise(t=>setTimeout(t,100)),await DL({message:r}))}async function iE(r,e){return lo||oE?e:(await kL({message:r,default:e})).trim()||e}import si,{supportsColor as YL}from"chalk";import{Console as aE}from"console";import{format as Oa}from"util";var wm=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}},Ll=class r extends aE{_buffer=[];_groupDepth=0;Console=aE;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new wm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
23
|
+
`)),console.log(" ",t(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=Pa[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Nr.reset,...e)}info(...e){this.logWithLevel(30,Nr.white,...e)}debug(...e){this.logWithLevel(20,Nr.dim,...e)}warn(...e){this.logWithLevel(40,Nr.yellow,...e)}error(...e){this.logWithLevel(50,Nr.red,...e)}success(...e){this.logWithLevel(1/0,Nr.green,...e)}dimmed(...e){this.logWithLevel(30,Nr.dim,...e)}underline(...e){this.logWithLevel(40,Nr.underline,...e)}bold(...e){this.logWithLevel(40,Nr.bold,...e)}grey(...e){this.logWithLevel(20,Nr.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},mm=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},v6=new mm,XO=typeof window>"u"&&typeof process<"u"&&Cl.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Cl.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,C=new dm(XO,{}),Cn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Cn,flush:async()=>{},bindings:()=>({})},wl={},Rl=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=wl[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},wl[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=wl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete wl[e]},n)};import{z as de}from"zod";var JO=de.array(oi.extend({id:de.string(),name:de.string(),description:de.string().optional(),labels:de.string().array().optional()})),QO=de.array(oi.extend({id:de.string(),name:de.string(),description:de.string().optional(),content:tm})),eb=de.object({name:de.string(),description:de.string().optional(),settings:_a.optional(),pathSegments:de.string().array(),defaultEnv:de.string().optional()}),x6=de.object({id:de.string(),fileName:de.string(),fullPath:de.string(),relativeFilePath:de.string().describe("relative to project root")});var tb=de.object({steps:ni.array().optional(),settings:_a.optional()}),M6=de.object({message:de.literal("ok")}),rb=de.object({tag:de.string(),channel:de.string(),filePath:de.string()}),_6=de.object({tests:JO,modules:QO,labels:de.string().array()}),nb=de.object({name:de.string(),description:de.string(),enabled:de.boolean()}).partial(),ob=de.object({name:de.string(),description:de.string(),enabled:de.boolean(),steps:ni.array(),testFilePath:de.string().describe("relative to the project root"),folderPath:de.string().optional().describe("user selected folder path")});import{z as Qe}from"zod";var ib=Qe.object({id:Qe.string(),createdAt:Qe.coerce.date(),createdBy:Qe.string(),organizationId:Qe.string(),name:Qe.string(),description:Qe.string().nullish(),enabled:Qe.boolean(),schemaVersion:Qe.string().describe("Schema version for steps"),parameters:Qe.string().array().nullish().describe("Parameter list"),parameterEnums:Qe.record(Qe.string(),Qe.string().array()).nullish(),defaultParameters:Qe.record(Qe.string(),Qe.string()).nullish(),defaultCacheKey:Qe.string().nullish(),defaultCacheTtl:Qe.number().nullish(),defaultCacheAllInvocations:Qe.boolean().nullish(),autoAuth:Qe.boolean().nullish(),advanced:Td.nullish()}),F6=ib.extend({steps:Qe.lazy(()=>Nt.array())}),B6=5*60*1e3,ZO=Zt.merge(ib.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as G6}from"date-fns-tz";import{z as xe}from"zod";var pm=Nd.extend({aiAction:xe.boolean().optional(),stepLintSuggestions:xe.boolean().optional(),agentConfig:xe.record(xe.string(),xe.string()).optional(),aiFailureAnalysis:xe.boolean().optional(),aiPageFiltering:xe.boolean().optional().describe("rag v2 feature flag")}),eL=xe.object({cliOnly:xe.boolean().optional()}),gm=xe.object({fakerConstantSeed:xe.boolean().optional()}),K6=xe.object({ai:pm.optional(),githubAppInstallationId:xe.number().nullish(),githubAppSummaryMessageEnabled:xe.boolean().nullish(),githubReleaseAppInstallationId:xe.number().nullish(),gitlabAppAccessToken:xe.string().nullish(),gitlabAppBaseUrl:xe.string().nullish(),qaseAccessToken:xe.string().nullish(),testSuggestionsEnabled:xe.boolean().nullish(),browser:xd.optional(),internal:eL.optional(),advanced:gm.optional()}),Y6=xe.object({globalOverrides:xe.record(xe.string()).optional(),agentConfig:xe.record(xe.string(),xe.string()).optional()}),X6=xe.record(xe.string(),xe.string()).nullish();import*as S from"zod";import{z as Ye}from"zod";var hm=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(hm||{});var tL=Ye.object({type:Ye.literal("DESCRIPTION_UPDATE"),thoughts:Ye.string()}),xl=Ye.discriminatedUnion("type",[tL]),rL=Ye.object({testId:Ye.string(),name:Ye.string(),orgId:Ye.string(),runId:Ye.string(),steps:lt.array(),purpose:Ye.nativeEnum(hm),details:xl.or(xl.array()).optional()});var e8=rL.pick({name:!0,orgId:!0}),nL=Ye.object({id:Ye.string(),name:Ye.string().nullish(),createdAt:Ye.string().pipe(Ye.coerce.date()).or(Ye.date()),organizationId:Ye.string(),schemaVersion:Ye.string(),runId:Ye.string().nullish(),purpose:Ye.nativeEnum(hm),details:xl.or(xl.array()).optional(),applied:Ye.boolean().nullish(),appliedAt:Ye.coerce.date().nullish()}),ab=nL.extend({steps:lt.array()});var Ml="x-momentic-cli-version",sb="x-momentic-client-mode",lb="x-momentic-cli-type",cb="x-momentic-logger-tags",oL="x-momentic-main-branch-name",iL="x-momentic-branch-name",aL="x-momentic-commit-timestamp",sL="x-momentic-last-commit-on-main",lL="x-momentic-last-commit-on-main-timestamp",cL="x-momentic-merged-branch-name",ub="x-momentic-session-id",S8=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),y8=ft.merge(Ud),db=Bs,b8=ft.merge(Ud);var E8=ft.merge(QS).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),fm=Hh,T8=ft.merge(ey),mb=ES,v8=ft.merge(ZS),pb=bS,A8=ft.merge(YS),gb=SS,w8=ft.merge(XS),hb=hS,C8=ft.merge(JS);var R8=ft.merge(oy),x8=ft.merge(iy),M8=S.object({testPaths:S.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:S.string().optional(),all:S.boolean().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional(),testInputMatrix:S.record(S.string(),S.string()).array().optional()}),fb=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var _8=S.string().array(),P8=S.union([S.object({paths:S.string().array().describe("run specific test paths (e.g. todo-test)"),all:S.boolean().describe("run all tests").optional()}),S.object({path:S.string().describe("deprecated; present for backcompat")})]),Sb=S.object({tests:S.record(S.string().describe("Test name"),S.string().describe("Test YAML")),modules:S.record(S.string().describe("Module name"),S.string().describe("Module YAML"))}),uL=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),I8=uL.array(),O8=S.object({testId:S.string(),schemaVersion:S.string()}).merge(Qn);function Sm(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[oL]=encodeURIComponent(e)),t&&(a[iL]=encodeURIComponent(t)),n&&(a[aL]=n.toISOString()),o&&(a[sL]=encodeURIComponent(o)),i&&(a[lL]=i.toISOString()),r.mergedGitBranchName&&(a[cL]=encodeURIComponent(r.mergedGitBranchName)),a}var L8=S.object({entries:S.array(Sf),testId:S.string()}),N8=S.object({entries:S.array(xy),testId:S.string()}),D8=S.object({testId:S.string()});function yb(r){return S.record(S.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 bb=yb(yf),Eb=yb(My),Tb=S.object({trigger:S.nativeEnum(rr),status:S.nativeEnum(Re),startedAt:S.coerce.date().optional(),gitCommitSha:S.string().optional(),gitCommitShaShort:S.string().optional(),gitCommitTimestamp:S.coerce.date().optional(),gitBranchName:S.string().optional(),gitOriginUrl:S.string().optional(),gitCommitMessage:S.string().optional(),gitCommitAuthorName:S.string().optional(),githubRepository:S.string().optional(),gitlabProjectPath:S.string().optional(),pipelineId:S.string().optional(),cliVersion:S.string().optional()}),k8=S.object({id:S.string()}),vb=S.object({status:S.nativeEnum(Re),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),Ab=S.object({stepsSnapshot:S.array(S.record(S.unknown())).optional(),runGroupId:S.string().optional(),testId:S.string(),testName:S.string(),resolvedBaseUrl:S.string().optional(),environmentName:S.string().optional(),labels:S.array(S.string()).optional(),cliVersion:S.string().optional(),trigger:S.nativeEnum(rr),schemaVersion:S.string().optional(),section:S.nativeEnum(il).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),U8=S.object({id:S.string()}),dL=Dd.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),wb=dL.array(),Cb=Dd.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(),F8=S.object({id:S.string()}),Rb=S.object({status:S.nativeEnum(Re),finishedAt:S.coerce.date().optional(),schemaVersion:S.string().optional().default("1.0.19"),results:S.record(S.string(),S.unknown()).array().optional(),beforeResults:S.record(S.string(),S.unknown()).array().optional(),afterResults:S.record(S.string(),S.unknown()).array().optional()}),B8=S.object({screenshot:S.string()}),xb=S.object({key:S.string()}),Mb=S.object({orgId:S.string(),userId:S.string()}),_b=S.array(LS),z8=S.record(S.string(),S.union([S.string(),S.boolean()])),H8=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),Pb=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),G8=S.object({suiteRunIds:S.string().array()}),V8=jS.array(),W8=S.object({runGroupIds:S.string().array()}),mL=S.object({uploadUrl:S.string()}),j8=ft.merge(ty),$8=ft.merge(ny),q8=ft.merge(ry),pL=S.object({testId:S.string().optional().default(""),testName:S.string().optional().default(""),suiteId:S.string().optional().default(""),suiteName:S.string().optional().default(""),creditsUsed:S.number().optional()}),gL=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(fa),properties:pL}),K8=gL.array(),Ib=ab.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),Y8=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),Ob=GS.array(),X8=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),Lb=mL.extend({id:S.string()}),J8=S.object({runGroupId:S.string().uuid().optional()}),Nb=S.object({runGroupId:S.string().uuid()}),Db=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),Q8=S.object({testId:S.string().uuid(),testName:S.string().optional(),reason:S.string(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Z8=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),e9=ft.merge(uy),t9=ft.merge(dy),r9=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(hl).optional(),osVersion:S.nativeEnum(Ta).optional(),sessionId:S.string().optional()}),kb=S.object({name:S.string(),webRtcUrl:S.string(),adbUrl:S.string(),token:S.string(),apkDownloadUrl:S.string().optional(),playwrightServerUrl:S.string().optional(),region:S.string().optional()}),n9=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),Ub=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),Fb=S.object({assets:S.array(S.object({channel:S.string(),tag:S.string(),md5:S.string(),createdAt:S.number().describe("Unix timestamp in milliseconds")}))});import{z as Z}from"zod";var Bb=7,hL=3,a9=Z.object({localTestId:Z.string(),quarantinedAt:Z.date(),quarantinedBy:Z.string().optional(),quarantinedReason:Z.string(),quarantinedByGitEmail:Z.string().optional(),quarantinedByGitName:Z.string().optional(),quarantinedByGitUsername:Z.string().optional()}).or(Z.object({cloudTestId:Z.string(),quarantinedAt:Z.date(),quarantinedBy:Z.string().optional(),quarantinedReason:Z.string(),quarantinedByGitEmail:Z.string().optional(),quarantinedByGitName:Z.string().optional(),quarantinedByGitUsername:Z.string().optional()})),zb=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(zb||{});var ym=Z.object({name:Z.string(),description:Z.string().nullish(),effect:Z.nativeEnum(zb),labels:Z.array(Z.string()).nullish(),githubRepository:Z.string().nullish(),gitlabProjectPath:Z.string().nullish(),gitBranchName:Z.string().nullish(),slackNotificationChannel:Z.string().nullish()}),fL=Z.object({type:Z.literal("LAST_N_RUNS"),lastN:Z.number().min(hL)}),SL=Z.object({type:Z.literal("LAST_N_HOURS"),lastN:Z.number().min(1).max(Bb*24)}),yL=Z.object({type:Z.literal("LAST_N_DAYS"),lastN:Z.number().min(1).max(Bb)}),bm=Z.discriminatedUnion("type",[fL,SL,yL]),bL=Z.object({flakeRateThreshold:Z.number().min(1).max(100),evaluationWindow:bm}),EL=ym.extend({type:Z.literal("FLAKE_RATE"),config:bL}),TL=Z.object({passRateThreshold:Z.number().min(1).max(100),evaluationWindow:bm}),vL=ym.extend({type:Z.literal("PASS_RATE"),config:TL}),AL=Z.object({failureCountThreshold:Z.number().min(0),evaluationWindow:bm}),wL=ym.extend({type:Z.literal("FAILURE_COUNT"),config:AL}),s9=Z.discriminatedUnion("type",[EL,vL,wL]);import{z as Ze}from"zod";var u9=Ze.object({repositoriesIndexed:Ze.boolean(),indexingInProgress:Ze.boolean(),indexesOutdated:Ze.boolean()}),Hb=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(Hb||{}),Gb=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(Gb||{}),d9=Ze.object({name:Ze.string(),status:Ze.nativeEnum(Hb),conclusion:Ze.nativeEnum(Gb).nullable()}),Ia=Ze.object({sha:Ze.string(),message:Ze.string(),author:Ze.object({name:Ze.string().optional(),email:Ze.string().optional(),date:Ze.coerce.date().optional()}),committer:Ze.object({name:Ze.string().optional(),email:Ze.string().optional(),date:Ze.coerce.date().optional()})}),Em=Ze.object({mergedBranch:Ze.string().optional()});import{z as He}from"zod";var Vb=He.object({orgId:He.string(),cacheKeys:He.string().array()}),g9=He.object({keyParams:Vb,clientMetadata:He.string(),lockAcquisitionTimeoutMs:He.number().optional()}),Wb=He.object({acquired:He.boolean(),acquiredByMetadata:He.string(),keyPrefix:He.string()}),h9=He.object({keyPrefix:He.string(),result:He.string(),ttlMs:He.number()}),f9=He.union([He.object({keyPrefix:He.string()}),Vb]),CL=He.object({remainingTtlMs:He.number(),value:He.string().nullish()}),S9=He.object({results:He.record(He.string(),CL),activeLocks:He.string().array()});var y9=5*60*1e3;var v9=90*24*60*60*1e3,A9=7*24*60*60*1e3;import{z as jb}from"zod";var R9=jb.object({quarantineNotifications:jb.string().nullish()});import{z as yt}from"zod";var RL=yt.object({version:yt.string(),json:yt.record(yt.unknown()),hash:yt.string()}),$b=yt.record(yt.unknown()),P9=yt.object({newSvgs:yt.array(RL),metadata:$b.optional()}),xL=yt.object({version:yt.string(),json:yt.record(yt.unknown()).nullish(),hash:yt.string(),description:yt.string().nullish(),metadata:$b.nullish()}),qb=yt.record(yt.string().describe("icon hash"),xL);import{z as je}from"zod";var Tm=je.object({assertion:je.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),ML=je.object({instruction:je.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:Tm.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.")}),Kb=ML.extend({subSteps:je.lazy(()=>Kb.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Yb=je.object({name:je.string().describe("Short name describing the test plan"),description:je.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),Xb=Yb.extend({id:je.string(),createdAt:je.coerce.date(),updatedAt:je.coerce.date(),updatedBy:je.string(),createdBy:je.string(),test:je.object({id:je.string(),name:je.string()}).nullish().transform(r=>r??void 0)}),N9=Xb.extend({testGenRuns:je.tuple([]).or(je.tuple([je.object({id:je.string(),startedAt:je.coerce.date(),status:je.nativeEnum(Re)})]))}),Jb=je.object({preConditions:Tm.array().nullish().transform(r=>r??[]),postConditions:Tm.array().nullish().transform(r=>r??[]),steps:Kb.array().nullish().transform(r=>r??[])}),D9=Xb.extend({plan:Jb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),_L=Yb.extend({plan:Jb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),k9=_L.array().nullish().transform(r=>r??[]);import{validator as PL}from"@exodus/schemasafe";function Qb(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{PL(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var Zb=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var _l=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as Z9}from"zod";var Pl=class{async resolveEntries(){}async saveEntries(){}};import{z as vm}from"zod";var eE=vm.object({parentStepIdChain:vm.array(vm.string()),result:Ut});import{z as Y}from"zod";var IL=Y.object({step:lt,status:Y.nativeEnum(Ke),startedAt:Y.coerce.date(),finishedAt:Y.coerce.date().optional(),healMetadata:Y.object({healType:Y.nativeEnum(ua).or(Y.literal("AI")),healedAt:Y.coerce.date()}).optional(),beforeSnapshotId:Y.string().uuid().optional(),afterSnapshotId:Y.string().uuid().optional(),message:Y.string().optional()}),OL=IL.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),SQ=OL.extend({step:Y.unknown()}),tE="1.0.0",Am=Rb.extend({id:Y.string().uuid().optional(),startedAt:Y.coerce.date(),runAttemptSchemaVersion:Y.string().optional(),schemaVersion:Y.string().optional().default("1.0.19"),results:Y.record(Y.string(),Y.unknown()).array().optional(),beforeResults:Y.record(Y.string(),Y.unknown()).array().optional(),afterResults:Y.record(Y.string(),Y.unknown()).array().optional(),activeVideos:Y.array(Y.object({videoName:Y.string(),timestamp:Y.coerce.date()})).optional()}),rE=Am.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),yQ=Am.merge(da),bQ=rE.merge(da),nE=Y.object({results:Y.array(Ut),beforeResults:Y.array(Ut).optional(),afterResults:Y.array(Ut).optional()}),EQ=Am.merge(nE),TQ=rE.merge(nE),LL=Cb.merge(Ab).extend({executionType:Y.nativeEnum(Xo).optional().default("WEB"),testId:Y.string().uuid(),testDescription:Y.string().optional(),runGroupId:Y.string().uuid(),status:Y.nativeEnum(Re),startedAt:Y.coerce.date(),attempts:Y.number(),failureRecoveryDetails:Y.object({attempts:Y.number()}).optional()}),vQ=LL.extend({finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)}),NL=Tb.merge(vb).extend({id:Y.string().uuid().optional(),startedAt:Y.coerce.date(),cliVersion:Y.string(),labels:Y.string().array().optional().default([])}),Il=NL.extend({updatedAt:Y.coerce.date().optional().transform(r=>r??new Date),finishedAt:Y.coerce.date().optional().transform(r=>r??new Date)});import{confirm as DL,input as kL}from"@inquirer/prompts";import{existsSync as XZ,mkdirSync as JZ,statSync as UL}from"fs";var lo=!!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;var FL=!1,oE=(()=>{try{return UL("/.dockerenv"),!0}catch{return!1}})();async function Ol(r){return lo||FL||oE?!0:(await C.flush(),await new Promise(t=>setTimeout(t,100)),await DL({message:r}))}async function iE(r,e){return lo||oE?e:(await kL({message:r,default:e})).trim()||e}import si,{supportsColor as YL}from"chalk";import{Console as aE}from"console";import{format as Oa}from"util";var wm=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}},Ll=class r extends aE{_buffer=[];_groupDepth=0;Console=aE;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new wm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
24
24
|
`).slice(o).filter(Boolean).join(`
|
|
25
25
|
`);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",Oa(e,...t))}error(e,...t){this._log("error",Oa(e,...t))}info(e,...t){this._log("info",Oa(e,...t))}log(e,...t){this._log("log",Oa(e,...t))}warn(e,...t){this._log("warn",Oa(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function sE(r){let e=globalThis.console,t=new Ll;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
26
26
|
`);process.stderr.write(`${o}
|
|
27
|
-
`),globalThis.console=e}}var Cm=" ".repeat(6);import BL from"fetch-retry";import zL from"os";import lE,{multistream as HL}from"pino";import GL from"pino-pretty";import VL from"pino-std-serializers";var ii=new Map,WL=!0,cE="Log throttle exceeded",jL=100,$L=5e3,qL=BL(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}}),Rm=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??zL.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=WL?lE(a):lE(a,HL([{stream:GL({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await qL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:so(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===cE)return!0;let t=Date.now();return t-this.lastWindowStart>$L&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,cE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<jL?(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(Pa[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=VL.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 s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:Qy({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,ii.set("app",this),ii.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=Zy[e]):(this.minLevelValue=Pa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ai=({app:r,hostname:e,disableConsoleLogs:t})=>(ii.has(r)||ii.set(r,new Rm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ii.get(r));async function uE(){await Promise.all([...ii.values()].map(r=>r.flush()))}import{hostname as KL}from"os";var ar=ai({app:"cli",hostname:KL(),disableConsoleLogs:!0}).child({cliVersion:"0.9.1"});function xm(r){if(!r)return;r=r.toLowerCase();let e=Cl.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function dE({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),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),l=r.filter(u=>u.status==="CANCELLED");return sE(()=>{if(c.forEach(u=>{C.log(""),o(u)}),c.length){C.log("");let u=c.length===1?"":"s";C.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{C.dimmed(n(d))})}if(l.length){C.log("");let u=l.length===1?"":"s";C.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{C.dimmed(n(d))})}if(a.length){C.log("");let u=a.length===1?"":"s";C.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{C.dimmed(n(d))})}if(s.length){C.log("");let u=s.length===1?"":"s";C.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{C.dimmed(n(d))})}if(i.length){C.log("");let u=i.length===1?"":"s";C.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{C.dimmed(n(d))})}C.log(""),C.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var La=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=si.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=si.bgGreen.white("PASS"),a=3):r.includes("START")?(i=si.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=si.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=si.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=si.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),YL||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import XL from"fs";import{tmpdir as JL}from"os";import QL from"path";import{registry as Na}from"playwright-core/lib/server";import mE from"proper-lockfile";var pE=QL.join(JL(),"momenticBrowserInstallation");var Mm=["chrome","chromium","chrome-for-testing","ffmpeg"],ZL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},gE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function hE(r){let e=gE[ZL[r]??""]??"",t=Na.findExecutable(e);return!t||t.installType==="none"?!1:_m(t)}function _m(r){let e=r.executablePath();return XL.existsSync(e)}function eN(r,e){let t=gE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Na.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&_m(n)))return n}async function tN({browser:r,force:e}){let t=eN(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await Na.installDeps([t],!1),await Na.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){C.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Na.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!_m(o);)C.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Nl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Mm:Array.from(new Set(r));try{await mE.lock(pE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){C.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 tN({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await mE.unlock(pE,{realpath:!1})}if(o)throw o}import{createServer as rN}from"http";async function Dl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await kl(o))return o}C.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function kl(r){return new Promise((e,t)=>{let n=rN();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(C.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import tee from"blocked-at";import nee from"why-is-node-running";import L0 from"fs";import{tmpdir as N0}from"os";import D0 from"path";import{remote as k0}from"webdriverio";import{createInstanceClient as R0}from"@limrun/api";import{execSync as x0}from"child_process";import gee,{multistream as fee}from"pino";import yee from"pino-pretty";var Tee=5*1024,nN="...[truncated]",vee=Buffer.byteLength(nN,"utf8");import{PostHog as Oee}from"posthog-node";var Rn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var fE=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 k(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:m}=e;if(m.aborted)return c(fE(m));l=()=>c(fE(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new Rn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as Hee}from"posthog-node";import{execSync as oN}from"child_process";import li from"os";import iN from"v8";var SE,Dr,bE=li.platform(),aN=li.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),{}),yE=r=>{try{let e={},t=!1,n=sN(),o=lN(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),t=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(t=!0);let s=iN.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(t=!0),t?(r.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),lo&&C.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function EE(r){if(!Lr)return yE(r),{interval:setInterval(()=>yE(r),2e4),cpuMetadata:aN,platform:bE}}function sN(){let r=li.totalmem(),e=bE==="darwin"?cN():(()=>{let n=li.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function lN(){let r=li.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,!Dr)return Dr=t,null;let n={user:t.user-Dr.user,nice:t.nice-Dr.nice,sys:t.sys-Dr.sys,idle:t.idle-Dr.idle,irq:t.irq-Dr.irq,total:t.total-Dr.total};return SE={measurementTime:e,intervalMs:e-Dr.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},Dr=t,SE}function cN(){try{let r=oN("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=li.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Ul=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function uN(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 Fl(r,e){let t=uN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var qE="=",Gl=";",Hm=",";var KE=8192;var mi={};TM(mi,{getKeyPairs:()=>VN,parseKeyPairsIntoRecord:()=>WN,parsePairKeyValue:()=>YE,serializeKeyPairs:()=>GN});Me();var HN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function GN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Hm:"")+t;return n.length>KE?e:n},"")}function VN(r){return r.getAllEntries().map(function(e){var t=HN(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Gl+o.metadata.toString()),i})}function YE(r){var e=r.split(Gl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(qE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Im(e.join(Gl))),{key:o,value:i,metadata:a}}}}}function WN(r){return typeof r!="string"||r.length===0?{}:r.split(Hm).map(function(e){return YE(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 Vl;(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"})(Vl||(Vl={}));var jN=",",$N=["OTEL_SDK_DISABLED"];function qN(r){return $N.indexOf(r)>-1}var KN=["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 YN(r){return KN.indexOf(r)>-1}var XN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function JN(r){return XN.indexOf(r)>-1}var Gm=1/0,Vm=128,QN=128,ZN=128,Wm={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:Ue.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:QN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:ZN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Vl.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 eD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function tD(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 rD(r,e,t,n){n===void 0&&(n=jN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var nD={ALL:Ue.ALL,VERBOSE:Ue.VERBOSE,DEBUG:Ue.DEBUG,INFO:Ue.INFO,WARN:Ue.WARN,ERROR:Ue.ERROR,NONE:Ue.NONE};function oD(r,e,t){var n=t[r];if(typeof n=="string"){var o=nD[n.toUpperCase()];o!=null&&(e[r]=o)}}function XE(r){var e={};for(var t in Wm){var n=t;switch(n){case"OTEL_LOG_LEVEL":oD(n,e,r);break;default:if(qN(n))eD(n,e,r);else if(YN(n))tD(n,e,r);else if(JN(n))rD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function bt(){var r=XE(process.env);return Object.assign({},Wm,r)}function JE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Wl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=JE(r.charCodeAt(n)),i=JE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var QE="1.25.1";var iD="deployment.environment";var aD="process.runtime.name";var sD="service.name";var lD="service.instance.id";var cD="telemetry.sdk.name",uD="telemetry.sdk.language",dD="telemetry.sdk.version";var ZE=iD;var eT=aD;var jl=sD;var tT=lD;var Ha=cD,Ga=uD,Va=dD;var mD="nodejs";var rT=mD;var pi,$l=(pi={},pi[Ha]="opentelemetry",pi[eT]="node",pi[Ga]=rT,pi[Va]=QE,pi);var pD=9,gD=6,hD=Math.pow(10,gD),fD=Math.pow(10,pD);function nT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*hD);return[t,n]}function oT(r){return r[0]*fD+r[1]}function Wa(r){return r[0]*1e6+r[1]/1e3}var uo;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(uo||(uo={}));var iT=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 SD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yD=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))},aT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new iT}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,yD([this._that],SD(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 sr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(sr||(sr={}));var Mt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Mt||(Mt={}));var bD=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 dne=function(r){bD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function sT(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 lr;(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"})(lr||(lr={}));var lT=function(){function r(){this.kind=lr.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 se;(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"})(se||(se={}));var ED=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function TD(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 jm=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=TD(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=sT(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 $m=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jm(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,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new jm(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new jm(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.HISTOGRAM,dataPoints:n.map(function(i){var a=ED(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var qm=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Km=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))},Ym=function(){function r(e,t,n,o){e===void 0&&(e=new vD),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 s=a%n;s<0&&(s+=n);for(var c=s;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 vD=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,Km([n,this._counts.length-t],qm(this._counts.slice(t)),!1)),o.splice.apply(o,Km([0,t],qm(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(Km([],qm(this._counts),!1))},r}();var cT=52,AD=2146435072,wD=1048575,Xm=1023,ql=-Xm+1,Kl=Xm,ja=Math.pow(2,-1022);function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&AD)>>20;return n-Xm}function Xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&wD)*Math.pow(2,32);return o+n}function $a(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function dT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var CD=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)}}(),xn=function(r){CD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var pT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ja)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,cT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new xn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new xn("overflow: "+e+" is > maximum lower boundary: "+n);return $a(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=ql>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Kl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var gT=function(){function r(e){this._scale=e,this._scaleFactor=$a(Math.LOG2E,e),this._inverseFactor=$a(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ja)return this._minNormalLowerBoundaryIndex()-1;if(Xl(e)===0){var t=Yl(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 xn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ja;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new xn("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 ql<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Kl+1<<this._scale)-1},r}();var hT=-10,fT=20,RD=Array.from({length:31},function(r,e){return e>10?new gT(e-10):new pT(e-10)});function Jm(r){if(r>fT||r<hT)throw new xn("expected scale >= "+hT+" && <= "+fT+", got: "+r);return RD[r+10]}var xD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jl=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}(),MD=20,_D=160,Qm=2,PD=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=_D),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Ym),u===void 0&&(u=new Ym),d===void 0&&(d=Jm(MD)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<Qm&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Qm),this._maxSize=Qm)}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,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(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=dT(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},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=Jm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Jl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Jl.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 Jl(0,-1);var o=t-n;return new Jl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var ST=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PD(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:Mt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=xD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();var ID=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zm=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=nT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var yT=function(){function r(){this.kind=lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Zm(e)},r.prototype.merge=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.GAUGE,dataPoints:n.map(function(i){var a=ID(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var OD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qa=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 ep=function(){function r(e){this.monotonic=e,this.kind=lr.SUM}return r.prototype.createAccumulation=function(e){return new qa(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new qa(t.startTime,this.monotonic,o,t.reset):new qa(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 qa(t.startTime,this.monotonic,o,!0):new qa(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.SUM,dataPoints:n.map(function(i){var a=OD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var mo=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)}}(),Ur=function(){function r(){}return r.Drop=function(){return RT},r.Sum=function(){return xT},r.LastValue=function(){return MT},r.Histogram=function(){return _T},r.ExponentialHistogram=function(){return LD},r.Default=function(){return ND},r}();var bT=function(r){mo(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 lT,e}(Ur);var ET=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ep(!0),e.NON_MONOTONIC_INSTANCE=new ep(!1),e}(Ur);var TT=function(r){mo(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 yT,e}(Ur);var vT=function(r){mo(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 $m([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ur);var AT=function(r){mo(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(s,c){return s-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 $m(this._boundaries,this._recordMinMax)},e}(Ur);var wT=function(r){mo(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 ST(this._maxSize,this._recordMinMax)},e}(Ur);var CT=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case se.COUNTER:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return xT;case se.GAUGE:case se.OBSERVABLE_GAUGE:return MT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new AT(t.advice.explicitBucketBoundaries):_T}return H.warn("Unable to recognize instrument type: "+t.type),RT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ur);var RT=new bT,xT=new ET,MT=new TT,_T=new vT,LD=new wT,ND=new CT;Me();function Ql(){return"unknown_service:"+process.argv0}var Mn=function(){return Mn=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},Mn.apply(this,arguments)},DD=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},kD=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},UD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tp=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[jl]=Ql(),e[Ga]=$l[Ga],e[Ha]=$l[Ha],e[Va]=$l[Va],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 DD(this,void 0,void 0,function(){return kD(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=Mn(Mn({},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 s,c=UD(a,2),l=c[0],u=c[1];return Mn(Mn(Mn(Mn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var po;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(po||(po={}));Me();var FD=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},BD=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},rp=function(){return sr.CUMULATIVE},PT=function(r){switch(r){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.GAUGE:case se.HISTOGRAM:case se.OBSERVABLE_GAUGE:return sr.DELTA;case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return sr.CUMULATIVE}},IT=function(r){switch(r){case se.COUNTER:case se.HISTOGRAM:return sr.DELTA;case se.GAUGE:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_GAUGE:return sr.CUMULATIVE}};function zD(){var r=bt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?rp:e==="delta"?PT:e==="lowmemory"?IT:(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."),rp)}function HD(r){return r!=null?r===po.DELTA?PT:r===po.LOWMEMORY?IT:rp:zD()}function GD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ur.Default()}}var OT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=GD(t),this._aggregationTemporalitySelector=HD(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return FD(this,void 0,void 0,function(){return BD(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 VD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},LT=1e4,NT=5,DT=1e3,kT=5e3,UT=1.5;function Ka(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=VD(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 np(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function op(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 ip(r){return typeof r=="number"?r<=0?ap(r,LT):r:WD()}function WD(){var r,e=Number((r=bt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:bt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?ap(e,LT):e}function ap(r,e){return H.warn("Timeout must be greater than 0",r),e}function FT(r){var e=[429,502,503,504];return e.includes(r)}function BT(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 zT=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 aT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=ip(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:uo.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:uo.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:uo.SUCCESS})}).catch(function(n){t({code:uo.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 sp from"url";import*as ec from"http";import*as tc from"https";import*as HT from"zlib";import{Readable as $D}from"stream";var _n;(function(r){r.NONE="none",r.GZIP="gzip"})(_n||(_n={}));var jD=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)}}(),gi=function(r){jD(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 Zl=function(){return Zl=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},Zl.apply(this,arguments)};function lp(r,e,t,n,o){var i=r.timeoutMillis,a=new sp.URL(r.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new gi("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Zl({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?ec.request:tc.request,p=function(h,f){switch(h===void 0&&(h=NT),f===void 0&&(f=DT),l=g(m,function(b){var x="";b.on("data",function(v){return x+=v}),b.on("aborted",function(){if(u){var v=new gi("Request Timeout");o(v)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)H.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&FT(b.statusCode)&&h>0){var v=void 0;f=UT*f,b.headers["retry-after"]?v=BT(b.headers["retry-after"]):v=Math.round(Math.random()*(kT-f)+f),c=setTimeout(function(){p(h-1,f)},v)}else{var A=new gi(b.statusMessage,b.statusCode,x);o(A),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new gi("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new gi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case _n.GZIP:{l.setHeader("Content-Encoding","gzip");var E=qD(e);E.on("error",o).pipe(HT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};p()}function qD(r){var e=new $D;return e.push(r),e.push(null),e}function cp(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 sp.URL(r.url),t=e.protocol==="http:"?ec.Agent:tc.Agent;return new t(Zl({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function up(r){if(r)return r;var e=bt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||bt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===_n.GZIP?_n.GZIP:_n.NONE}Me();var KD=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)}}(),rc=function(r){KD(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,Ka(t.headers),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=cp(t),i.compression=up(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,l){var u;lp(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(zT);function VT(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function YD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function WT(r){var e=VT(r);return YD(e)}function XD(r){var e=VT(r);return e.toString()}var JD=typeof BigInt<"u"?XD:oT;function GT(r){return r}function jT(r){if(r!==void 0)return Wl(r)}var QD={encodeHrTime:WT,encodeSpanContext:Wl,encodeOptionalSpanContext:jT};function $T(r){var e,t;if(r===void 0)return QD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?WT:JD,encodeSpanContext:o?GT:Wl,encodeOptionalSpanContext:o?GT:jT}}var ZD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function qT(r){return{name:r.name,version:r.version}}function hi(r){return Object.keys(r).map(function(e){return KT(e,r[e])})}function KT(r,e){return{key:r,value:YT(e)}}function YT(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(YT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=ZD(t,2),o=n[0],i=n[1];return KT(o,i)})}}:{}}function XT(r){return{attributes:hi(r.attributes),droppedAttributesCount:0}}Me();function QT(r,e){var t=$T(e);return{resource:XT(r.resource),schemaUrl:void 0,scopeMetrics:ek(r.scopeMetrics,t)}}function ek(r,e){return Array.from(r.map(function(t){return{scope:qT(t.scope),metrics:t.metrics.map(function(n){return tk(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function tk(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=ik(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:JT(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:JT(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:nk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:ok(r,e)};break}return t}function rk(r,e,t){var n={attributes:hi(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case jt.INT:n.asInt=r.value;break;case jt.DOUBLE:n.asDouble=r.value;break}return n}function JT(r,e){return r.dataPoints.map(function(t){return rk(t,r.descriptor.valueType,e)})}function nk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ok(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ik(r){switch(r){case sr.DELTA:return 1;case sr.CUMULATIVE:return 2}}function ZT(r,e){return{resourceMetrics:r.map(function(t){return QT(t,e)})}}var dp={serializeRequest:function(r){var e=ZT(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 ev="0.52.1";var tv=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)}}(),fi=function(){return fi=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},fi.apply(this,arguments)},rv="v1/metrics",ak="http://localhost:4318/"+rv,sk={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+ev},lk=function(r){tv(e,r);function e(t){var n=r.call(this,t,dp,"application/json")||this;return n.headers=fi(fi(fi(fi({},n.headers),sk),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ka(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?op(bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):bt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?np(bt().OTEL_EXPORTER_OTLP_ENDPOINT,rv):ak},e}(rc),nv=function(r){tv(e,r);function e(t){return r.call(this,new lk(t),t)||this}return e}(OT);var Si;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Si||(Si={}));var Fr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Fr||(Fr={}));Me();var ck=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)}}(),ov=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},iv=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},uk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dk=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))},mk=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 av(r){return r!=null}function nc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function sv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var mp=function(r){ck(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Pn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new mp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function lv(r){return ov(this,void 0,void 0,function(){var e=this;return iv(this,function(t){return[2,Promise.all(r.map(function(n){return ov(e,void 0,void 0,function(){var o,i;return iv(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 cv(r){return r.status==="rejected"}function pp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,dk([],uk(e(n)),!1))}),t}function uv(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=mk(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){t={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function dv(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 mv(r,e){return r.toLowerCase()===e.toLowerCase()}Me();var cr;(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"})(cr||(cr={}));var gp=function(){function r(){this.kind=cr.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 he;(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"})(he||(he={}));function Br(r,e,t){var n,o,i,a;return gk(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:jt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function pv(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 gv(r,e){return mv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var pk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function gk(r){return r.match(pk)!=null}var hk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function fk(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 oc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=fk(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=dv(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 ic=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=cr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new oc(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,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new oc(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new oc(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.HISTOGRAM,dataPoints:n.map(function(i){var a=hk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var hp=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},fp=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))},Sp=function(){function r(e,t,n,o){e===void 0&&(e=new Sk),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 s=a%n;s<0&&(s+=n);for(var c=s;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 Sk=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,fp([n,this._counts.length-t],hp(this._counts.slice(t)),!1)),o.splice.apply(o,fp([0,t],hp(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(fp([],hp(this._counts),!1))},r}();var hv=52,yk=2146435072,bk=1048575,yp=1023,ac=-yp+1,sc=yp,Ya=Math.pow(2,-1022);function lc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&yk)>>20;return n-yp}function cc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&bk)*Math.pow(2,32);return o+n}function Xa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Sv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Ek=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)}}(),In=function(r){Ek(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var bv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ya)return this._minNormalLowerBoundaryIndex();var t=lc(e),n=this._rightShift(cc(e)-1,hv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new In("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new In("overflow: "+e+" is > maximum lower boundary: "+n);return Xa(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=ac>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return sc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Ev=function(){function r(e){this._scale=e,this._scaleFactor=Xa(Math.LOG2E,e),this._inverseFactor=Xa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ya)return this._minNormalLowerBoundaryIndex()-1;if(cc(e)===0){var t=lc(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 In("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ya;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new In("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 ac<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(sc+1<<this._scale)-1},r}();var Tv=-10,vv=20,Tk=Array.from({length:31},function(r,e){return e>10?new Ev(e-10):new bv(e-10)});function bp(r){if(r>vv||r<Tv)throw new In("expected scale >= "+Tv+" && <= "+vv+", got: "+r);return Tk[r+10]}var vk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},uc=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}(),Ak=20,wk=160,Ep=2,Av=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=wk),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Sp),u===void 0&&(u=new Sp),d===void 0&&(d=bp(Ak)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<Ep&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Ep),this._maxSize=Ep)}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,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(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=Sv(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},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=bp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=uc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=uc.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 uc(0,-1);var o=t-n;return new uc(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var Tp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=cr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Av(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:Fr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=vk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();Me();var Ck=Om("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function wv(r){return r.setValue(Ck,!0)}Me();function Cv(){return function(r){H.error(Rk(r))}}function Rk(r){return typeof r=="string"?r:JSON.stringify(xk(r))}function xk(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 Mk=Cv();function dc(r){try{Mk(r)}catch{}}var Rv="1.30.1";var _k="process.runtime.name";var Pk="service.name";var Ik="telemetry.sdk.name",Ok="telemetry.sdk.language",Lk="telemetry.sdk.version";var xv=_k;var Mv=Pk;var Ja=Ik,Qa=Ok,Za=Lk;var Nk="nodejs";var _v=Nk;var yi,go=(yi={},yi[Ja]="opentelemetry",yi[xv]="node",yi[Qa]=_v,yi[Za]=Rv,yi);function es(r){r.unref()}var Hk=9,Gk=6,Vk=Math.pow(10,Gk),hae=Math.pow(10,Hk);function ho(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*Vk);return[t,n]}function bi(r){return r[0]*1e6+r[1]/1e3}var ts;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ts||(ts={}));Me();function Pv(r,e){return new Promise(function(t){di.with(wv(di.active()),function(){r.export(e,function(n){t(n)})})})}var Iv={_export:Pv};var Wk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},mc=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=ho(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vp=function(){function r(){this.kind=cr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new mc(e)},r.prototype.merge=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.GAUGE,dataPoints:n.map(function(i){var a=Wk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var jk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ei=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 pc=function(){function r(e){this.monotonic=e,this.kind=cr.SUM}return r.prototype.createAccumulation=function(e){return new Ei(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ei(t.startTime,this.monotonic,o,t.reset):new Ei(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 Ei(t.startTime,this.monotonic,o,!0):new Ei(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.SUM,dataPoints:n.map(function(i){var a=jk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var fo=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)}}(),ur=function(){function r(){}return r.Drop=function(){return Fv},r.Sum=function(){return Bv},r.LastValue=function(){return zv},r.Histogram=function(){return Hv},r.ExponentialHistogram=function(){return $k},r.Default=function(){return qk},r}();var Ov=function(r){fo(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 gp,e}(ur);var Lv=function(r){fo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case he.COUNTER:case he.OBSERVABLE_COUNTER:case he.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new pc(!0),e.NON_MONOTONIC_INSTANCE=new pc(!1),e}(ur);var Nv=function(r){fo(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 vp,e}(ur);var Dv=function(r){fo(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 ic([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ur);var rs=function(r){fo(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(s,c){return s-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 ic(this._boundaries,this._recordMinMax)},e}(ur);var kv=function(r){fo(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 Tp(this._maxSize,this._recordMinMax)},e}(ur);var Uv=function(r){fo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case he.COUNTER:case he.UP_DOWN_COUNTER:case he.OBSERVABLE_COUNTER:case he.OBSERVABLE_UP_DOWN_COUNTER:return Bv;case he.GAUGE:case he.OBSERVABLE_GAUGE:return zv;case he.HISTOGRAM:return t.advice.explicitBucketBoundaries?new rs(t.advice.explicitBucketBoundaries):Hv}return H.warn("Unable to recognize instrument type: "+t.type),Fv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ur);var Fv=new Ov,Bv=new Lv,zv=new Nv,Hv=new Dv,$k=new kv,qk=new Uv;var Gv=function(r){return ur.Default()},Vv=function(r){return Si.CUMULATIVE};var Ap=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},wp=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Wv=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Kk=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))},jv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:Gv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:Vv,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 Ap(this,void 0,void 0,function(){var t,n,o,i,a,s;return wp(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(Kk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],Wv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=Wv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(pp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(pp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var Yk=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)}}(),gc=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},hc=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Xk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jk=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))},Cp=function(r){Yk(e,r);function e(t){var n,o,i,a,s=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 s._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=t.exporter,s}return e.prototype._runOnce=function(){return gc(this,void 0,void 0,function(){var t;return hc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Pn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof mp?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(dc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return gc(this,void 0,void 0,function(){var o,i,a,s,c,l;return hc(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=H).error.apply(l,Jk(["PeriodicExportingMetricReader: metrics collection errors"],Xk(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 s=u.sent(),H.debug("Error while resolving async portion of resource: ",s),dc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,Iv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ts.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),es(this._interval)},e.prototype.onForceFlush=function(){return gc(this,void 0,void 0,function(){return hc(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 gc(this,void 0,void 0,function(){return hc(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}(jv);Me();Me();function fc(){return"unknown_service:"+process.argv0}var On=function(){return On=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},On.apply(this,arguments)},Qk=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Zk=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},e0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Sc=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[Mv]=fc(),e[Qa]=go[Qa],e[Ja]=go[Ja],e[Za]=go[Za],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 Qk(this,void 0,void 0,function(){return Zk(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=On(On({},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 s,c=e0(a,2),l=c[0],u=c[1];return On(On(On(On({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var $v=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 So=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)}}(),yc=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=di.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===jt.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,ho(Date.now()))},r}();var qv=function(r){So(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}(yc);var Kv=function(r){So(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}(yc);var Yv=function(r){So(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}(yc);var Xv=function(r){So(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}(yc);var bc=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 Jv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Qv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Zv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);function ns(r){return r instanceof bc}var eA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Br(e,he.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new Yv(o,n)},r.prototype.createHistogram=function(e,t){var n=Br(e,he.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new Xv(o,n)},r.prototype.createCounter=function(e,t){var n=Br(e,he.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Kv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Br(e,he.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new qv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Br(e,he.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Qv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Br(e,he.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Jv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Br(e,he.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Zv(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 Ec=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Br(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var t0=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)}}(),tA=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},r0=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 tA(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 tA(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 Tr=function(r){t0(e,r);function e(){return r.call(this,nc)||this}return e}(r0);var n0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Tc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Tr,this._cumulativeMemoStorage=new Tr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=nc(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 s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.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=n0(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Tr,e},r}();var Rp=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.")},rA=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},vc=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,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===Si.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=o0(a);if(u.length!==0)return this._aggregator.toMetricData(t,s,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Rp(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){t={error:l}}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 Tr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Rp(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=r.merge(o,c,this._aggregator)}}catch(l){t={error:l}}finally{try{s&&!s.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 s=rA(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Rp(e.keys()),s=a.next();!s.done;s=a.next()){var c=rA(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function o0(r){return Array.from(r.entries())}var i0=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)}}(),a0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nA=function(r){i0(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Tc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new vc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Tr;Array.from(t.entries()).forEach(function(a){var s=a0(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),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}(Ec);Me();function xp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
27
|
+
`),globalThis.console=e}}var Cm=" ".repeat(6);import BL from"fetch-retry";import zL from"os";import lE,{multistream as HL}from"pino";import GL from"pino-pretty";import VL from"pino-std-serializers";var ii=new Map,WL=!0,cE="Log throttle exceeded",jL=100,$L=5e3,qL=BL(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}}),Rm=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??zL.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=WL?lE(a):lE(a,HL([{stream:GL({colorize:!0})}]))}child(e){return new r({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}async flush(){await this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush()}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let t=await qL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:so(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===cE)return!0;let t=Date.now();return t-this.lastWindowStart>$L&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,cE),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<jL?(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(Pa[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=VL.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 s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:Qy({message:n||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let t=this.bindingAttributes.app;this.bindingAttributes.app=e,ii.set("app",this),ii.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=Zy[e]):(this.minLevelValue=Pa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},ai=({app:r,hostname:e,disableConsoleLogs:t})=>(ii.has(r)||ii.set(r,new Rm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),ii.get(r));async function uE(){await Promise.all([...ii.values()].map(r=>r.flush()))}import{hostname as KL}from"os";var ar=ai({app:"cli",hostname:KL(),disableConsoleLogs:!0}).child({cliVersion:"0.9.2"});function xm(r){if(!r)return;r=r.toLowerCase();let e=Cl.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function dE({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),s=r.filter(u=>u.status==="FAILED"&&u.quarantined),c=r.filter(u=>u.status==="FAILED"&&!u.quarantined),l=r.filter(u=>u.status==="CANCELLED");return sE(()=>{if(c.forEach(u=>{C.log(""),o(u)}),c.length){C.log("");let u=c.length===1?"":"s";C.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{C.dimmed(n(d))})}if(l.length){C.log("");let u=l.length===1?"":"s";C.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{C.dimmed(n(d))})}if(a.length){C.log("");let u=a.length===1?"":"s";C.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{C.dimmed(n(d))})}if(s.length){C.log("");let u=s.length===1?"":"s";C.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{C.dimmed(n(d))})}if(i.length){C.log("");let u=i.length===1?"":"s";C.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{C.dimmed(n(d))})}C.log(""),C.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var La=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=si.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=si.bgGreen.white("PASS"),a=3):r.includes("START")?(i=si.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=si.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=si.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=si.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),YL||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import XL from"fs";import{tmpdir as JL}from"os";import QL from"path";import{registry as Na}from"playwright-core/lib/server";import mE from"proper-lockfile";var pE=QL.join(JL(),"momenticBrowserInstallation");var Mm=["chrome","chromium","chrome-for-testing","ffmpeg"],ZL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},gE={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function hE(r){let e=gE[ZL[r]??""]??"",t=Na.findExecutable(e);return!t||t.installType==="none"?!1:_m(t)}function _m(r){let e=r.executablePath();return XL.existsSync(e)}function eN(r,e){let t=gE[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Na.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&_m(n)))return n}async function tN({browser:r,force:e}){let t=eN(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await Na.installDeps([t],!1),await Na.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){C.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Na.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!_m(o);)C.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Nl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Mm:Array.from(new Set(r));try{await mE.lock(pE,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){C.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 tN({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await mE.unlock(pE,{realpath:!1})}if(o)throw o}import{createServer as rN}from"http";async function Dl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await kl(o))return o}C.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function kl(r){return new Promise((e,t)=>{let n=rN();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(C.warn({err:o},"Unexpected error checking for open ports, continuing..."),n.close(),e(!0))}),n.once("listening",()=>{n.close(()=>{e(!0)})}),n.listen(r)})}import ree from"blocked-at";import oee from"why-is-node-running";import L0 from"fs";import{tmpdir as N0}from"os";import D0 from"path";import{remote as k0}from"webdriverio";import{createInstanceClient as R0}from"@limrun/api";import{execSync as x0}from"child_process";import hee,{multistream as See}from"pino";import bee from"pino-pretty";var vee=5*1024,nN="...[truncated]",Aee=Buffer.byteLength(nN,"utf8");import{PostHog as Lee}from"posthog-node";var Rn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var fE=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 k(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((s,c)=>{let l;if(e.signal){let{signal:m}=e;if(m.aborted)return c(fE(m));l=()=>c(fE(m)),m.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(m){c(m)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let m=o instanceof Error?o:new Rn(o??`Promise timed out after ${t}ms`);c(m)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(m=>{d(),s(m)}).catch(m=>{d(),c(m)})})}import{PostHog as Gee}from"posthog-node";import{execSync as oN}from"child_process";import li from"os";import iN from"v8";var SE,Dr,bE=li.platform(),aN=li.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),{}),yE=r=>{try{let e={},t=!1,n=sN(),o=lN(),i=`${Math.round(n.freePercentage*100)}%`;n.freePercentage<.05&&(Object.assign(e,process.memoryUsage()),t=!0);let a=`${o?Math.round(o.idle):"unknown"}%`;o&&o?.total>80&&(t=!0);let s=iN.getHeapStatistics(),c=s.used_heap_size,l=s.heap_size_limit;c/l>.9&&(t=!0),t?(r.warn({memory:n,cpu:o,heapStats:s,...e},"Critical resource usage metrics detected"),lo&&C.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function EE(r){if(!Lr)return yE(r),{interval:setInterval(()=>yE(r),2e4),cpuMetadata:aN,platform:bE}}function sN(){let r=li.totalmem(),e=bE==="darwin"?cN():(()=>{let n=li.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function lN(){let r=li.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,!Dr)return Dr=t,null;let n={user:t.user-Dr.user,nice:t.nice-Dr.nice,sys:t.sys-Dr.sys,idle:t.idle-Dr.idle,irq:t.irq-Dr.irq,total:t.total-Dr.total};return SE={measurementTime:e,intervalMs:e-Dr.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},Dr=t,SE}function cN(){try{let r=oN("/usr/bin/vm_stat",{encoding:"utf8",stdio:["pipe","pipe","ignore"]}),t=r.match(/page size of (\d+) bytes/)?.[1],n=t?Number.parseInt(t,10):4096,o=u=>{let m=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return m?Number.parseInt(m,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=li.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var Ul=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function uN(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 Fl(r,e){let t=uN(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var qE="=",Gl=";",Hm=",";var KE=8192;var mi={};TM(mi,{getKeyPairs:()=>VN,parseKeyPairsIntoRecord:()=>WN,parsePairKeyValue:()=>YE,serializeKeyPairs:()=>GN});Me();var HN=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function GN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Hm:"")+t;return n.length>KE?e:n},"")}function VN(r){return r.getAllEntries().map(function(e){var t=HN(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Gl+o.metadata.toString()),i})}function YE(r){var e=r.split(Gl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(qE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Im(e.join(Gl))),{key:o,value:i,metadata:a}}}}}function WN(r){return typeof r!="string"||r.length===0?{}:r.split(Hm).map(function(e){return YE(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 Vl;(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"})(Vl||(Vl={}));var jN=",",$N=["OTEL_SDK_DISABLED"];function qN(r){return $N.indexOf(r)>-1}var KN=["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 YN(r){return KN.indexOf(r)>-1}var XN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function JN(r){return XN.indexOf(r)>-1}var Gm=1/0,Vm=128,QN=128,ZN=128,Wm={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:Ue.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Gm,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Vm,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:QN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:ZN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Vl.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 eD(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function tD(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 rD(r,e,t,n){n===void 0&&(n=jN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var nD={ALL:Ue.ALL,VERBOSE:Ue.VERBOSE,DEBUG:Ue.DEBUG,INFO:Ue.INFO,WARN:Ue.WARN,ERROR:Ue.ERROR,NONE:Ue.NONE};function oD(r,e,t){var n=t[r];if(typeof n=="string"){var o=nD[n.toUpperCase()];o!=null&&(e[r]=o)}}function XE(r){var e={};for(var t in Wm){var n=t;switch(n){case"OTEL_LOG_LEVEL":oD(n,e,r);break;default:if(qN(n))eD(n,e,r);else if(YN(n))tD(n,e,r);else if(JN(n))rD(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function bt(){var r=XE(process.env);return Object.assign({},Wm,r)}function JE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function Wl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=JE(r.charCodeAt(n)),i=JE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var QE="1.25.1";var iD="deployment.environment";var aD="process.runtime.name";var sD="service.name";var lD="service.instance.id";var cD="telemetry.sdk.name",uD="telemetry.sdk.language",dD="telemetry.sdk.version";var ZE=iD;var eT=aD;var jl=sD;var tT=lD;var Ha=cD,Ga=uD,Va=dD;var mD="nodejs";var rT=mD;var pi,$l=(pi={},pi[Ha]="opentelemetry",pi[eT]="node",pi[Ga]=rT,pi[Va]=QE,pi);var pD=9,gD=6,hD=Math.pow(10,gD),fD=Math.pow(10,pD);function nT(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*hD);return[t,n]}function oT(r){return r[0]*fD+r[1]}function Wa(r){return r[0]*1e6+r[1]/1e3}var uo;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(uo||(uo={}));var iT=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 SD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},yD=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))},aT=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new iT}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,yD([this._that],SD(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 sr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(sr||(sr={}));var Mt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Mt||(Mt={}));var bD=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 mne=function(r){bD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function sT(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 lr;(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"})(lr||(lr={}));var lT=function(){function r(){this.kind=lr.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 se;(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"})(se||(se={}));var ED=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function TD(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 jm=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=TD(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=sT(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 $m=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=lr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new jm(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,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new jm(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new jm(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.HISTOGRAM,dataPoints:n.map(function(i){var a=ED(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var qm=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Km=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))},Ym=function(){function r(e,t,n,o){e===void 0&&(e=new vD),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 s=a%n;s<0&&(s+=n);for(var c=s;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 vD=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,Km([n,this._counts.length-t],qm(this._counts.slice(t)),!1)),o.splice.apply(o,Km([0,t],qm(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(Km([],qm(this._counts),!1))},r}();var cT=52,AD=2146435072,wD=1048575,Xm=1023,ql=-Xm+1,Kl=Xm,ja=Math.pow(2,-1022);function Yl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&AD)>>20;return n-Xm}function Xl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&wD)*Math.pow(2,32);return o+n}function $a(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function dT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var CD=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)}}(),xn=function(r){CD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var pT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<ja)return this._minNormalLowerBoundaryIndex();var t=Yl(e),n=this._rightShift(Xl(e)-1,cT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new xn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new xn("overflow: "+e+" is > maximum lower boundary: "+n);return $a(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=ql>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Kl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var gT=function(){function r(e){this._scale=e,this._scaleFactor=$a(Math.LOG2E,e),this._inverseFactor=$a(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=ja)return this._minNormalLowerBoundaryIndex()-1;if(Xl(e)===0){var t=Yl(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 xn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return ja;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new xn("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 ql<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Kl+1<<this._scale)-1},r}();var hT=-10,fT=20,RD=Array.from({length:31},function(r,e){return e>10?new gT(e-10):new pT(e-10)});function Jm(r){if(r>fT||r<hT)throw new xn("expected scale >= "+hT+" && <= "+fT+", got: "+r);return RD[r+10]}var xD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jl=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}(),MD=20,_D=160,Qm=2,PD=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=_D),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Ym),u===void 0&&(u=new Ym),d===void 0&&(d=Jm(MD)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<Qm&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Qm),this._maxSize=Qm)}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,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(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=dT(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},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=Jm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Jl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Jl.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 Jl(0,-1);var o=t-n;return new Jl(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var ST=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=lr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new PD(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:Mt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=xD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===se.GAUGE||e.type===se.UP_DOWN_COUNTER||e.type===se.OBSERVABLE_GAUGE||e.type===se.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();var ID=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Zm=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=nT(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var yT=function(){function r(){this.kind=lr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Zm(e)},r.prototype.merge=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=Wa(t.sampleTime)>=Wa(e.sampleTime)?t:e;return new Zm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.GAUGE,dataPoints:n.map(function(i){var a=ID(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var OD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},qa=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 ep=function(){function r(e){this.monotonic=e,this.kind=lr.SUM}return r.prototype.createAccumulation=function(e){return new qa(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new qa(t.startTime,this.monotonic,o,t.reset):new qa(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 qa(t.startTime,this.monotonic,o,!0):new qa(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Mt.SUM,dataPoints:n.map(function(i){var a=OD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var mo=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)}}(),Ur=function(){function r(){}return r.Drop=function(){return RT},r.Sum=function(){return xT},r.LastValue=function(){return MT},r.Histogram=function(){return _T},r.ExponentialHistogram=function(){return LD},r.Default=function(){return ND},r}();var bT=function(r){mo(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 lT,e}(Ur);var ET=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ep(!0),e.NON_MONOTONIC_INSTANCE=new ep(!1),e}(Ur);var TT=function(r){mo(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 yT,e}(Ur);var vT=function(r){mo(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 $m([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Ur);var AT=function(r){mo(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(s,c){return s-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 $m(this._boundaries,this._recordMinMax)},e}(Ur);var wT=function(r){mo(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 ST(this._maxSize,this._recordMinMax)},e}(Ur);var CT=function(r){mo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case se.COUNTER:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return xT;case se.GAUGE:case se.OBSERVABLE_GAUGE:return MT;case se.HISTOGRAM:return t.advice.explicitBucketBoundaries?new AT(t.advice.explicitBucketBoundaries):_T}return H.warn("Unable to recognize instrument type: "+t.type),RT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Ur);var RT=new bT,xT=new ET,MT=new TT,_T=new vT,LD=new wT,ND=new CT;Me();function Ql(){return"unknown_service:"+process.argv0}var Mn=function(){return Mn=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},Mn.apply(this,arguments)},DD=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},kD=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},UD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},tp=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[jl]=Ql(),e[Ga]=$l[Ga],e[Ha]=$l[Ha],e[Va]=$l[Va],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 DD(this,void 0,void 0,function(){return kD(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=Mn(Mn({},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 s,c=UD(a,2),l=c[0],u=c[1];return Mn(Mn(Mn(Mn({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var po;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(po||(po={}));Me();var FD=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},BD=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},rp=function(){return sr.CUMULATIVE},PT=function(r){switch(r){case se.COUNTER:case se.OBSERVABLE_COUNTER:case se.GAUGE:case se.HISTOGRAM:case se.OBSERVABLE_GAUGE:return sr.DELTA;case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:return sr.CUMULATIVE}},IT=function(r){switch(r){case se.COUNTER:case se.HISTOGRAM:return sr.DELTA;case se.GAUGE:case se.UP_DOWN_COUNTER:case se.OBSERVABLE_UP_DOWN_COUNTER:case se.OBSERVABLE_COUNTER:case se.OBSERVABLE_GAUGE:return sr.CUMULATIVE}};function zD(){var r=bt(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?rp:e==="delta"?PT:e==="lowmemory"?IT:(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."),rp)}function HD(r){return r!=null?r===po.DELTA?PT:r===po.LOWMEMORY?IT:rp:zD()}function GD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Ur.Default()}}var OT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=GD(t),this._aggregationTemporalitySelector=HD(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return FD(this,void 0,void 0,function(){return BD(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 VD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},LT=1e4,NT=5,DT=1e3,kT=5e3,UT=1.5;function Ka(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=VD(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 np(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function op(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 ip(r){return typeof r=="number"?r<=0?ap(r,LT):r:WD()}function WD(){var r,e=Number((r=bt().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:bt().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?ap(e,LT):e}function ap(r,e){return H.warn("Timeout must be greater than 0",r),e}function FT(r){var e=[429,502,503,504];return e.includes(r)}function BT(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 zT=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 aT(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=ip(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:uo.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:uo.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:uo.SUCCESS})}).catch(function(n){t({code:uo.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 sp from"url";import*as ec from"http";import*as tc from"https";import*as HT from"zlib";import{Readable as $D}from"stream";var _n;(function(r){r.NONE="none",r.GZIP="gzip"})(_n||(_n={}));var jD=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)}}(),gi=function(r){jD(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 Zl=function(){return Zl=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},Zl.apply(this,arguments)};function lp(r,e,t,n,o){var i=r.timeoutMillis,a=new sp.URL(r.url),s=Number(process.versions.node.split(".")[0]),c,l,u=!1,d=setTimeout(function(){if(clearTimeout(c),u=!0,l.destroyed){var h=new gi("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),m={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Zl({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?ec.request:tc.request,p=function(h,f){switch(h===void 0&&(h=NT),f===void 0&&(f=DT),l=g(m,function(b){var x="";b.on("data",function(v){return x+=v}),b.on("aborted",function(){if(u){var v=new gi("Request Timeout");o(v)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)H.debug("statusCode: "+b.statusCode,x),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&FT(b.statusCode)&&h>0){var v=void 0;f=UT*f,b.headers["retry-after"]?v=BT(b.headers["retry-after"]):v=Math.round(Math.random()*(kT-f)+f),c=setTimeout(function(){p(h-1,f)},v)}else{var A=new gi(b.statusMessage,b.statusCode,x);o(A),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new gi("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new gi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case _n.GZIP:{l.setHeader("Content-Encoding","gzip");var E=qD(e);E.on("error",o).pipe(HT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};p()}function qD(r){var e=new $D;return e.push(r),e.push(null),e}function cp(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 sp.URL(r.url),t=e.protocol==="http:"?ec.Agent:tc.Agent;return new t(Zl({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function up(r){if(r)return r;var e=bt().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||bt().OTEL_EXPORTER_OTLP_COMPRESSION;return e===_n.GZIP?_n.GZIP:_n.NONE}Me();var KD=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)}}(),rc=function(r){KD(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,Ka(t.headers),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=cp(t),i.compression=up(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,l){var u;lp(i,(u=i._serializer.serializeRequest(t))!==null&&u!==void 0?u:new Uint8Array,i._contentType,c,l)}).then(n,o);this._sendingPromises.push(a);var s=function(){var c=i._sendingPromises.indexOf(a);i._sendingPromises.splice(c,1)};a.then(s,s)},e.prototype.onShutdown=function(){},e}(zT);function VT(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function YD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function WT(r){var e=VT(r);return YD(e)}function XD(r){var e=VT(r);return e.toString()}var JD=typeof BigInt<"u"?XD:oT;function GT(r){return r}function jT(r){if(r!==void 0)return Wl(r)}var QD={encodeHrTime:WT,encodeSpanContext:Wl,encodeOptionalSpanContext:jT};function $T(r){var e,t;if(r===void 0)return QD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?WT:JD,encodeSpanContext:o?GT:Wl,encodeOptionalSpanContext:o?GT:jT}}var ZD=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function qT(r){return{name:r.name,version:r.version}}function hi(r){return Object.keys(r).map(function(e){return KT(e,r[e])})}function KT(r,e){return{key:r,value:YT(e)}}function YT(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(YT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=ZD(t,2),o=n[0],i=n[1];return KT(o,i)})}}:{}}function XT(r){return{attributes:hi(r.attributes),droppedAttributesCount:0}}Me();function QT(r,e){var t=$T(e);return{resource:XT(r.resource),schemaUrl:void 0,scopeMetrics:ek(r.scopeMetrics,t)}}function ek(r,e){return Array.from(r.map(function(t){return{scope:qT(t.scope),metrics:t.metrics.map(function(n){return tk(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function tk(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=ik(r.aggregationTemporality);switch(r.dataPointType){case Mt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:JT(r,e)};break;case Mt.GAUGE:t.gauge={dataPoints:JT(r,e)};break;case Mt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:nk(r,e)};break;case Mt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:ok(r,e)};break}return t}function rk(r,e,t){var n={attributes:hi(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case jt.INT:n.asInt=r.value;break;case jt.DOUBLE:n.asDouble=r.value;break}return n}function JT(r,e){return r.dataPoints.map(function(t){return rk(t,r.descriptor.valueType,e)})}function nk(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ok(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:hi(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 ik(r){switch(r){case sr.DELTA:return 1;case sr.CUMULATIVE:return 2}}function ZT(r,e){return{resourceMetrics:r.map(function(t){return QT(t,e)})}}var dp={serializeRequest:function(r){var e=ZT(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 ev="0.52.1";var tv=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)}}(),fi=function(){return fi=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},fi.apply(this,arguments)},rv="v1/metrics",ak="http://localhost:4318/"+rv,sk={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+ev},lk=function(r){tv(e,r);function e(t){var n=r.call(this,t,dp,"application/json")||this;return n.headers=fi(fi(fi(fi({},n.headers),sk),mi.parseKeyPairsIntoRecord(bt().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),Ka(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?op(bt().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):bt().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?np(bt().OTEL_EXPORTER_OTLP_ENDPOINT,rv):ak},e}(rc),nv=function(r){tv(e,r);function e(t){return r.call(this,new lk(t),t)||this}return e}(OT);var Si;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(Si||(Si={}));var Fr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Fr||(Fr={}));Me();var ck=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)}}(),ov=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},iv=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},uk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},dk=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))},mk=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 av(r){return r!=null}function nc(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function sv(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var mp=function(r){ck(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Pn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new mp("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function lv(r){return ov(this,void 0,void 0,function(){var e=this;return iv(this,function(t){return[2,Promise.all(r.map(function(n){return ov(e,void 0,void 0,function(){var o,i;return iv(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 cv(r){return r.status==="rejected"}function pp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,dk([],uk(e(n)),!1))}),t}function uv(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=mk(r),i=o.next();!i.done;i=o.next()){var a=i.value;if(!e.has(a))return!1}}catch(s){t={error:s}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0}function dv(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 mv(r,e){return r.toLowerCase()===e.toLowerCase()}Me();var cr;(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"})(cr||(cr={}));var gp=function(){function r(){this.kind=cr.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 he;(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"})(he||(he={}));function Br(r,e,t){var n,o,i,a;return gk(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:jt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function pv(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 gv(r,e){return mv(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var pk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function gk(r){return r.match(pk)!=null}var hk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i};function fk(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 oc=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=fk(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=dv(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 ic=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=cr.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new oc(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,s=new Array(i.length),c=0;c<i.length;c++)s[c]=i[c]+a[c];var l=1/0,u=-1/0;return this._recordMinMax&&(n.hasMinMax&&o.hasMinMax?(l=Math.min(n.min,o.min),u=Math.max(n.max,o.max)):n.hasMinMax?(l=n.min,u=n.max):o.hasMinMax&&(l=o.min,u=o.max)),new oc(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},r.prototype.diff=function(e,t){for(var n=e.toPointValue(),o=t.toPointValue(),i=n.buckets.counts,a=o.buckets.counts,s=new Array(i.length),c=0;c<i.length;c++)s[c]=a[c]-i[c];return new oc(t.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:o.count-n.count,sum:o.sum-n.sum,hasMinMax:!1,min:1/0,max:-1/0})},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.HISTOGRAM,dataPoints:n.map(function(i){var a=hk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,buckets:l.buckets,count:l.count}}})}},r}();Me();var hp=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},fp=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))},Sp=function(){function r(e,t,n,o){e===void 0&&(e=new Sk),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 s=a%n;s<0&&(s+=n);for(var c=s;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 Sk=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,fp([n,this._counts.length-t],hp(this._counts.slice(t)),!1)),o.splice.apply(o,fp([0,t],hp(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(fp([],hp(this._counts),!1))},r}();var hv=52,yk=2146435072,bk=1048575,yp=1023,ac=-yp+1,sc=yp,Ya=Math.pow(2,-1022);function lc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&yk)>>20;return n-yp}function cc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&bk)*Math.pow(2,32);return o+n}function Xa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function Sv(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var Ek=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)}}(),In=function(r){Ek(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var bv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ya)return this._minNormalLowerBoundaryIndex();var t=lc(e),n=this._rightShift(cc(e)-1,hv);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new In("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new In("overflow: "+e+" is > maximum lower boundary: "+n);return Xa(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=ac>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return sc>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var Ev=function(){function r(e){this._scale=e,this._scaleFactor=Xa(Math.LOG2E,e),this._inverseFactor=Xa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ya)return this._minNormalLowerBoundaryIndex()-1;if(cc(e)===0){var t=lc(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 In("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ya;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new In("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 ac<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(sc+1<<this._scale)-1},r}();var Tv=-10,vv=20,Tk=Array.from({length:31},function(r,e){return e>10?new Ev(e-10):new bv(e-10)});function bp(r){if(r>vv||r<Tv)throw new In("expected scale >= "+Tv+" && <= "+vv+", got: "+r);return Tk[r+10]}var vk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},uc=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}(),Ak=20,wk=160,Ep=2,Av=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=wk),n===void 0&&(n=!0),o===void 0&&(o=0),i===void 0&&(i=0),a===void 0&&(a=0),s===void 0&&(s=Number.POSITIVE_INFINITY),c===void 0&&(c=Number.NEGATIVE_INFINITY),l===void 0&&(l=new Sp),u===void 0&&(u=new Sp),d===void 0&&(d=bp(Ak)),this.startTime=e,this._maxSize=t,this._recordMinMax=n,this._sum=o,this._count=i,this._zeroCount=a,this._min=s,this._max=c,this._positive=l,this._negative=u,this._mapping=d,this._maxSize<Ep&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Ep),this._maxSize=Ep)}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,s=0;if(e.length===0?(e.indexStart=o,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):o<e.indexStart&&e.indexEnd-o>=this._maxSize?(i=!0,s=o,a=e.indexEnd):o>e.indexEnd&&o-e.indexStart>=this._maxSize&&(i=!0,s=e.indexStart,a=o),i){var c=this._changeScale(a,s);this._downscale(c),o=this._mapping.mapToIndex(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=Sv(t);a>this._maxSize&&(a=this._maxSize);var s=a-o;e.backing.growTo(a,i,s)},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=bp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=uc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=uc.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 uc(0,-1);var o=t-n;return new uc(e.indexStart>>o,e.indexEnd>>o)},r.prototype._mergeBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++)this._incrementIndexBy(e,i+s>>a,n.at(s))},r.prototype._diffBuckets=function(e,t,n,o){for(var i=n.offset,a=t.scale-o,s=0;s<n.length;s++){var c=i+s>>a,l=c-e.indexBase;l<0&&(l+=e.backing.length),e.decrementBucket(l,n.at(s))}e.trim()},r}();var Tp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=cr.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Av(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:Fr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=vk(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===he.GAUGE||e.type===he.UP_DOWN_COUNTER||e.type===he.OBSERVABLE_GAUGE||e.type===he.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:s,startTime:c.startTime,endTime:o,value:{min:l.hasMinMax?l.min:void 0,max:l.hasMinMax?l.max:void 0,sum:u?void 0:l.sum,positive:{offset:l.positive.offset,bucketCounts:l.positive.bucketCounts},negative:{offset:l.negative.offset,bucketCounts:l.negative.bucketCounts},count:l.count,scale:l.scale,zeroCount:l.zeroCount}}})}},r}();Me();var Ck=Om("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function wv(r){return r.setValue(Ck,!0)}Me();function Cv(){return function(r){H.error(Rk(r))}}function Rk(r){return typeof r=="string"?r:JSON.stringify(xk(r))}function xk(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 Mk=Cv();function dc(r){try{Mk(r)}catch{}}var Rv="1.30.1";var _k="process.runtime.name";var Pk="service.name";var Ik="telemetry.sdk.name",Ok="telemetry.sdk.language",Lk="telemetry.sdk.version";var xv=_k;var Mv=Pk;var Ja=Ik,Qa=Ok,Za=Lk;var Nk="nodejs";var _v=Nk;var yi,go=(yi={},yi[Ja]="opentelemetry",yi[xv]="node",yi[Qa]=_v,yi[Za]=Rv,yi);function es(r){r.unref()}var Hk=9,Gk=6,Vk=Math.pow(10,Gk),fae=Math.pow(10,Hk);function ho(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*Vk);return[t,n]}function bi(r){return r[0]*1e6+r[1]/1e3}var ts;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(ts||(ts={}));Me();function Pv(r,e){return new Promise(function(t){di.with(wv(di.active()),function(){r.export(e,function(n){t(n)})})})}var Iv={_export:Pv};var Wk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},mc=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=ho(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var vp=function(){function r(){this.kind=cr.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new mc(e)},r.prototype.merge=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=bi(t.sampleTime)>=bi(e.sampleTime)?t:e;return new mc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.GAUGE,dataPoints:n.map(function(i){var a=Wk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var jk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Ei=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 pc=function(){function r(e){this.monotonic=e,this.kind=cr.SUM}return r.prototype.createAccumulation=function(e){return new Ei(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ei(t.startTime,this.monotonic,o,t.reset):new Ei(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 Ei(t.startTime,this.monotonic,o,!0):new Ei(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Fr.SUM,dataPoints:n.map(function(i){var a=jk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var fo=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)}}(),ur=function(){function r(){}return r.Drop=function(){return Fv},r.Sum=function(){return Bv},r.LastValue=function(){return zv},r.Histogram=function(){return Hv},r.ExponentialHistogram=function(){return $k},r.Default=function(){return qk},r}();var Ov=function(r){fo(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 gp,e}(ur);var Lv=function(r){fo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case he.COUNTER:case he.OBSERVABLE_COUNTER:case he.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new pc(!0),e.NON_MONOTONIC_INSTANCE=new pc(!1),e}(ur);var Nv=function(r){fo(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 vp,e}(ur);var Dv=function(r){fo(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 ic([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ur);var rs=function(r){fo(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(s,c){return s-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 ic(this._boundaries,this._recordMinMax)},e}(ur);var kv=function(r){fo(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 Tp(this._maxSize,this._recordMinMax)},e}(ur);var Uv=function(r){fo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case he.COUNTER:case he.UP_DOWN_COUNTER:case he.OBSERVABLE_COUNTER:case he.OBSERVABLE_UP_DOWN_COUNTER:return Bv;case he.GAUGE:case he.OBSERVABLE_GAUGE:return zv;case he.HISTOGRAM:return t.advice.explicitBucketBoundaries?new rs(t.advice.explicitBucketBoundaries):Hv}return H.warn("Unable to recognize instrument type: "+t.type),Fv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ur);var Fv=new Ov,Bv=new Lv,zv=new Nv,Hv=new Dv,$k=new kv,qk=new Uv;var Gv=function(r){return ur.Default()},Vv=function(r){return Si.CUMULATIVE};var Ap=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},wp=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Wv=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Kk=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))},jv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:Gv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:Vv,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 Ap(this,void 0,void 0,function(){var t,n,o,i,a,s;return wp(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(Kk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],Wv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=Wv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(pp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(pp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return Ap(this,void 0,void 0,function(){return wp(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,Pn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();Me();var Yk=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)}}(),gc=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},hc=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Xk=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Jk=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))},Cp=function(r){Yk(e,r);function e(t){var n,o,i,a,s=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 s._exportInterval=(i=t.exportIntervalMillis)!==null&&i!==void 0?i:6e4,s._exportTimeout=(a=t.exportTimeoutMillis)!==null&&a!==void 0?a:3e4,s._exporter=t.exporter,s}return e.prototype._runOnce=function(){return gc(this,void 0,void 0,function(){var t;return hc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Pn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof mp?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(dc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return gc(this,void 0,void 0,function(){var o,i,a,s,c,l;return hc(this,function(u){switch(u.label){case 0:return[4,this.collect({timeoutMillis:this._exportTimeout})];case 1:if(o=u.sent(),i=o.resourceMetrics,a=o.errors,a.length>0&&(l=H).error.apply(l,Jk(["PeriodicExportingMetricReader: metrics collection errors"],Xk(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 s=u.sent(),H.debug("Error while resolving async portion of resource: ",s),dc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,Iv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==ts.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),es(this._interval)},e.prototype.onForceFlush=function(){return gc(this,void 0,void 0,function(){return hc(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 gc(this,void 0,void 0,function(){return hc(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}(jv);Me();Me();function fc(){return"unknown_service:"+process.argv0}var On=function(){return On=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},On.apply(this,arguments)},Qk=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Zk=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},e0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Sc=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[Mv]=fc(),e[Qa]=go[Qa],e[Ja]=go[Ja],e[Za]=go[Za],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 Qk(this,void 0,void 0,function(){return Zk(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=On(On({},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 s,c=e0(a,2),l=c[0],u=c[1];return On(On(On(On({},t._syncAttributes),l),(s=e._syncAttributes)!==null&&s!==void 0?s:e.attributes),u)});return new r(o,i)},r.EMPTY=new r({}),r}();var $v=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 So=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)}}(),yc=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=di.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===jt.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,ho(Date.now()))},r}();var qv=function(r){So(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}(yc);var Kv=function(r){So(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}(yc);var Yv=function(r){So(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}(yc);var Xv=function(r){So(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}(yc);var bc=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 Jv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Qv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);var Zv=function(r){So(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(bc);function ns(r){return r instanceof bc}var eA=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=Br(e,he.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new Yv(o,n)},r.prototype.createHistogram=function(e,t){var n=Br(e,he.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new Xv(o,n)},r.prototype.createCounter=function(e,t){var n=Br(e,he.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Kv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=Br(e,he.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new qv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=Br(e,he.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Qv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=Br(e,he.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Jv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=Br(e,he.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Zv(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 Ec=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=Br(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var t0=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)}}(),tA=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},r0=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 tA(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 tA(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 Tr=function(r){t0(e,r);function e(){return r.call(this,nc)||this}return e}(r0);var n0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},Tc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new Tr,this._cumulativeMemoStorage=new Tr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=nc(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 s=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,function(){return i._aggregator.createAccumulation(o)});s?.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=n0(o,3),a=i[0],s=i[1],c=i[2],l=n._aggregator.createAccumulation(t);l?.record(s);var u=l;if(n._cumulativeMemoStorage.has(a,c)){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}else if(n._cumulativeMemoStorage.size>=n._cardinalityLimit&&(a=n._overflowAttributes,c=n._overflowHashCode,n._cumulativeMemoStorage.has(a,c))){var d=n._cumulativeMemoStorage.get(a,c);u=n._aggregator.diff(d,l)}if(n._activeCollectionStorage.has(a,c)){var m=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(m,u)}n._cumulativeMemoStorage.set(a,l,c),n._activeCollectionStorage.set(a,u,c)})},r.prototype.collect=function(){var e=this._activeCollectionStorage;return this._activeCollectionStorage=new Tr,e},r}();var Rp=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.")},rA=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},vc=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,s;if(this._reportHistory.has(e)){var c=this._reportHistory.get(e),l=c.collectionTime;s=c.aggregationTemporality,s===Si.CUMULATIVE?a=r.merge(c.accumulations,i,this._aggregator):a=r.calibrateStartTime(c.accumulations,i,l)}else s=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:a,collectionTime:o,aggregationTemporality:s});var u=o0(a);if(u.length!==0)return this._aggregator.toMetricData(t,s,u,o)},r.prototype._stashAccumulations=function(e){var t,n,o=this._unreportedAccumulations.keys();try{for(var i=Rp(o),a=i.next();!a.done;a=i.next()){var s=a.value,c=this._unreportedAccumulations.get(s);c===void 0&&(c=[],this._unreportedAccumulations.set(s,c)),c.push(e)}}catch(l){t={error:l}}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 Tr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=Rp(i),s=a.next();!s.done;s=a.next()){var c=s.value;o=r.merge(o,c,this._aggregator)}}catch(l){t={error:l}}finally{try{s&&!s.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 s=rA(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),m=n.merge(d,l);o.set(c,m,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=Rp(e.keys()),s=a.next();!s.done;s=a.next()){var c=rA(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(m){o={error:m}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function o0(r){return Array.from(r.entries())}var i0=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)}}(),a0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},nA=function(r){i0(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Tc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new vc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Tr;Array.from(t.entries()).forEach(function(a){var s=a0(a,2),c=s[0],l=s[1];i.set(o._attributesProcessor.process(c),l)}),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}(Ec);Me();function xp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
28
28
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
29
29
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
30
30
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
@@ -36,11 +36,11 @@ ${this.decisions.map(e=>e.toString()).join(`
|
|
|
36
36
|
To resolve the conflict:`,Mp(l,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.
|
|
37
37
|
`,`Details:
|
|
38
38
|
`,xp(l,e),`To resolve the conflict:
|
|
39
|
-
`,Mp(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var iA=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 aA=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Tr}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===jt.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 sA=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!ns(e)){var o=this._buffer.get(e);if(o==null&&(o=new Tr,this._buffer.set(e,o)),typeof t!="number"){H.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===jt.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 Pp=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Ip=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},lA=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},cA=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))},uA=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(ns));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(ns)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Pp(this,void 0,void 0,function(){var n,o,i,a;return Ip(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,lv(cA(cA([],lA(n),!1),lA(o),!1))];case 1:return i=s.sent(),a=i.filter(cv).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 Pp(n,void 0,void 0,function(){var s,c;return Ip(this,function(l){switch(l.label){case 0:return s=new aA(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),t!=null&&(c=Pn(c,t)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._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 Pp(n,void 0,void 0,function(){var s,c;return Ip(this,function(l){switch(l.label){case 0:return s=new sA,c=Promise.resolve(i(s)),t!=null&&(c=Pn(c,t)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(m){m.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&&uv(n.instruments,t)})},r}();var d0=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)}}(),dA=function(r){d0(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Tc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new vc(n,i),s}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}(Ec);var mA=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)}}(),Ti=function(){function r(){}return r.Noop=function(){return p0},r}();var m0=function(r){mA(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Ti);var pA=function(r){mA(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}(Ti);var p0=new m0;var g0=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},h0=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gA=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new oA,this.observableRegistry=new uA,this.meter=new eA(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,dA);return t.length===1?t[0]:new iA(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,nA);return t},r.prototype.collect=function(e,t,n){return g0(this,void 0,void 0,function(){var o,i,a;return h0(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(av),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 l=pv(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),m=new t(l,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(m),m});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),s=a.map(function(c){var l=f0(c,2),u=l[0],d=l[1],m=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(m!=null)return m;var g=d.createAggregator(e),p=u.selectCardinalityLimit(e.type),h=new t(e,g,Ti.Noop(),[u],p);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var S0=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.")},hA=function(){function r(e){this.resource=e,this.viewRegistry=new $v,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=sv(e),n=this.meterSharedStates.get(t);return n==null&&(n=new gA(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=S0(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.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 Ac=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},wc=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},y0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},b0=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))},fA=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Ac(this,void 0,void 0,function(){var t,n,o,i,a=this;return wc(this,function(s){switch(s.label){case 0:return t=ho(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Ac(a,void 0,void 0,function(){var l;return wc(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,b0([],y0(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Ac(this,void 0,void 0,function(){return wc(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 Ac(this,void 0,void 0,function(){return wc(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 SA=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},yA=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},bA=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 E0(r,e){var t=e??Sc.empty();return r?Sc.default().merge(t):t}var Op=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new hA(E0((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=bA(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=bA(e.readers),d=u.next();!d.done;d=u.next()){var m=d.value;this.addMetricReader(m)}}catch(g){o={error:g}}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"),Um()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new fA(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return SA(this,void 0,void 0,function(){return yA(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 SA(this,void 0,void 0,function(){return yA(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 T0=/[\^$\\.+?()[\]{}|]/g,Cc=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(T0,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var vi=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 EA=function(){function r(e){var t;this._nameFilter=new Cc((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new vi(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 TA=function(){function r(e){this._nameFilter=new vi(e?.name),this._versionFilter=new vi(e?.version),this._schemaUrlFilter=new vi(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 v0(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Rc=function(){function r(e){var t;if(v0(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Cc.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 pA(e.attributeKeys):this.attributesProcessor=Ti.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:ur.Default(),this.instrumentSelector=new EA({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new TA({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Xle=process.env.APP||"unknown";Me();import{v4 as A0}from"uuid";function w0(){return new nv({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:po.DELTA})}var C0=[new Rc({instrumentName:"test_event_duration",instrumentType:he.HISTOGRAM,aggregation:new rs([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new Rc({instrumentName:"test_step_duration",instrumentType:he.HISTOGRAM,aggregation:new rs([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],Mc=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 tp({[jl]:e.serviceName,[ZE]:t,[tT]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:A0()}),o=w0(),i=new Cp({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Op({resource:n,readers:[i],views:C0}),Hl.setGlobalMeterProvider(this.provider),this.meter=Hl.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Fl(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=Fl(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 Et=new Ul;function vA(r){r.disabled||(Et=new Mc(r))}import{hostname as M0}from"os";import _0 from"path";import{_android as P0}from"playwright";async function AA(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i,orgId:a,sessionId:s}=r,{token:c,webRtcUrl:l,adbUrl:u,name:d,apkDownloadUrl:m,region:g,playwrightServerUrl:p}=await e.createAndroidEmulator({...n,hostname:M0(),sessionId:s}),h;try{x0("adb --version"),h="adb"}catch{if(process.env.ANDROID_HOME)h=_0.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("The adb binary was not found in PATH and ANDROID_HOME is not set either")}t.info({emulatorName:d,apkToInstall:n.apkToInstall,region:g,apkDownloadUrl:m,sessionId:s,playwrightServerUrl:p},"Android instance creation ok");let f=await Et.recordDuration({fn:async()=>await R0({adbUrl:u,endpointUrl:l,token:c,logLevel:i,adbPath:h}),name:"test_event_duration",tags:["name:limbar-client-creation",`orgId:${a}`]}),E=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];m&&E.push(m);let b=n.apkToInstall?.channel,x=n.apkToInstall?.tag;o(`Installing APK${b?` with channel ${b}`:""}${x?` and tag ${x}`:""}`),await Promise.all(E.map(w=>f.sendAsset(w))),o("Starting ADB tunnel");let v=await Et.recordDuration({fn:async()=>await f.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]}),A=()=>{v.close(),f.disconnect()},_;return p&&(o("Opening Playwright connection"),_=await Et.recordDuration({fn:async()=>await P0.connect(p),name:"test_event_duration",tags:["name:playwright-device-connect",`orgId:${a}`]})),{adbPort:v.address.port,close:A,limbarToken:c,limbarUrl:l,emulatorName:d,playwrightDevice:_,client:f}}async function _c({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a,orgId:s,sessionId:c}){let l=Date.now(),u=[],d;if("avdId"in e)d=e;else{d=await AA({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r,orgId:s,sessionId:c});let p=d.emulatorName;u.push(()=>t.deleteAndroidEmulator(p),d.close)}let m=async()=>{for(let p=u.length-1;p>=0;p-=1)try{await u[p]()}catch(h){if(h instanceof Error&&h.message.includes("ECONNREFUSED"))return;n.warn({err:h},"Error running cleanup task")}},g=async()=>{if(a&&!a.connected)throw await m(),new Error("Client disconnected before Appium driver could be started")};await g();try{let p=await U0({logger:n,driverLogLevel:o,appiumPort:i,emulatorStart:l,emulatorCreationParams:d,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:s,sessionId:c});return u.push(p.appiumClose),u.push(async()=>p.driver.deleteSession()),await g(),{...d,...p,cleanup:m,appiumPort:i}}catch(p){throw await m(),new Error(`Failed to start Appium driver: ${p}`)}}async function U0({logger:r,driverLogLevel:e="warn",emulatorStart:t,appiumPort:n,emulatorCreationParams:o,onStatusUpdate:i,creationOpts:a}){let s=[],{adbPort:c,emulatorName:l}=o,u;if(!c){let v=0;for(;v<30;){let A=5560+Math.floor(Math.random()*100);if(A%2!==0&&(A=Math.min(A+1,5658)),await kl(A)&&await kl(A+1)){u=A,c=A+1;break}v+=1}if(!c)throw new Error(`Failed to find an available ADB port after ${v} attempts`)}l||(l=`emulator-${u}`,s.push(async()=>{let v=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{O0(`${v} -s ${l} emu kill`,{stdio:"inherit"})}catch(A){r.warn({err:A,emulatorName:l},"Failed to kill emulator")}}));let d=Date.now(),{close:m,logFile:g}=await F0({logger:r,logLevel:e,appiumPort:n}),p={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${c}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0,"appium:ensureWebviewsHavePages":!0},h={hostname:"localhost",port:n,logLevel:e,capabilities:p,connectionRetryTimeout:15e3,connectionRetryCount:2};"avdId"in o&&(p["appium:avd"]=o.avdId,p["appium:avdLaunchTimeout"]=18e4,p["appium:avdReadyTimeout"]=18e4,p["appium:skipDeviceInitialization"]=!1,p["appium:skipServerInstallation"]=!1,p["appium:udid"]=void 0,p["appium:avdArgs"]=`-port ${u} -no-snapshot-save -no-boot-anim -noaudio`,h.connectionRetryTimeout=12e4,h.connectionRetryCount=3);let f=Date.now(),E;try{E=await k0(h)}catch(v){throw i(`Emulator creation failed: ${v}`),await Promise.all(s.map(A=>A())),v}if(await E.updateSettings({enableMultiWindows:!0}),"avdId"in a){let v=a.apkFilePath?.trim();if(v){let A=D0.resolve(v);if(!L0.existsSync(A))throw new Error(`APK not found at path: ${A}`);i("Installing local APK...");let _=Date.now();try{await E.installApp(A),r.info({apkFilePath:A,installDurationMs:Date.now()-_},"Installed local APK")}catch(w){throw r.error({err:w,apkFilePath:A},"Failed to install local APK"),new Error(`Failed to install APK from ${A}: ${w.message}`)}}}let b=new Map;return E.on("command",v=>{b.set(v.command,Date.now())}),E.on("result",v=>{let A=b.get(v.command);if(!A)return;let _=Date.now()-A;v.result instanceof Error?r.warn({err:v.result,command:v.command,args:v.body,durationMs:_},"Appium cmd failed"):_>1e4&&r.warn({command:v.command,args:v.body,durationMs:_},"Appium cmd took very long"),b.delete(v.command)}),r.info({timings:{emulatorDuration:d-t,appiumDuration:f-d,wdioDuration:Date.now()-f},capabilities:p,emulatorName:l},"Started Appium driver"),{driver:E,appiumClose:async()=>{await m(),await Promise.all(s.map(v=>v()))},appiumPort:n,appiumLogFile:g,emulatorName:l,adbPort:c}}async function F0({logger:r,logLevel:e,appiumPort:t}){let n=`${N0()}/appium-port-${Date.now()}.log`,o=await I0.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e,logFile:n});return{logFile:n,close:async()=>{await o.close()}}}import wA from"crypto";import B0 from"fs";async function Pc({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await B0.promises.readFile(t),a=wA.createHash("md5").update(i).digest("base64"),s=wA.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===s)){o.info({channel:e,tag:r,md5:a,md5Hex:s},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let l=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(l.status!==200)throw new Error(`Got error response from emulator platform: ${l.status} ${await l.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(l){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:l},"Failed to upload asset"),l}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as CA}from"child_process";import{existsSync as z0}from"fs";import{platform as RA}from"os";import{dirname as H0,join as G0,resolve as V0}from"path";import{fileURLToPath as W0}from"url";var xA,j0=W0(import.meta.url),$0=H0(j0);xA=V0($0,"..");var os=xA;C.info(`Setting APPIUM_HOME to ${os}`);process.env.APPIUM_HOME=os;var q0="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",K0="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",Y0="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",MA="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",_A="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function X0(){if(!process.env.JAVA_HOME)C.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&C.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>G0(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");z0(e)||C.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{CA("java --version",{stdio:"pipe",encoding:"utf-8"})||(C.error(`Could not find a Java installation. ${q0}`),process.exit(1))}catch(r){C.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function J0(){process.env.ANDROID_HOME||(C.error(`The ANDROID_HOME environment variable is not set. ${Y0} ${RA()==="darwin"?MA:_A}`),process.exit(1))}function Q0(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{CA(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(C.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${K0} Finally, ensure that the 'adb' command is available in your shell. ${RA()==="darwin"?MA:_A}`),process.exit(1))}catch(e){C.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function PA(){X0(),J0(),Q0()}import{create as Z0,windowedFiniteBatchScheduler as eU}from"@yornaath/batshit";import tU from"ws";var rU=100,nU=2500,IA=4e3,oU="\u2026";async function Ic({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=Z0({fetcher:async l=>{e(l)},resolver:()=>{},scheduler:eU({windowMs:nU,maxBatchSize:rU})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,s=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new tU(s);return c.on("message",l=>{let u=l.toString().trim();u.length!==0&&(u.length>IA&&(u=u.slice(0,IA)+oU),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}try{t.next()}catch{}}}import{Server as G1}from"socket.io";import f1 from"path";import{randomUUID as hU}from"crypto";import{faker as iU}from"@faker-js/faker";import aU from"assert";import sU from"axios";import*as lU from"child_process";import cU from"moment";import*as uU from"otpauth";import dU from"pg";async function OA(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=cl(n,e);t.push(...o)}),t}function mU(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 pU(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 gU=Object.getPrototypeOf(async function(){}).constructor;async function LA(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(x,v)=>{o[x]=v,l[x]=v},d={},m=(x,v)=>{o[x]=v,d[x]=v},g;n.includes("Octokit")&&(g=(await import("@octokit/rest")).Octokit);let p;n.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new gU("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(sU,cU,c.fakerInstance??iU,aU,dU,g,p,uU,lU,OA,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:m,v=>c.sms.send(v),v=>c.sms.fetchLatest(v),c.email,c.sms,c.ai,mU(a,s),...Object.values(i??{}))),f=!0,E,b;try{let x=await k(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await pU(e.options.responseSerialization??"RAW",x)}catch(x){t.error({err:x,env:o,evalCode:n},`[${r}] Error executing code: ${x}`),f=!1,x instanceof Rn?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=x instanceof Error?x.message:`${x}`}return{result:E,variableUpdates:l,persistentVariableUpdates:d,success:f,error:b}}async function NA({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=vn,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=hU(),m=await LA(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return C.debug(`[${d}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as fU,randomUUID as SU}from"crypto";import yU from"fetch-retry";var bU=yU(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}}),DA=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,kA=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function UA({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=vn,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!DA)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,g,p=0;if(!kA)throw new Error("Missing lambda auth secret.");let h=fU("sha256",kA).update(r).digest("hex");for(;p<=i;){p++,a?.throwIfAborted();let E={id:SU(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(m=await k(bU(DA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!m)throw new Error("Got empty response from code evaluation server");if(!m.ok)throw new Error(`Code evaluation server returned error code ${m.status}`);g=void 0;break}catch(b){g=b}}if(g)throw s.error({err:g},"Failed to evaluate code remotely"),g;if(!m)throw new Error(`An unexpected code evaluation error occurred${g?`: ${g}`:""}`);let f;try{f=Fy.parse(await m.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 zr(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await UA(r);else if(r.localTools)e=await NA({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
39
|
+
`,Mp(l,e))}}catch(u){n={error:u}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(n)throw n.error}}return i},r}();var iA=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 aA=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Tr}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===jt.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 sA=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!ns(e)){var o=this._buffer.get(e);if(o==null&&(o=new Tr,this._buffer.set(e,o)),typeof t!="number"){H.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===jt.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 Pp=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},Ip=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},lA=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},cA=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))},uA=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(ns));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(ns)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return Pp(this,void 0,void 0,function(){var n,o,i,a;return Ip(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,lv(cA(cA([],lA(n),!1),lA(o),!1))];case 1:return i=s.sent(),a=i.filter(cv).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 Pp(n,void 0,void 0,function(){var s,c;return Ip(this,function(l){switch(l.label){case 0:return s=new aA(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),t!=null&&(c=Pn(c,t)),[4,c];case 1:return l.sent(),a._metricStorages.forEach(function(u){u.record(s._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 Pp(n,void 0,void 0,function(){var s,c;return Ip(this,function(l){switch(l.label){case 0:return s=new sA,c=Promise.resolve(i(s)),t!=null&&(c=Pn(c,t)),[4,c];case 1:return l.sent(),a.forEach(function(u){var d=s._buffer.get(u);d!=null&&u._metricStorages.forEach(function(m){m.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&&uv(n.instruments,t)})},r}();var d0=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)}}(),dA=function(r){d0(e,r);function e(t,n,o,i,a){var s=r.call(this,t)||this;return s._attributesProcessor=o,s._aggregationCardinalityLimit=a,s._deltaMetricStorage=new Tc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new vc(n,i),s}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}(Ec);var mA=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)}}(),Ti=function(){function r(){}return r.Noop=function(){return p0},r}();var m0=function(r){mA(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(Ti);var pA=function(r){mA(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}(Ti);var p0=new m0;var g0=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},h0=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},gA=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new oA,this.observableRegistry=new uA,this.meter=new eA(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,dA);return t.length===1?t[0]:new iA(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,nA);return t},r.prototype.collect=function(e,t,n){return g0(this,void 0,void 0,function(){var o,i,a;return h0(this,function(s){switch(s.label){case 0:return[4,this.observableRegistry.observe(t,n?.timeoutMillis)];case 1:return o=s.sent(),i=this.metricStorageRegistry.getStorages(e),i.length===0?[2,null]:(a=i.map(function(c){return c.collect(e,t)}).filter(av),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 l=pv(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),m=new t(l,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(m),m});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),s=a.map(function(c){var l=f0(c,2),u=l[0],d=l[1],m=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(m!=null)return m;var g=d.createAggregator(e),p=u.selectCardinalityLimit(e.type),h=new t(e,g,Ti.Noop(),[u],p);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var S0=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.")},hA=function(){function r(e){this.resource=e,this.viewRegistry=new $v,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=sv(e),n=this.meterSharedStates.get(t);return n==null&&(n=new gA(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=S0(this.metricCollectors),a=i.next();!a.done;a=i.next()){var s=a.value;o.push([s,s.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 Ac=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},wc=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},y0=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(s){a={error:s}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return i},b0=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))},fA=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return Ac(this,void 0,void 0,function(){var t,n,o,i,a=this;return wc(this,function(s){switch(s.label){case 0:return t=ho(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return Ac(a,void 0,void 0,function(){var l;return wc(this,function(u){switch(u.label){case 0:return[4,c.collect(this,t,e)];case 1:return l=u.sent(),l?.scopeMetrics!=null&&n.push(l.scopeMetrics),l?.errors!=null&&o.push.apply(o,b0([],y0(l.errors),!1)),[2]}})})}),[4,Promise.all(i)];case 1:return s.sent(),[2,{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}]}})})},r.prototype.forceFlush=function(e){return Ac(this,void 0,void 0,function(){return wc(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 Ac(this,void 0,void 0,function(){return wc(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 SA=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 s(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):o(u.value).then(s,c)}l((n=n.apply(r,e||[])).next())})},yA=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:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function s(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,o&&(i=l[0]&2?o.return:l[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,l[1])).done)return i;switch(o=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,o=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){t.label=l[1];break}if(l[0]===6&&t.label<i[1]){t.label=i[1],i=l;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(l);break}i[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],o=0}finally{n=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},bA=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 E0(r,e){var t=e??Sc.empty();return r?Sc.default().merge(t):t}var Op=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new hA(E0((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=bA(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}if(e?.readers!=null&&e.readers.length>0)try{for(var u=bA(e.readers),d=u.next();!d.done;d=u.next()){var m=d.value;this.addMetricReader(m)}}catch(g){o={error:g}}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"),Um()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new fA(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return SA(this,void 0,void 0,function(){return yA(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 SA(this,void 0,void 0,function(){return yA(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 T0=/[\^$\\.+?()[\]{}|]/g,Cc=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(T0,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var vi=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 EA=function(){function r(e){var t;this._nameFilter=new Cc((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new vi(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 TA=function(){function r(e){this._nameFilter=new vi(e?.name),this._versionFilter=new vi(e?.version),this._schemaUrlFilter=new vi(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 v0(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var Rc=function(){function r(e){var t;if(v0(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Cc.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 pA(e.attributeKeys):this.attributesProcessor=Ti.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:ur.Default(),this.instrumentSelector=new EA({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new TA({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Jle=process.env.APP||"unknown";Me();import{v4 as A0}from"uuid";function w0(){return new nv({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:po.DELTA})}var C0=[new Rc({instrumentName:"test_event_duration",instrumentType:he.HISTOGRAM,aggregation:new rs([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new Rc({instrumentName:"test_step_duration",instrumentType:he.HISTOGRAM,aggregation:new rs([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],Mc=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 tp({[jl]:e.serviceName,[ZE]:t,[tT]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:A0()}),o=w0(),i=new Cp({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Op({resource:n,readers:[i],views:C0}),Hl.setGlobalMeterProvider(this.provider),this.meter=Hl.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Fl(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=Fl(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 Et=new Ul;function vA(r){r.disabled||(Et=new Mc(r))}import{hostname as M0}from"os";import _0 from"path";import{_android as P0}from"playwright";async function AA(r){let{apiClient:e,logger:t,creationOpts:n,onStatusUpdate:o,logLevel:i,orgId:a,sessionId:s}=r,{token:c,webRtcUrl:l,adbUrl:u,name:d,apkDownloadUrl:m,region:g,playwrightServerUrl:p}=await e.createAndroidEmulator({...n,hostname:M0(),sessionId:s}),h;try{x0("adb --version"),h="adb"}catch{if(process.env.ANDROID_HOME)h=_0.join(process.env.ANDROID_HOME,"platform-tools","adb");else throw new Error("The adb binary was not found in PATH and ANDROID_HOME is not set either")}t.info({emulatorName:d,apkToInstall:n.apkToInstall,region:g,apkDownloadUrl:m,sessionId:s,playwrightServerUrl:p},"Android instance creation ok");let f=await Et.recordDuration({fn:async()=>await R0({adbUrl:u,endpointUrl:l,token:c,logLevel:i,adbPath:h}),name:"test_event_duration",tags:["name:limbar-client-creation",`orgId:${a}`]}),E=["https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-v7.6.2.apk","https://github.com/appium/appium-uiautomator2-server/releases/download/v7.6.2/appium-uiautomator2-server-debug-androidTest.apk","https://github.com/appium/io.appium.settings/releases/download/v5.14.15/settings_apk-debug.apk"];m&&E.push(m);let b=n.apkToInstall?.channel,x=n.apkToInstall?.tag;o(`Installing APK${b?` with channel ${b}`:""}${x?` and tag ${x}`:""}`),await Promise.all(E.map(w=>f.sendAsset(w))),o("Starting ADB tunnel");let v=await Et.recordDuration({fn:async()=>await f.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]}),A=()=>{v.close(),f.disconnect()},_;return p&&(o("Opening Playwright connection"),_=await Et.recordDuration({fn:async()=>await P0.connect(p),name:"test_event_duration",tags:["name:playwright-device-connect",`orgId:${a}`]})),{adbPort:v.address.port,close:A,limbarToken:c,limbarUrl:l,emulatorName:d,playwrightDevice:_,client:f}}async function _c({onStatusUpdate:r,creationOpts:e,apiClient:t,logger:n,driverLogLevel:o,appiumPort:i,socket:a,orgId:s,sessionId:c}){let l=Date.now(),u=[],d;if("avdId"in e)d=e;else{d=await AA({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r,orgId:s,sessionId:c});let p=d.emulatorName;u.push(()=>t.deleteAndroidEmulator(p),d.close)}let m=async()=>{for(let p=u.length-1;p>=0;p-=1)try{await u[p]()}catch(h){if(h instanceof Error&&h.message.includes("ECONNREFUSED"))return;n.warn({err:h},"Error running cleanup task")}},g=async()=>{if(a&&!a.connected)throw await m(),new Error("Client disconnected before Appium driver could be started")};await g();try{let p=await U0({logger:n,driverLogLevel:o,appiumPort:i,emulatorStart:l,emulatorCreationParams:d,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:s,sessionId:c});return u.push(p.appiumClose),u.push(async()=>p.driver.deleteSession()),await g(),{...d,...p,cleanup:m,appiumPort:i}}catch(p){throw await m(),new Error(`Failed to start Appium driver: ${p}`)}}async function U0({logger:r,driverLogLevel:e="warn",emulatorStart:t,appiumPort:n,emulatorCreationParams:o,onStatusUpdate:i,creationOpts:a}){let s=[],{adbPort:c,emulatorName:l}=o,u;if(!c){let v=0;for(;v<30;){let A=5560+Math.floor(Math.random()*100);if(A%2!==0&&(A=Math.min(A+1,5658)),await kl(A)&&await kl(A+1)){u=A,c=A+1;break}v+=1}if(!c)throw new Error(`Failed to find an available ADB port after ${v} attempts`)}l||(l=`emulator-${u}`,s.push(async()=>{let v=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{O0(`${v} -s ${l} emu kill`,{stdio:"inherit"})}catch(A){r.warn({err:A,emulatorName:l},"Failed to kill emulator")}}));let d=Date.now(),{close:m,logFile:g}=await F0({logger:r,logLevel:e,appiumPort:n}),p={platformName:"Android","appium:automationName":"UiAutomator2","appium:deviceName":"Android","appium:udid":`127.0.0.1:${c}`,"appium:adbExecTimeout":3e4,"appium:newCommandTimeout":600,"appium:skipDeviceInitialization":!0,"appium:skipServerInstallation":!0,"appium:androidInstallTimeout":6e4,"appium:autoWebview":!1,"appium:autoWebviewTimeout":0,"appium:clearDeviceLogsOnStart":!0,"appium:ensureWebviewsHavePages":!0},h={hostname:"localhost",port:n,logLevel:e,capabilities:p,connectionRetryTimeout:15e3,connectionRetryCount:2};"avdId"in o&&(p["appium:avd"]=o.avdId,p["appium:avdLaunchTimeout"]=18e4,p["appium:avdReadyTimeout"]=18e4,p["appium:skipDeviceInitialization"]=!1,p["appium:skipServerInstallation"]=!1,p["appium:udid"]=void 0,p["appium:avdArgs"]=`-port ${u} -no-snapshot-save -no-boot-anim -noaudio`,h.connectionRetryTimeout=12e4,h.connectionRetryCount=3);let f=Date.now(),E;try{E=await k0(h)}catch(v){throw i(`Emulator creation failed: ${v}`),await Promise.all(s.map(A=>A())),v}if(await E.updateSettings({enableMultiWindows:!0}),"avdId"in a){let v=a.apkFilePath?.trim();if(v){let A=D0.resolve(v);if(!L0.existsSync(A))throw new Error(`APK not found at path: ${A}`);i("Installing local APK...");let _=Date.now();try{await E.installApp(A),r.info({apkFilePath:A,installDurationMs:Date.now()-_},"Installed local APK")}catch(w){throw r.error({err:w,apkFilePath:A},"Failed to install local APK"),new Error(`Failed to install APK from ${A}: ${w.message}`)}}}let b=new Map;return E.on("command",v=>{b.set(v.command,Date.now())}),E.on("result",v=>{let A=b.get(v.command);if(!A)return;let _=Date.now()-A;v.result instanceof Error?r.warn({err:v.result,command:v.command,args:v.body,durationMs:_},"Appium cmd failed"):_>1e4&&r.warn({command:v.command,args:v.body,durationMs:_},"Appium cmd took very long"),b.delete(v.command)}),r.info({timings:{emulatorDuration:d-t,appiumDuration:f-d,wdioDuration:Date.now()-f},capabilities:p,emulatorName:l},"Started Appium driver"),{driver:E,appiumClose:async()=>{await m(),await Promise.all(s.map(v=>v()))},appiumPort:n,appiumLogFile:g,emulatorName:l,adbPort:c}}async function F0({logger:r,logLevel:e,appiumPort:t}){let n=`${N0()}/appium-port-${Date.now()}.log`,o=await I0.main({port:t,address:"localhost",relaxedSecurityEnabled:!0,longStacktrace:e==="debug",logFormat:"json",loglevel:e,logFile:n});return{logFile:n,close:async()=>{await o.close()}}}import wA from"crypto";import B0 from"fs";async function Pc({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await B0.promises.readFile(t),a=wA.createHash("md5").update(i).digest("base64"),s=wA.createHash("md5").update(i).digest("hex"),c=await n.generateAndroidAssetUrls({channel:e,tag:r??"latest",md5:a});if(c.md5&&(c.md5===a||c.md5===s)){o.info({channel:e,tag:r,md5:a,md5Hex:s},`Asset ${t} already exists on emulator platform`);return}if(c.uploadUrl){o.info({channel:e,tag:r,md5:a,uploadUrl:c.uploadUrl},`Uploading asset ${t} to emulator platform...`);try{let l=await fetch(c.uploadUrl,{headers:{"Content-Length":i.length.toString(),"Content-Type":"application/octet-stream"},method:"PUT",body:i});if(l.status!==200)throw new Error(`Got error response from emulator platform: ${l.status} ${await l.text()}`);o.info({channel:e,tag:r,md5:a},`Asset ${t} was uploaded successfully!`);return}catch(l){try{await n.deleteAndroidAsset(e,r??"latest")}catch(u){o.warn({err:u,tag:r,channel:e},"Failed to cleanup asset metadata for failed upload. Please contact Momentic support.")}throw o.error({err:l},"Failed to upload asset"),l}}throw new Error(`No upload URL was given for asset ${t}`)}import{execSync as CA}from"child_process";import{existsSync as z0}from"fs";import{platform as RA}from"os";import{dirname as H0,join as G0,resolve as V0}from"path";import{fileURLToPath as W0}from"url";var xA,j0=W0(import.meta.url),$0=H0(j0);xA=V0($0,"..");var os=xA;C.info(`Setting APPIUM_HOME to ${os}`);process.env.APPIUM_HOME=os;var q0="If you do not have Java installed, please download the JDK 24 from https://www.oracle.com/java/technologies/downloads/, move it to your home directory, and then set the JAVA_HOME environment variable in your shell profile to the JDK path.",K0="If you do not have Android Studio installed, please download it first from https://developer.android.com/studio and then follow all setup instructions in the Android Studio app.",Y0="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",MA="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",_A="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function X0(){if(!process.env.JAVA_HOME)C.warn("JAVA_HOME is not set. Some Appium drivers and Android tools may not work as expected.");else{process.platform==="darwin"&&/\.jdk\/?$/.test(process.env.JAVA_HOME)&&C.warn("JAVA_HOME appears to point at a *.jdk bundle, which is incorrect. The correct path should be formatted like '<bundle>/Contents/Home'.");let e=((t,n)=>G0(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");z0(e)||C.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{CA("java --version",{stdio:"pipe",encoding:"utf-8"})||(C.error(`Could not find a Java installation. ${q0}`),process.exit(1))}catch(r){C.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function J0(){process.env.ANDROID_HOME||(C.error(`The ANDROID_HOME environment variable is not set. ${Y0} ${RA()==="darwin"?MA:_A}`),process.exit(1))}function Q0(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{CA(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(C.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${K0} Finally, ensure that the 'adb' command is available in your shell. ${RA()==="darwin"?MA:_A}`),process.exit(1))}catch(e){C.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function PA(){X0(),J0(),Q0()}import{create as Z0,windowedFiniteBatchScheduler as eU}from"@yornaath/batshit";import tU from"ws";var rU=100,nU=2500,IA=4e3,oU="\u2026";async function Ic({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=Z0({fetcher:async l=>{e(l)},resolver:()=>{},scheduler:eU({windowMs:nU,maxBatchSize:rU})}),{hostname:n="localhost",port:o=4723,protocol:i="http"}=r.options,s=`${i==="https"?"wss":"ws"}://${n}:${o}/ws/session/${r.sessionId}/appium/device/logcat`,c=new tU(s);return c.on("message",l=>{let u=l.toString().trim();u.length!==0&&(u.length>IA&&(u=u.slice(0,IA)+oU),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}try{t.next()}catch{}}}import{Server as G1}from"socket.io";import f1 from"path";import{randomUUID as hU}from"crypto";import{faker as iU}from"@faker-js/faker";import aU from"assert";import sU from"axios";import*as lU from"child_process";import cU from"moment";import*as uU from"otpauth";import dU from"pg";async function OA(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=cl(n,e);t.push(...o)}),t}function mU(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 pU(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 gU=Object.getPrototypeOf(async function(){}).constructor;async function LA(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,additionalBindings:i,request:a,response:s}=e.bindings,c=e.tools,l={},u=(x,v)=>{o[x]=v,l[x]=v},d={},m=(x,v)=>{o[x]=v,d[x]=v},g;n.includes("Octokit")&&(g=(await import("@octokit/rest")).Octokit);let p;n.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new gU("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(sU,cU,c.fakerInstance??iU,aU,dU,g,p,uU,lU,OA,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:m,v=>c.sms.send(v),v=>c.sms.fetchLatest(v),c.email,c.sms,c.ai,mU(a,s),...Object.values(i??{}))),f=!0,E,b;try{let x=await k(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await pU(e.options.responseSerialization??"RAW",x)}catch(x){t.error({err:x,env:o,evalCode:n},`[${r}] Error executing code: ${x}`),f=!1,x instanceof Rn?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=x instanceof Error?x.message:`${x}`}return{result:E,variableUpdates:l,persistentVariableUpdates:d,success:f,error:b}}async function NA({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=vn,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=hU(),m=await LA(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return C.debug(`[${d}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as fU,randomUUID as SU}from"crypto";import yU from"fetch-retry";var bU=yU(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}}),DA=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,kA=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function UA({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=vn,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!DA)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,g,p=0;if(!kA)throw new Error("Missing lambda auth secret.");let h=fU("sha256",kA).update(r).digest("hex");for(;p<=i;){p++,a?.throwIfAborted();let E={id:SU(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(m=await k(bU(DA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!m)throw new Error("Got empty response from code evaluation server");if(!m.ok)throw new Error(`Code evaluation server returned error code ${m.status}`);g=void 0;break}catch(b){g=b}}if(g)throw s.error({err:g},"Failed to evaluate code remotely"),g;if(!m)throw new Error(`An unexpected code evaluation error occurred${g?`: ${g}`:""}`);let f;try{f=Fy.parse(await m.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 zr(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await UA(r);else if(r.localTools)e=await NA({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
40
40
|
${e.error}
|
|
41
41
|
Code received:
|
|
42
|
-
${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 EU}from"lodash-es";async function is(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=vn,allowUndefined:c=!1}=r,l=/{{(.*?)}}/g,u=t.matchAll(l),d=t;for(let m of u){if(m.length<2)continue;let g=m[1].trim(),p;try{p=await zr({orgId:e,code:g,fragment:!0,context:n,timeoutMs:s,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(p===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${g}' 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 p=="string"?p:`${p}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(m[0],h)}return d}async function Oc(r){return FA(r)}async function FA({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let s in r){if(e.includes(s))continue;let c=!1;if(t)if(t.includes(s))c=!0;else continue;let l=r[s],u=[...o,s];if(typeof l=="string"&&l.includes("{{")){let d=await is({s:l,context:n,...a});if(l===d)continue;i.push({path:u,original:l}),r[s]=d}else typeof l=="object"&&l!==null&&!Array.isArray(l)&&await FA({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Lc(r,e){for(let{path:t,original:n}of e)EU(r,t,n)}import TU from"fetch-retry";var
|
|
43
|
-
${JSON.stringify(t)}`);let n=[];return n.push({key:wU(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Dc({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&id(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function as(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;WA(n,e)&&(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date})}function Fp(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function jA(r,e){return r?WA(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:Fp(e.target),updatedAt:e.updatedAt}}function RU(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${pl(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${pl(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"SCROLL_TO":{let e=r.scrollStepPercent?` (${Math.round(r.scrollStepPercent*100)}% per step)`:"";return`Scroll ${r.direction} to find: ${r.target.description}${e}`}case"SCREEN_CHECK":return`Check that the screen ${GA(r.assertion)}`;case"ELEMENT_CHECK":return`Check that the element ${pl(r.target)} ${zA(r.assertion)}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;case"INSTALL_APP":return`Install app: ${r.uri}`;case"UNINSTALL_APP":return`Uninstall app: ${r.packageName}`;case"ADB":return`ADB command: ${r.command}`;case"KILL_APP":return"Kill active app";case"STATE":return"Send debug state to Momentic";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}function Bp(r){switch(r.type){case"MOBILE_PRESET_STEP":return RU(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;case"MOBILE_AI_ACTION_STEP":return`AI action: ${r.text}`;default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as Tw}from"lodash-es";import zp from"semver";function kc(r,e){if(r!=="0.0.1"&&r!==e[e.length-1].toVersion)throw new Error("Please bump latestSchemaVersion in types package after adding a migration");e.forEach((t,n)=>{if(!zp.valid(t.toVersion)||!zp.valid(t.fromVersion))throw new Error(`Migration '${t.name}' has invalid version`);if(!zp.gt(t.toVersion,t.fromVersion))throw new Error(`Migration '${t.name}' has toVersion <= fromVersion`);if(n===0)return;if(e[n-1].toVersion!==t.fromVersion)throw new Error(`Migration '${t.name}' at index ${n} is not contiguous with previous migration`)})}import xU from"diff-lines";import MU,{gte as _U}from"semver";function PU(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}async function Hp({metadata:r,steps:e,logger:t,toVersion:n,migrations:o}){let i=e,{schemaVersion:a,id:s}=r,c=o.findIndex(d=>MU.gt(d.toVersion,a));if(c===-1)return{steps:i,newVersion:a};let l=a;for(let d=c;d<o.length;d++){if(n&&_U(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let m=o[d],g={id:s,migration:m.name,toVersion:m.toVersion};try{i=await $A(i,m),l=m.toVersion}catch(p){throw t.error({err:p,...g},"Migration failed"),new Error(`Step migration ${m.name} failed: ${p}`)}}let u=xU(JSON.stringify(e,void 0,2),JSON.stringify(i,void 0,2),{n_surrounding:1});return u.trim()&&t.debug({diffs:u,id:s},"Migration diffs"),{newVersion:l,steps:i}}async function $A(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)||PU(i)&&(n[o]=await $A(i,e))}return t}var qA={name:"Migrate API request body types",fromVersion:"0.0.1",toVersion:"0.0.2",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="MOBILE_PRESET_STEP")return e;let t=e.command;if(!t||t.type!=="REQUEST")return e;let n=typeof t.body=="string"&&t.body.length>0?{type:"json",content:t.body}:void 0;return t.body=n,e})};var KA=[qA];kc(Zn,KA);async function Gp({metadata:r,steps:e,logger:t,toVersion:n}){return await Hp({metadata:r,steps:e,logger:t,toVersion:n,migrations:KA})}var YA={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 XA={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 IU=["target","fromTarget","toTarget"];function JA(r){for(let e of IU){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var QA={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 JA(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])JA(n);return e}default:return e}})};import{v4 as OU}from"uuid";var ZA={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=OU()),e;default:return e}})};import{v4 as ew}from"uuid";var tw={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??ew(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??ew()}})),delete e.commands),e;default:return e}})};var rw={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 LU}from"uuid";var nw={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=LU()),e))};import{v4 as ow}from"uuid";var iw={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=ow())}return e.id=ow(),e})};var aw={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 NU}from"uuid";var sw={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=NU()),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 lw={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 cw={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&&uw(t),e})};function uw(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){uw(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 dw={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 mw={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 pw={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 gw={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 hw={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 fw={name:"Migrate API request body types",fromVersion:"1.0.21",toVersion:"1.0.22",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t||t.type!=="REQUEST")return e;let n=typeof t.body=="string"&&t.body.length>0?{type:"json",content:t.body}:void 0;return t.body=n,e})};var Sw={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 Uc=new Set(["CLICK","TYPE","SELECT_OPTION"]),yw={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||Uc.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||Uc.has(c))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||Uc.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let m=d?.elementDescriptor,g=d?.type;(m!==void 0||Uc.has(g))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var bw={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 Ew={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,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(l=>{let u=l.type;u?.startsWith("PRESET_")&&(l.type=u.slice(7))})}),e}),stopOnFailure:!0};var DU=[Sw,bw,Ew,yw,YA,XA,QA,ZA,tw,rw,nw,iw,aw,sw,lw,cw,dw,mw,pw,gw,hw,fw];kc(yn,DU);async function vw(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await Fc({rawSteps:r.rawStepLists.steps,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e}),o={steps:t};for(let i of["beforeSteps","afterSteps"]){let a=r.rawStepLists[i];if(!a)continue;let{resolvedSteps:s}=await Fc({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=s}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function UU(r,e,t){let{newVersion:n,steps:o}=await Gp({metadata:r,steps:e,logger:t});try{return{steps:ir.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 ia(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function Fc({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await UU(n,r,t),s=[];for(let c of a)s.push(await Aw({rawStep:ir.parse(c),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function Aw({rawStep:r,onFetchModule:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"MOBILE_MODULE_STEP":{let o=r.moduleId,i=n[o];if(i)return{...Tw(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let s;try{s=ir.array().parse(a.steps)}catch(u){throw t.error({err:u,steps:a.steps,moduleId:o},"Module failed to parse (mobile)"),u}let c=await Promise.all(s.map(u=>Aw({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),l={...a,description:a.description||void 0,steps:c};return n[o]=Tw(l),{...l,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_AI_ACTION_STEP":case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as FU}from"lodash-es";import{v4 as Vp}from"uuid";async function Ln(r){let e=new Map,t=new Set,n=FU(r.steps),o=await ww({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function ww({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Vp():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Vp():d.id,"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Up({id:d.id,orgId:n.orgId,testId:n.testId,value:Tn.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),l.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Vp():u.id,m=u.moduleId;a.has(m)?m=a.get(m):s!==void 0&&(m=await s(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:p,moduleUpdates:h}=await ww({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(h),l.cachesToSave=l.cachesToSave.concat(g),t.has(m)||(t.add(m),l.moduleUpdates.push({...ri.parse(u),steps:ir.array().parse(p),moduleId:m}));let f=Ra.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:m,inputs:u.inputs,id:d});l.stepsToSave.push(f);break}case"MOBILE_AI_ACTION_STEP":{l.stepsToSave.push(u);break}default:{let d=u}}return l}function BU(r){let e={parentChain:[]};return Cw(r,e),e}function Cw(r,e){let{onPreset:t,onModule:n,earlyStop:o}=r;for(let i of r.steps){if(i.type==="RESOLVED_MOBILE_MODULE"){if(n?.(i,e)&&o||(e.parentChain.push(i),Cw({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function zU(r,e,t=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return BU({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function Rw({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==i[s])return!1;i.shift()}return!!zU([r],t,i).result}function xw(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":if(!t.steps.length){e=t,n=!0;break}t=t.steps[0];break;case"MOBILE_PRESET_STEP":e=t,n=!0;break;default:{let s=t}}let o=r[r.length-1],i=r[r.length-1],a=!1;for(;!a&&i;)switch(i.type){case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":if(!i.steps.length){o=i,a=!0;break}i=i.steps[i.steps.length-1];break;case"MOBILE_PRESET_STEP":o=i,a=!0;break;default:{let s=i}}return{firstMetadata:e,lastMetadata:o}}function Mw({result:r,firstMetadata:e,lastMetadata:t}){e&&(r.beforeSnapshot=e.beforeSnapshot),t&&(r.data=t.data,r.afterSnapshot=t.afterSnapshot,t.status!=="SUCCESS"&&(r.message=t.message))}import{cloneDeep as Qge}from"lodash-es";import ehe from"truncate-json";import{v4 as che}from"uuid";import{cloneDeep as Gge,unset as Vge}from"lodash-es";import{cloneDeep as ghe}from"lodash-es";import{diff as Zhe}from"deep-object-diff";import{diff as Ohe}from"deep-object-diff";import{cloneDeep as Nhe}from"lodash-es";import{v4 as Yhe}from"uuid";import{cloneDeep as ife}from"lodash-es";import{cloneDeep as Tfe}from"lodash-es";import{stringify as Lfe}from"yaml";async function q(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function jp({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((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function ss({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await jp({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function Bc(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}import HU from"picomatch";var zc=(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||HU(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},Hc=(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}},Ai=r=>{try{return new URL(r),!0}catch{return!1}},_w=r=>!r.toLowerCase().startsWith("http"),wi=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function bo(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as Pw}from"uuid";function $p(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Gc=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:$p({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(ky(e.type)){this.creditsUsedV2+=1;return}let t=Gd(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Vd(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:Pw(),properties:$p({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:Pw(),properties:$p({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as gSe}from"lodash-es";import{CookieJar as h1}from"tough-cookie";var qp={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
|
|
42
|
+
${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 EU}from"lodash-es";async function is(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=vn,allowUndefined:c=!1}=r,l=/{{(.*?)}}/g,u=t.matchAll(l),d=t;for(let m of u){if(m.length<2)continue;let g=m[1].trim(),p;try{p=await zr({orgId:e,code:g,fragment:!0,context:n,timeoutMs:s,logger:o,retries:a,localTools:r.localTools,signal:i})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(p===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${g}' 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 p=="string"?p:`${p}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(m[0],h)}return d}async function Oc(r){return FA(r)}async function FA({obj:r,bannedKeys:e,allowList:t,context:n,prefixPath:o=[],replacements:i=[],...a}){for(let s in r){if(e.includes(s))continue;let c=!1;if(t)if(t.includes(s))c=!0;else continue;let l=r[s],u=[...o,s];if(typeof l=="string"&&l.includes("{{")){let d=await is({s:l,context:n,...a});if(l===d)continue;i.push({path:u,original:l}),r[s]=d}else typeof l=="object"&&l!==null&&!Array.isArray(l)&&await FA({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Lc(r,e){for(let{path:t,original:n}of e)EU(r,t,n)}import TU from"fetch-retry";var gde=process.env.MAILINATOR_API_KEY,hde=TU(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import p1 from"fetch-cookie";import g1 from"path";function gt(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var rn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},nn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Lp={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Np={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function zA(r){switch(r.type){case"ELEMENT_CONTENT":return`content ${r.negated?nn[r.operation]:rn[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?nn[r.operation]:rn[r.operation];return r.operation==="EXISTS"?`attribute '${r.attr}' ${t}`:`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_NAME":{let t=r.negated?nn[r.operation]:rn[r.operation];return r.operation==="EXISTS"?`tag name ${t}`:`tag name ${t} '${r.value}'`}case"ELEMENT_STYLE":{let t=r.negated?nn[r.operation]:rn[r.operation];return r.operation==="EXISTS"?`style property '${r.property}' ${t}`:`style property '${r.property}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?Np[r.condition]:Lp[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 Ide={CONTENT:"The page"};function HA(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 Dp(r){return`${r.negated?nn.CONTAINS:rn.CONTAINS} '${r.value}'`}function GA(r){switch(r.type){case"CONTENT":return Dp(r);default:return r.type,""}}function vU(r){return typeof r=="object"&&r!==null}function yo(r){if(Array.isArray(r))return r.map(yo);if(vU(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=yo(n))}),e}return r}function Hr(r,e,t,n){let{negated:o,ignoreCase:i}=n,a=r.trim(),s=e.trim();i&&(a=a.toLowerCase(),s=s.toLowerCase());let c;switch(t){case"CONTAINS":{c=a.includes(s);break}case"EQUALS":{c=a===s;break}case"STARTS_WITH":{c=a.startsWith(s);break}case"EXISTS":{c=a.length>0;break}default:throw new Error(`Unrecognized content assertion type: ${t}`)}return o?!c:c}function Nc(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function dr(r){return r.type==="ELEMENT_EXISTENCE"?r.negated?Lp[r.condition]:Np[r.condition]:r.negated?rn[r.operation]:nn[r.operation]}import{diff as AU}from"deep-object-diff";import{cloneDeep as tme}from"lodash-es";function WA(r,e){return!r&&!e?!1:!r||!e?!0:Object.keys(AU(r,e)).length>0}function kp({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],s=[],c=[],l=0,u=(m,g)=>{try{let p=Tn.parse(g.value);if(p.type!==m.type){o.warn({parsedCacheEntry:p,command:m},"Not using step cache due to type mismatch"),s.push(g.key);return}m.cache=p.cache,a.push(g.key),c.push(g.uniqueKey)}catch(p){s.push(g.key),o.error({err:p,cacheEntry:g},"Not using step cache due to parsing error")}},d=(m,g)=>{let p=CU(m.id,g),h=p.find(f=>!!n[f]);if(h)u(m,n[h]);else{if(m.type==="AI_CHECK")return;s.push(p[0])}};for(let m of r)switch(m.type){case"MOBILE_PRESET_STEP":{if(!gl(m.command)||m.command.type==="TYPE"&&!m.command.target||"cache"in m.command&&m.command.cache.cache)continue;l++,d(m.command,i);break}case"RESOLVED_MOBILE_MODULE":{l+=m.steps.length;let{cacheKeysHit:g,cacheKeysMissed:p,uniqueKeysHit:h}=kp({...t,steps:m.steps,keyPrefix:i?`${i}:${m.id}`:m.id,topLevel:!1});a.push(...g),s.push(...p),c.push(...h);break}case"MOBILE_AI_ACTION_STEP":{l++;break}default:{let g=m}}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheKeysMissed:s,cacheKeysHit:a,uniqueKeysHit:c,cacheEntriesKeys:Object.values(n).map(m=>m.uniqueKey)},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:s,uniqueKeysHit:c}}function wU(r,e){return e?`${e}:${r}`:r}function CU(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 Up(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
43
|
+
${JSON.stringify(t)}`);let n=[];return n.push({key:wU(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Dc({cmd:r,newTarget:e,key:t,logger:n,updatedWithAI:o}){if(r.type==="DRAG")if(t!=="fromTarget"&&t!=="toTarget")n.error({cmd:r,newTarget:e,key:t},"Attempted to apply invalid cache to DRAG command");else{let i=r.cache?.updatedAt;r.cache={...r.cache,[t]:e,updatedAt:i&&!o?i:new Date}}else if(t==="target"&&id(r)){let i=r.cache?.updatedAt;r.cache={...r.cache,target:e,updatedAt:i&&!o?i:new Date}}else n.error({cmd:r,newTarget:e,key:t},"Invalid target cache application")}function as(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;WA(n,e)&&(t.info({updatedTraces:e,oldCmd:r},"Wrote new memory to assertion command"),r.cache={...r.cache,memory:{type:"GCS_TRACES",traces:e},updatedAt:new Date})}function Fp(r){return{...r,serializedHtml:void 0,nodeOnlySerializedHtml:void 0,screenshotUrl:void 0,boundingBox:void 0,selector:void 0,hybridSelector:void 0,generatedSelectors:void 0,id:-1}}function jA(r,e){return r?WA(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:Fp(e.target),updatedAt:e.updatedAt}}function RU(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${pl(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${pl(r.target)}`:""}`;case"PRESS":return`Press the ${r.key} button`;case"PRESS_KEYBOARD":return`Press the ${r.key} key`;case"SWIPE":return r.scrollableElement.type==="CUSTOM"?`Swipe ${r.direction} in container: ${r.scrollableElement.target.description}`:`Swipe ${r.direction} in the ${r.scrollableElement.type.toLowerCase()}`;case"SCROLL_TO":{let e=r.scrollStepPercent?` (${Math.round(r.scrollStepPercent*100)}% per step)`:"";return`Scroll ${r.direction} to find: ${r.target.description}${e}`}case"SCREEN_CHECK":return`Check that the screen ${GA(r.assertion)}`;case"ELEMENT_CHECK":return`Check that the element ${pl(r.target)} ${zA(r.assertion)}`;case"OPEN_APP":return`Open app: ${r.packageName}`;case"OPEN_NOTIFICATION_DRAWER":return"Open notification drawer";case"JAVASCRIPT":return`Execute JavaScript: ${r.code}`;case"REQUEST":return`Make API request to ${r.url}`;case"WAIT":return`Wait ${r.timeoutSecs} seconds`;case"ADD_FILE":return`Add file: ${r.file} to ${r.storageLocation}`;case"INSTALL_APP":return`Install app: ${r.uri}`;case"UNINSTALL_APP":return`Uninstall app: ${r.packageName}`;case"ADB":return`ADB command: ${r.command}`;case"KILL_APP":return"Kill active app";case"STATE":return"Send debug state to Momentic";default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}function Bp(r){switch(r.type){case"MOBILE_PRESET_STEP":return RU(r.command);case"MOBILE_MODULE_STEP":return`Module ${r.moduleId}`;case"RESOLVED_MOBILE_MODULE":return`Module ${r.name}`;case"MOBILE_AI_ACTION_STEP":return`AI action: ${r.text}`;default:{let e=r;throw new Error("If Typescript complains about the line above, you missed a case or break in the switch above")}}}import{cloneDeep as Tw}from"lodash-es";import zp from"semver";function kc(r,e){if(r!=="0.0.1"&&r!==e[e.length-1].toVersion)throw new Error("Please bump latestSchemaVersion in types package after adding a migration");e.forEach((t,n)=>{if(!zp.valid(t.toVersion)||!zp.valid(t.fromVersion))throw new Error(`Migration '${t.name}' has invalid version`);if(!zp.gt(t.toVersion,t.fromVersion))throw new Error(`Migration '${t.name}' has toVersion <= fromVersion`);if(n===0)return;if(e[n-1].toVersion!==t.fromVersion)throw new Error(`Migration '${t.name}' at index ${n} is not contiguous with previous migration`)})}import xU from"diff-lines";import MU,{gte as _U}from"semver";function PU(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}async function Hp({metadata:r,steps:e,logger:t,toVersion:n,migrations:o}){let i=e,{schemaVersion:a,id:s}=r,c=o.findIndex(d=>MU.gt(d.toVersion,a));if(c===-1)return{steps:i,newVersion:a};let l=a;for(let d=c;d<o.length;d++){if(n&&_U(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let m=o[d],g={id:s,migration:m.name,toVersion:m.toVersion};try{i=await $A(i,m),l=m.toVersion}catch(p){throw t.error({err:p,...g},"Migration failed"),new Error(`Step migration ${m.name} failed: ${p}`)}}let u=xU(JSON.stringify(e,void 0,2),JSON.stringify(i,void 0,2),{n_surrounding:1});return u.trim()&&t.debug({diffs:u,id:s},"Migration diffs"),{newVersion:l,steps:i}}async function $A(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)||PU(i)&&(n[o]=await $A(i,e))}return t}var qA={name:"Migrate API request body types",fromVersion:"0.0.1",toVersion:"0.0.2",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="MOBILE_PRESET_STEP")return e;let t=e.command;if(!t||t.type!=="REQUEST")return e;let n=typeof t.body=="string"&&t.body.length>0?{type:"json",content:t.body}:void 0;return t.body=n,e})};var KA=[qA];kc(Zn,KA);async function Gp({metadata:r,steps:e,logger:t,toVersion:n}){return await Hp({metadata:r,steps:e,logger:t,toVersion:n,migrations:KA})}var YA={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 XA={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 IU=["target","fromTarget","toTarget"];function JA(r){for(let e of IU){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var QA={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 JA(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])JA(n);return e}default:return e}})};import{v4 as OU}from"uuid";var ZA={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=OU()),e;default:return e}})};import{v4 as ew}from"uuid";var tw={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??ew(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??ew()}})),delete e.commands),e;default:return e}})};var rw={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 LU}from"uuid";var nw={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=LU()),e))};import{v4 as ow}from"uuid";var iw={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=ow())}return e.id=ow(),e})};var aw={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 NU}from"uuid";var sw={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=NU()),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 lw={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 cw={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&&uw(t),e})};function uw(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){uw(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 dw={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 mw={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 pw={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 gw={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 hw={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 fw={name:"Migrate API request body types",fromVersion:"1.0.21",toVersion:"1.0.22",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;if(!t||t.type!=="REQUEST")return e;let n=typeof t.body=="string"&&t.body.length>0?{type:"json",content:t.body}:void 0;return t.body=n,e})};var Sw={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 Uc=new Set(["CLICK","TYPE","SELECT_OPTION"]),yw={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||Uc.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,c=a?.type;(s!==void 0||Uc.has(c))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||Uc.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let m=d?.elementDescriptor,g=d?.type;(m!==void 0||Uc.has(g))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var bw={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 Ew={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,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(l=>{let u=l.type;u?.startsWith("PRESET_")&&(l.type=u.slice(7))})}),e}),stopOnFailure:!0};var DU=[Sw,bw,Ew,yw,YA,XA,QA,ZA,tw,rw,nw,iw,aw,sw,lw,cw,dw,mw,pw,gw,hw,fw];kc(yn,DU);async function vw(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await Fc({rawSteps:r.rawStepLists.steps,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e}),o={steps:t};for(let i of["beforeSteps","afterSteps"]){let a=r.rawStepLists[i];if(!a)continue;let{resolvedSteps:s}=await Fc({rawSteps:a,onFetchModule:r.onFetchModule,logger:r.logger,metadata:r.testMetadata,resolvedModuleCache:e});o[i]=s}return{resolvedStepLists:o,moduleIds:Array.from(Object.keys(e))}}async function UU(r,e,t){let{newVersion:n,steps:o}=await Gp({metadata:r,steps:e,logger:t});try{return{steps:ir.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 ia(`Failed to parse test steps while migrating test: ${i}`,r.id,"entity",{cause:i})}}async function Fc({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await UU(n,r,t),s=[];for(let c of a)s.push(await Aw({rawStep:ir.parse(c),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function Aw({rawStep:r,onFetchModule:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"MOBILE_MODULE_STEP":{let o=r.moduleId,i=n[o];if(i)return{...Tw(i),...r,type:"RESOLVED_MOBILE_MODULE"};let a=await e(o);if(!a)throw new Error(`Could not find module with id ${o}`);let s;try{s=ir.array().parse(a.steps)}catch(u){throw t.error({err:u,steps:a.steps,moduleId:o},"Module failed to parse (mobile)"),u}let c=await Promise.all(s.map(u=>Aw({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),l={...a,description:a.description||void 0,steps:c};return n[o]=Tw(l),{...l,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_AI_ACTION_STEP":case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as FU}from"lodash-es";import{v4 as Vp}from"uuid";async function Ln(r){let e=new Map,t=new Set,n=FU(r.steps),o=await ww({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function ww({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let u of r)switch(u.id=c?Vp():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Vp():d.id,"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Up({id:d.id,orgId:n.orgId,testId:n.testId,value:Tn.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),l.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Vp():u.id,m=u.moduleId;a.has(m)?m=a.get(m):s!==void 0&&(m=await s(u),a.set(u.moduleId,m));let{cachesToSave:g,stepsToSave:p,moduleUpdates:h}=await ww({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,m],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(h),l.cachesToSave=l.cachesToSave.concat(g),t.has(m)||(t.add(m),l.moduleUpdates.push({...ri.parse(u),steps:ir.array().parse(p),moduleId:m}));let f=Ra.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:m,inputs:u.inputs,id:d});l.stepsToSave.push(f);break}case"MOBILE_AI_ACTION_STEP":{l.stepsToSave.push(u);break}default:{let d=u}}return l}function BU(r){let e={parentChain:[]};return Cw(r,e),e}function Cw(r,e){let{onPreset:t,onModule:n,earlyStop:o}=r;for(let i of r.steps){if(i.type==="RESOLVED_MOBILE_MODULE"){if(n?.(i,e)&&o||(e.parentChain.push(i),Cw({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function zU(r,e,t=[]){let n,o=[],i=(a,s)=>{let c=JSON.stringify(s.parentChain.map(u=>u.id)),l=t.length===0?!0:JSON.stringify(t)===c;return a.id===e&&l?(n=a,o=s.parentChain,!0):!1};return BU({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function Rw({currentStep:r,currentParentChain:e,desiredStepId:t,desiredStepParentChain:n}){let o=Array.from(e),i=Array.from(n);for(let s=0;s<o.length;s++){if(o[s]!==i[s])return!1;i.shift()}return!!zU([r],t,i).result}function xw(r){let e=r[0],t=r[0],n=!1;for(;!n&&t;)switch(t.type){case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":if(!t.steps.length){e=t,n=!0;break}t=t.steps[0];break;case"MOBILE_PRESET_STEP":e=t,n=!0;break;default:{let s=t}}let o=r[r.length-1],i=r[r.length-1],a=!1;for(;!a&&i;)switch(i.type){case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":if(!i.steps.length){o=i,a=!0;break}i=i.steps[i.steps.length-1];break;case"MOBILE_PRESET_STEP":o=i,a=!0;break;default:{let s=i}}return{firstMetadata:e,lastMetadata:o}}function Mw({result:r,firstMetadata:e,lastMetadata:t}){e&&(r.beforeSnapshot=e.beforeSnapshot),t&&(r.data=t.data,r.afterSnapshot=t.afterSnapshot,t.status!=="SUCCESS"&&(r.message=t.message))}import{cloneDeep as Zge}from"lodash-es";import the from"truncate-json";import{v4 as uhe}from"uuid";import{cloneDeep as Vge,unset as Wge}from"lodash-es";import{cloneDeep as hhe}from"lodash-es";import{diff as efe}from"deep-object-diff";import{diff as Lhe}from"deep-object-diff";import{cloneDeep as Dhe}from"lodash-es";import{v4 as Xhe}from"uuid";import{cloneDeep as afe}from"lodash-es";import{cloneDeep as vfe}from"lodash-es";import{stringify as Nfe}from"yaml";async function q(r,e){if(!(r<=0))return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r);function i(){clearTimeout(o),e?.removeEventListener("abort",i),n(e?.reason)}})}async function jp({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((s,c)=>{function l(){clearInterval(a),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(a);return}e?.addEventListener("abort",l,{once:!0}),(async()=>{try{s(await r())}catch(u){c(u)}finally{clearInterval(a),e?.removeEventListener("abort",l)}})()})}async function ss({promiseGenerator:r,timeoutMs:e,codePath:t,logger:n,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},c=setTimeout(()=>{o?.removeEventListener("abort",s),!i&&a.abort()},e);o?.addEventListener("abort",s,{once:!0});try{return await jp({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function Bc(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}import HU from"picomatch";var zc=(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||HU(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},Hc=(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}},Ai=r=>{try{return new URL(r),!0}catch{return!1}},_w=r=>!r.toLowerCase().startsWith("http"),wi=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function bo(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}import{v4 as Pw}from"uuid";function $p(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Gc=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:$p({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(ky(e.type)){this.creditsUsedV2+=1;return}let t=Gd(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Vd(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:Pw(),properties:$p({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:Pw(),properties:$p({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as hSe}from"lodash-es";import{CookieJar as h1}from"tough-cookie";var qp={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
|
|
44
44
|
var momenticConstants = {
|
|
45
45
|
bannedClassSubstrings: [
|
|
46
46
|
"relative",
|
|
@@ -4218,7 +4218,7 @@ ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="Th
|
|
|
4218
4218
|
writable: false,
|
|
4219
4219
|
configurable: false,
|
|
4220
4220
|
});`),`${t}
|
|
4221
|
-
//# sourceURL=momentic-injected/extra-scripts.js`}async function uC(r){try{return await DF(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function DF({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:te}),o=await Ar(r,e,500),i=await r.boundingBox({timeout:te});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:te}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let l=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),m=u.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let g={x:Math.min(Math.max(1,d.left-m.left),m.width-1),y:Math.min(Math.max(1,d.top-m.top),m.height-1)},p=l._MOMENTIC_FEATURE_FLAGS?.[Vc],h=c.getAttribute(on),f=!p&&h?vr(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:g,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:te});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:te}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var mC=["date","datetime-local","month","time","week"],dC={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 pC(r){try{await k(kF(r),{milliseconds:ee})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function kF({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await it({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:te,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!dC[i])return;dC[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 Vt}from"zod";var gC=Vt.object({doubleClick:Vt.boolean().optional(),rightClick:Vt.boolean().optional(),force:Vt.boolean().optional(),waitForDownload:Vt.boolean().optional(),delayMs:Vt.number().optional(),downloadTimeoutMs:Vt.number().optional(),relativePosition:Vt.object({x:Vt.number(),y:Vt.number()}).optional()}),nEe=Vt.object({repeat:Vt.number().optional(),convertMeta:Vt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Vt.number().optional()});async function Xc({locator:r,callbacks:e,logger:t,timeoutMs:n=te}){try{await fg(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let g=window.getComputedStyle(d,null).getPropertyValue("display");if(g==="none"||g==="contents")return!1;let p=d.getBoundingClientRect();return!(!p.height||!p.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await k(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 fg(r,e=te){let t=await r.state.getRoot();await it({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 Sg(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return vo({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>fC({...r,targetingResult:t,useVisualClick:e})})}async function zF(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await HF(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 HF(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:te});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:te}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),fC({...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 GF(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=gC.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await jF({targetingResult:t,position:n,options:o,logger:e,isAndroid:r.isAndroid});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function VF(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 l=await uC({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1;s&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();o.info({locator:c},"Locator click");try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:ee,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:ee,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(qF(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),zF(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function fC(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Kp;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof BF.TimeoutError?new R("ActionFailureError",`Download did not complete in ${u}ms`):new R("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Xc({locator:a.locator,callbacks:n,logger:t,timeoutMs:te})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await GF(r):l=(await VF(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new R("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await k(s,{milliseconds:e.downloadTimeoutMs??Kp});if(u instanceof Error)throw u;return{downloadedFile:await $F(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function WF(r,e){let t=await r.locator.boundingBox({timeout:ee});if(!t){let i=await Ar(r.locator,e,500);throw new R("ActionFailureError",`${pd}${i?`: ${i}`:""}`)}if(r.hints?.relativeXYToLocator){let i=t.x+r.hints.relativeXYToLocator.x,a=t.y+r.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function jF({options:r,targetingResult:e,position:t,logger:n}){let o,i,a;if(r?.relativePosition){let u=await e.locator.boundingBox({timeout:ee}),d=r.relativePosition.x,m=r.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(r.relativePosition.x,u.width))),u?.height&&(m=Math.max(0,Math.min(r.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+m,a="relative position from user"}else if(t){let u=await e.locator.boundingBox({timeout:ee});o=(u?.x??0)+t.x,i=(u?.y??0)+t.y,a="predefined position"}else{let[u,d]=await WF(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=r?.rightClick?"right":"left",l=r?.delayMs??25;return r?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l}),{clickX:o,clickY:i,reason:a}}async function $F(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=og(r.suggestedFilename()),i=e();await r.saveAs(FF(i,o)),hC(n,{force:!0}),setTimeout(()=>{hC(i,{recursive:!0,force:!0})},5*60*1e3);let a=Gw(UF(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function qF(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as KF}from"os";var YF={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 XF(){let r=KF();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function SC(r){return JSON.stringify(r.split("+").sort())}function Jc(r,e){let t=XF(),n=SC(r);for(let o of Object.values(YF))if(Object.values(o).some(i=>SC(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function yg({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await it({root:r,fn:([d,m,g,p])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*g,window.scrollY+(m??window.innerHeight)*p),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:be,codePath:"scrolling page"});else{let d=e.viewportSize()||En,m=await it({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:be,codePath:"computing page height"}),[g,p,h]=await it({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:s.waitForPageLoad,timeout:be,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<be;){a?.throwIfAborted();let E=await k(e.evaluate(()=>document.body.scrollHeight),{milliseconds:te}),[b,x,v]=await k(e.evaluate(()=>{let A=document.activeElement;if(!A)return[void 0,void 0,void 0];let _=A.getBoundingClientRect();return[A.scrollTop,_.x,_.y]}),{milliseconds:te});if(E===m&&b===g&&x===p&&v===h)break;m=E,g=b,p=x,h=v,await q(ct)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function bg(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 q(ct)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}async function yC(r){let{page:e,deltaX:t,deltaY:n,steps:o,visualTarget:i,isAndroid:a,delayMs:s}=r;if(a){await JF(e,t,n,o,s,i);return}await e.mouse.move(i.x,i.y),await e.mouse.down(),await e.mouse.move(t+i.x,n+i.y,{steps:o}),await q(s??Eo),await e.mouse.up()}async function bC(r,e,t,n){await r.mouse.move(e.x,e.y,{steps:3}),await r.mouse.down(),await r.mouse.move(t.x,t.y,{steps:3}),await q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Wc):500),await r.mouse.up()}async function JF(r,e,t,n,o,i){let a=Math.max(1,n??1),s=i.x,c=i.y,l=i.x+e,u=i.y+t;await r.evaluate(async({startX:d,startY:m,endX:g,endY:p,stepCount:h,delayMs:f})=>{let E=document.elementFromPoint(d,m)??document.body??document.documentElement,x=window._momenticMobileUtilities.dispatchTouch;x(E,"touchstart",d,m);for(let v=1;v<=h;v+=1){let A=d+(g-d)*v/h,_=m+(p-m)*v/h;x(E,"touchmove",A,_),await new Promise(w=>setTimeout(w,Math.floor((f??500)/h)))}x(E,"touchend",g,p)},{startX:s,startY:c,endX:l,endY:u,stepCount:a,delayMs:o})}import{randomUUID as iB}from"crypto";import{cloneDeep as vg}from"lodash-es";function Fn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as QF}from"crypto";var ZF="v1";function Eg(r,e){if(r.tagName.toLowerCase()==="svg"&&!tB(r))try{let t=EC(r,e),n=eB(JSON.stringify(t));return{version:ZF,json:t,hash:n}}catch{return}}function eB(r){return QF("md5").update(r).digest("hex")}function EC(r,e){let t=r.tagName.toLowerCase(),n=rB(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 s=EC(a,e);s&&o.children.push(s)}}return o}function tB(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function rB(r){let e={},t=r.attributes;for(let n of Object.keys(t))mr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var Ao={r:147,g:196,b:125,a:.55},vC={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Ao,paddingColor:Ao,borderColor:Ao,marginColor:Ao,eventTargetColor:Ao,shapeColor:Ao,shapeMarginColor:Ao,showInfo:!0,showAccessibilityInfo:!0};function AC({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=nB({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function nB({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=r[o],l=c.layout,u={};l.nodeIndex.forEach((w,N)=>{u[w]=N});let d=l.styles,m=l.bounds??[],g=c.nodes,p=g.contentDocumentIndex??{index:[],value:[]},h=g.backendNodeId??[],f=g.attributes??[],E=g.parentIndex??[],b=g.nodeName??[],x=g.nodeType??[],v=g.pseudoType??{index:[],value:[]},A=g.inputChecked??{index:[]},_=e[c.frameId];for(let w=0;w<h.length;w++){let N=h[w],G=x[w],W=f[w]??[],ye=E[w]!==void 0&&E[w]>=0?E[w]:void 0,Se=ye!==void 0?h[ye]:void 0,Ae=Se!==void 0?a[Se]:void 0,K=v.index.indexOf(w),j=K!==-1?e[v.value[K]]:void 0,le=u[w],Q;le?Q=m[le]??[]:Q=[];let Xe=b[w]!==void 0?e[b[w]]?.toLowerCase():void 0;if(!Xe){s.warn({backendNodeId:N,frameId:_,frameIndex:o,nodeBounds:Q},"DOM node has no tag name");continue}let De={backendNodeId:N,psuedoType:j,nodeType:G,frameIndex:o,parentFrameId:_,ownedFrameId:void 0,bounds:{x:Q[0]??null,y:Q[1]??null,width:Q[2]??null,height:Q[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:Se??null,tagName:Xe,parent:Ae??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Ae&&Ae.childrenBackendIds.push(N);let Bt=p.index.indexOf(w);if(Bt!==-1){let ke=p.value[Bt];i[ke]=De;let Pe=r[ke]?.frameId;De.ownedFrameId=Pe!==void 0?e[Pe]:void 0}for(let ke of Object.keys(De.bounds)){let Pe=ke;De.bounds[Pe]!==null&&(De.bounds[Pe]/=n)}let Wt=le!==void 0?d[le]??[]:[];for(let ke=0;ke<Wt.length&&!(ke>=t.length);ke++){let Pe=Wt[ke];if(Pe===void 0||isNaN(Pe))continue;let _t=e[Pe];if(_t===void 0)continue;let dt=t[ke];De.computedStyles[dt]=_t}for(let ke=0;ke<W.length;ke+=2){let Pe=W[ke],_t=W[ke+1];if(!Pe||!_t)continue;let dt=e[Pe],qr=e[_t];!dt||!qr||(De.attributes[dt]=qr)}A.index.includes(w)&&(De.attributes.checked="true"),a[De.backendNodeId]=De}return a[h[0]]}function Tg(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=`${Tg(t,e)}${a}`}return r.mPathSelector=n,n}function TC(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var oB=["html","#document","#document-fragment"];function wC({node:r,domGraph:e}){let t=[],n=r,o=TC(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=TC(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++,oB.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],m=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else m?.nodeType===1&&!m.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function CC(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 RC(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:be});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:be}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:be})).attributes,i=Fn(o,on);if(!i)throw new Error(`Could not find attribute ${on} for object ${e}`);return i}var aB=["focusable","keyshortcuts","controls","live","relevant","orientation"],sB=["selected","readonly","modal","required","invalid"],lB=["id","name","role","content"],xC=["absolute","fixed","sticky"],cB=["i","label"],uB=["path"],dB=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator","LabelText"],PC=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],IC=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],mB=["menulistpopup","statictext","inlinetextbox"],pB=80,MC=100,OC=50,Cg=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],gB=["cite"],hB={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"]},fB={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},_C={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<OC?t:""),this.role=this.role||(e.domNode.attributes.role??""),EB(this.properties,e.domNode,e.importantProperties)}vB(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&&uB.includes(this.domNode.tagName)||this.ignoredReasons.some(n=>IC.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>UC(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>FC(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&cB.includes(this.domNode.tagName)||dB.includes(this.role.toLowerCase())||this.domNode?.computedStyles["background-image"]&&this.domNode?.computedStyles["background-image"]!=="none"&&this.children.length===0||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||mr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>kC(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")||this.children.some(n=>n.isIneligible())?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isIneligible(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=_C){let t=Object.assign({},_C,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=vg(this.properties),u=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",g=this.name;d==="heading"&&g==="heading"&&(g=""),this.nameSources?.find(A=>!A.superseded&&A.type==="contents")&&this.children.length>0&&(g="");let h=this.nameSources?.find(A=>!A.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let A=h.attributeValue?.relatedNodes??[];A.length===1&&A[0].text&&A[0].text===g&&(g="")}let f=Cg.includes(this.role)||gB.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${g}
|
|
4221
|
+
//# sourceURL=momentic-injected/extra-scripts.js`}async function uC(r){try{return await DF(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function DF({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:te}),o=await Ar(r,e,500),i=await r.boundingBox({timeout:te});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:te}),{locator:c,relativePoint:void 0}}catch{}let a=await r.evaluate(c=>{let l=window,u=c.parentElement;if(!u)return{type:"error",error:"Input click target has no parent for redirection"};let d=c.getBoundingClientRect(),m=u.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let g={x:Math.min(Math.max(1,d.left-m.left),m.width-1),y:Math.min(Math.max(1,d.top-m.top),m.height-1)},p=l._MOMENTIC_FEATURE_FLAGS?.[Vc],h=c.getAttribute(on),f=!p&&h?vr(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:g,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:te});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:te}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var mC=["date","datetime-local","month","time","week"],dC={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 pC(r){try{await k(kF(r),{milliseconds:ee})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function kF({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await it({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:te,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!dC[i])return;dC[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 Vt}from"zod";var gC=Vt.object({doubleClick:Vt.boolean().optional(),rightClick:Vt.boolean().optional(),force:Vt.boolean().optional(),waitForDownload:Vt.boolean().optional(),delayMs:Vt.number().optional(),downloadTimeoutMs:Vt.number().optional(),relativePosition:Vt.object({x:Vt.number(),y:Vt.number()}).optional()}),oEe=Vt.object({repeat:Vt.number().optional(),convertMeta:Vt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Vt.number().optional()});async function Xc({locator:r,callbacks:e,logger:t,timeoutMs:n=te}){try{await fg(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let g=window.getComputedStyle(d,null).getPropertyValue("display");if(g==="none"||g==="contents")return!1;let p=d.getBoundingClientRect();return!(!p.height||!p.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await k(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 fg(r,e=te){let t=await r.state.getRoot();await it({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 Sg(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return vo({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>fC({...r,targetingResult:t,useVisualClick:e})})}async function zF(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await HF(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 HF(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:te});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:te}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),fC({...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 GF(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=gC.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await jF({targetingResult:t,position:n,options:o,logger:e,isAndroid:r.isAndroid});return e.info({position:n,options:i.success?i.data:void 0,clickLocation:{clickX:s,clickY:c,reason:l},duration:Date.now()-a},"Visual click"),{x:s,y:c}}async function VF(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 l=await uC({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=n?.force||t.hints?.force||!1;s&&!a&&t.hints?.relativeXYToLocator&&(a=t.hints.relativeXYToLocator);let c=i.toString();o.info({locator:c},"Locator click");try{n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:ee,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:ee,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(qF(u))o.warn({err:u},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:u},"Error clicking on locator, attempting to recover..."),zF(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function fC(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Kp;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof BF.TimeoutError?new R("ActionFailureError",`Download did not complete in ${u}ms`):new R("ActionFailureError",`Download failed: ${d.message}`)}})());try{await Xc({locator:a.locator,callbacks:n,logger:t,timeoutMs:te})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await GF(r):l=(await VF(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new R("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await k(s,{milliseconds:e.downloadTimeoutMs??Kp});if(u instanceof Error)throw u;return{downloadedFile:await $F(u,o.createIsolatedFolder,t),coordinates:c,locatorSource:l}}else throw new Error("No download promise or error but the step requested to wait for a download");return{coordinates:c,locatorSource:l}}async function WF(r,e){let t=await r.locator.boundingBox({timeout:ee});if(!t){let i=await Ar(r.locator,e,500);throw new R("ActionFailureError",`${pd}${i?`: ${i}`:""}`)}if(r.hints?.relativeXYToLocator){let i=t.x+r.hints.relativeXYToLocator.x,a=t.y+r.hints.relativeXYToLocator.y;return[{x:i,y:a},"targeting hint"]}let n=t.x+t.width/2,o=t.y+t.height/2;return[{x:n,y:o},"halfway point"]}async function jF({options:r,targetingResult:e,position:t,logger:n}){let o,i,a;if(r?.relativePosition){let u=await e.locator.boundingBox({timeout:ee}),d=r.relativePosition.x,m=r.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(r.relativePosition.x,u.width))),u?.height&&(m=Math.max(0,Math.min(r.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+m,a="relative position from user"}else if(t){let u=await e.locator.boundingBox({timeout:ee});o=(u?.x??0)+t.x,i=(u?.y??0)+t.y,a="predefined position"}else{let[u,d]=await WF(e,n);o=u.x,i=u.y,a=d}let s=e.locator.page(),c=r?.rightClick?"right":"left",l=r?.delayMs??25;return r?.doubleClick?await s.mouse.dblclick(o,i,{button:c,delay:l}):await s.mouse.click(o,i,{button:c,delay:l}),{clickX:o,clickY:i,reason:a}}async function $F(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=og(r.suggestedFilename()),i=e();await r.saveAs(FF(i,o)),hC(n,{force:!0}),setTimeout(()=>{hC(i,{recursive:!0,force:!0})},5*60*1e3);let a=Gw(UF(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function qF(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as KF}from"os";var YF={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 XF(){let r=KF();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function SC(r){return JSON.stringify(r.split("+").sort())}function Jc(r,e){let t=XF(),n=SC(r);for(let o of Object.values(YF))if(Object.values(o).some(i=>SC(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function yg({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await it({root:r,fn:([d,m,g,p])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*g,window.scrollY+(m??window.innerHeight)*p),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:be,codePath:"scrolling page"});else{let d=e.viewportSize()||En,m=await it({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:be,codePath:"computing page height"}),[g,p,h]=await it({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:s.waitForPageLoad,timeout:be,codePath:"computing active element position"});await e.mouse.wheel((t??d.width)*l,(o??d.height)*u);try{let f=Date.now();for(;Date.now()-f<be;){a?.throwIfAborted();let E=await k(e.evaluate(()=>document.body.scrollHeight),{milliseconds:te}),[b,x,v]=await k(e.evaluate(()=>{let A=document.activeElement;if(!A)return[void 0,void 0,void 0];let _=A.getBoundingClientRect();return[A.scrollTop,_.x,_.y]}),{milliseconds:te});if(E===m&&b===g&&x===p&&v===h)break;m=E,g=b,p=x,h=v,await q(ct)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function bg(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 q(ct)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}async function yC(r){let{page:e,deltaX:t,deltaY:n,steps:o,visualTarget:i,isAndroid:a,delayMs:s}=r;if(a){await JF(e,t,n,o,s,i);return}await e.mouse.move(i.x,i.y),await e.mouse.down(),await e.mouse.move(t+i.x,n+i.y,{steps:o}),await q(s??Eo),await e.mouse.up()}async function bC(r,e,t,n){await r.mouse.move(e.x,e.y,{steps:3}),await r.mouse.down(),await r.mouse.move(t.x,t.y,{steps:3}),await q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Wc):500),await r.mouse.up()}async function JF(r,e,t,n,o,i){let a=Math.max(1,n??1),s=i.x,c=i.y,l=i.x+e,u=i.y+t;await r.evaluate(async({startX:d,startY:m,endX:g,endY:p,stepCount:h,delayMs:f})=>{let E=document.elementFromPoint(d,m)??document.body??document.documentElement,x=window._momenticMobileUtilities.dispatchTouch;x(E,"touchstart",d,m);for(let v=1;v<=h;v+=1){let A=d+(g-d)*v/h,_=m+(p-m)*v/h;x(E,"touchmove",A,_),await new Promise(w=>setTimeout(w,Math.floor((f??500)/h)))}x(E,"touchend",g,p)},{startX:s,startY:c,endX:l,endY:u,stepCount:a,delayMs:o})}import{randomUUID as iB}from"crypto";import{cloneDeep as vg}from"lodash-es";function Fn(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as QF}from"crypto";var ZF="v1";function Eg(r,e){if(r.tagName.toLowerCase()==="svg"&&!tB(r))try{let t=EC(r,e),n=eB(JSON.stringify(t));return{version:ZF,json:t,hash:n}}catch{return}}function eB(r){return QF("md5").update(r).digest("hex")}function EC(r,e){let t=r.tagName.toLowerCase(),n=rB(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 s=EC(a,e);s&&o.children.push(s)}}return o}function tB(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function rB(r){let e={},t=r.attributes;for(let n of Object.keys(t))mr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var Ao={r:147,g:196,b:125,a:.55},vC={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Ao,paddingColor:Ao,borderColor:Ao,marginColor:Ao,eventTargetColor:Ao,shapeColor:Ao,shapeMarginColor:Ao,showInfo:!0,showAccessibilityInfo:!0};function AC({snapshot:r,devicePixelRatio:e,computedStylesToFetch:t,logger:n}){let o=r.strings,i=r.documents,a={},s={},c={roots:[],backendIdToNode:a,frameIndexToIframeNode:s};return i.forEach((l,u)=>{let d=nB({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function nB({allDocuments:r,stringConstants:e,computedStylesToFetch:t,devicePixelRatio:n,frameIndex:o,frameIndexToIframeNode:i,backendIdToNode:a,logger:s}){let c=r[o],l=c.layout,u={};l.nodeIndex.forEach((w,N)=>{u[w]=N});let d=l.styles,m=l.bounds??[],g=c.nodes,p=g.contentDocumentIndex??{index:[],value:[]},h=g.backendNodeId??[],f=g.attributes??[],E=g.parentIndex??[],b=g.nodeName??[],x=g.nodeType??[],v=g.pseudoType??{index:[],value:[]},A=g.inputChecked??{index:[]},_=e[c.frameId];for(let w=0;w<h.length;w++){let N=h[w],G=x[w],W=f[w]??[],ye=E[w]!==void 0&&E[w]>=0?E[w]:void 0,Se=ye!==void 0?h[ye]:void 0,Ae=Se!==void 0?a[Se]:void 0,K=v.index.indexOf(w),j=K!==-1?e[v.value[K]]:void 0,le=u[w],Q;le?Q=m[le]??[]:Q=[];let Xe=b[w]!==void 0?e[b[w]]?.toLowerCase():void 0;if(!Xe){s.warn({backendNodeId:N,frameId:_,frameIndex:o,nodeBounds:Q},"DOM node has no tag name");continue}let De={backendNodeId:N,psuedoType:j,nodeType:G,frameIndex:o,parentFrameId:_,ownedFrameId:void 0,bounds:{x:Q[0]??null,y:Q[1]??null,width:Q[2]??null,height:Q[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:Se??null,tagName:Xe,parent:Ae??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};Ae&&Ae.childrenBackendIds.push(N);let Bt=p.index.indexOf(w);if(Bt!==-1){let ke=p.value[Bt];i[ke]=De;let Pe=r[ke]?.frameId;De.ownedFrameId=Pe!==void 0?e[Pe]:void 0}for(let ke of Object.keys(De.bounds)){let Pe=ke;De.bounds[Pe]!==null&&(De.bounds[Pe]/=n)}let Wt=le!==void 0?d[le]??[]:[];for(let ke=0;ke<Wt.length&&!(ke>=t.length);ke++){let Pe=Wt[ke];if(Pe===void 0||isNaN(Pe))continue;let _t=e[Pe];if(_t===void 0)continue;let dt=t[ke];De.computedStyles[dt]=_t}for(let ke=0;ke<W.length;ke+=2){let Pe=W[ke],_t=W[ke+1];if(!Pe||!_t)continue;let dt=e[Pe],qr=e[_t];!dt||!qr||(De.attributes[dt]=qr)}A.index.includes(w)&&(De.attributes.checked="true"),a[De.backendNodeId]=De}return a[h[0]]}function Tg(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=`${Tg(t,e)}${a}`}return r.mPathSelector=n,n}function TC(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var oB=["html","#document","#document-fragment"];function wC({node:r,domGraph:e}){let t=[],n=r,o=TC(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=TC(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++,oB.includes(n.tagName)){i();continue}if(n.tagName==="body")t.push("body");else{let c=!1,l=1;for(let u=0;u<o.childrenBackendIds.length;u++){let d=o.childrenBackendIds[u],m=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else m?.nodeType===1&&!m.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function CC(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 RC(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:be});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:be}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:be})).attributes,i=Fn(o,on);if(!i)throw new Error(`Could not find attribute ${on} for object ${e}`);return i}var aB=["focusable","keyshortcuts","controls","live","relevant","orientation"],sB=["selected","readonly","modal","required","invalid"],lB=["id","name","role","content"],xC=["absolute","fixed","sticky"],cB=["i","label"],uB=["path"],dB=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator","LabelText"],PC=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],IC=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],mB=["menulistpopup","statictext","inlinetextbox"],pB=80,MC=100,OC=50,Cg=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],gB=["cite"],hB={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"]},fB={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},_C={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<OC?t:""),this.role=this.role||(e.domNode.attributes.role??""),EB(this.properties,e.domNode,e.importantProperties)}vB(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&&uB.includes(this.domNode.tagName)||this.ignoredReasons.some(n=>IC.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>UC(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>FC(o,e))||e.styles?.some(o=>{let i=o.split(":");if(i.length!==2)return!1;let a=i[0]?.trim(),s=i[1]?.trim();if(a===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[a];return c!==void 0&&(c===s||s==="*")}))return!0}if(this.domNode&&cB.includes(this.domNode.tagName)||dB.includes(this.role.toLowerCase())||this.domNode?.computedStyles["background-image"]&&this.domNode?.computedStyles["background-image"]!=="none"&&this.children.length===0||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||mr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>kC(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")||this.children.some(n=>n.isIneligible())?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}shouldSerializeBounds(){let e=this.domNode?.computedStyles.position;return!!(e&&(e==="absolute"||e==="fixed"||e==="sticky"))}isIneligible(){return!!(this.domNode?.computedStyles.display==="contents"||this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height))}serialize(e=_C){let t=Object.assign({},_C,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=vg(this.properties),u=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",g=this.name;d==="heading"&&g==="heading"&&(g=""),this.nameSources?.find(A=>!A.superseded&&A.type==="contents")&&this.children.length>0&&(g="");let h=this.nameSources?.find(A=>!A.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let A=h.attributeValue?.relatedNodes??[];A.length===1&&A[0].text&&A[0].text===g&&(g="")}let f=Cg.includes(this.role)||gB.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${g}
|
|
4222
4222
|
`;let E=`${u}<${m}`;!a&&!f&&(E+=` id="${this.id}"`);let b=s??!1;if((l.multiline||l.contenteditable)&&this.children.length>0&&(b=!0),d&&d!=="generic"&&d!==m&&!(hB[d]??[]).includes(m)&&(E+=` role=${JSON.stringify(d)}`),g&&(E+=` name=${JSON.stringify(g)}`),this.content&&!b&&(E+=` content=${JSON.stringify(this.content)}`),this.flagNotActionableNodes&&this.tagName!=="#document"&&this.isIneligible()&&(E+=` ${mr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let A=this.domNode.bounds,_=Math.round(A.x??0),w=Math.round(A.y??0),N=Math.round((A.x??0)+(A.width??0)),G=Math.round((A.y??0)+(A.height??0));E+=` bounds=[${_} ${w} ${N} ${G}]`}let x=Date.now();if(Object.keys(l).length>0&&!i){if(Date.now()-x>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(l).forEach(([A,_])=>{if(!aB.includes(A)){{if(sB.includes(A)&&(!_||_==="false"))return;if(A==="value"&&b&&(l.type==="text"||this.role==="textbox"))return;if(A==="level"&&`${_}`=="1")return;if(A==="url"&&l.src&&m==="img")return;if(A==="url"&&l.href&&m==="a")return;if(A==="editable"&&_==="plaintext")return;if(A==="type"&&_===m)return;if(c&&!fB[A])return}typeof _=="string"?E+=` ${A}="${gt(_,MC,!0)}"`:typeof _=="boolean"?_?E+=` ${A}`:E+=` ${A}={false}`:typeof _<"u"&&(E+=` ${A}={${gt(JSON.stringify(_),MC,!0)}}`)}})}if(m==="::before"||m==="::after"){let A="";for(let _ of this.children)A+=_.serialize({...e,indentLevel:n,neighbors:0});return A}let v=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||v)E+=` />
|
|
4223
4223
|
`;else{let A="";for(let w of this.children)A+=w.serialize({...e,indentLevel:n+2,neighbors:0});let _=A.trim();_.length<=pB&&!_.includes(`
|
|
4224
4224
|
`)?E+=`>${_}</${m}>
|
|
@@ -4226,7 +4226,7 @@ ${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="Th
|
|
|
4226
4226
|
${A}${u}</${m}>
|
|
4227
4227
|
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let A=this.parent.children.findIndex(N=>N.id===this.id),_=A>0?this.parent.children[A-1]?.serialize({...e,neighbors:0}):"",w=A<this.parent.children.length-1?this.parent.children[A+1]?.serialize({...e,neighbors:0}):"";return`${_||""}
|
|
4228
4228
|
${E}
|
|
4229
|
-
${w||""}`}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:vg(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=vg(this.properties),e}},wg=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 l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let m=a(d);m&&(u.push(m),m.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(t);return new r(s,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 s=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let m of l){let g=n(m,s||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,s||u)return c;if(Cg.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=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,l)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:l,noChildren:!0});return o.set(c,u),u},a=(c,l,u)=>{let d=c.shallowClone();d.children=[];let m=i(c,l).length;if(u<=m)return{clone:d,used:m};if(n(c)||c.children.length===0)return{clone:d,used:m};let g=m,p=u-g;for(let h of c.children){let f=l+2,E=i(h,f).length;if(p<E)break;let{clone:b,used:x}=a(h,f,p);if(x>p)break;d.children.push(b),b.parent=d,g+=x,p-=x}return{clone:d,used:g}},{clone:s}=a(t,0,Math.max(1e4,e));return new r(s,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function SB(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 yB(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?(Rl({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?(Rl({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 LC({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:s,showZeroOpacityElements:c,filterByViewport:l,viewportDetails:u,useMPaths:d,importantProperties:m,allowedA11yIgnoreReasonsOverride:g,cdpClient:p,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(j,le={})=>{},b=r.backendDOMNodeId,x=mB.includes(r.role?.value?.toLowerCase()??"");if(!x&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let v=b?i.backendIdToNode[b]:void 0;if(!x&&!v)try{let j=await k(p.send({method:"DOM.describeNode",params:{backendNodeId:b}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(j&&j.node.nodeName.toLowerCase()==="slot"&&j.node.distributedNodes?.length)h.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:j},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:j}),[]}catch(j){return E("Filtering out node since it doesn't exist in the DOM",{err:j}),[]}if(v&&e&&l&&u&&r.backendDOMNodeId&&!yB(v,u,h,f))return v.momenticIgnored=!0,[];if(v&&v.computedStyles.display==="none")return v.momenticIgnored=!0,[];if(v&&v.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&v.tagName.toLowerCase()!=="input")return v.momenticIgnored=!0,[];if(c===!1)return v.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",_=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new Ag({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:_,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(j=>(g??PC).includes(j.name)||IC.includes(j.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+SB(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:m,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),N=n,G=a[t],W=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let j=n.childFrames.find(Xe=>Xe.frameId===v.ownedFrameId),le=o[j?.frameId??""]?.root,Q=a[j?.frameId??""];if(j&&le&&Q){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Xe=le;r.childIds=Xe.childIds,N=j,G=Q,W=j.frameId}}let ye=v?.childrenBackendIds?.length??0,Se=(r.childIds??[]).filter(j=>!!G.get(parseInt(j))).length;if(ye>Se){let j=r.childIds?.map(Q=>G.get(parseInt(Q))).filter(Boolean).map(Q=>Q?.backendDOMNodeId).filter(Q=>Q!==void 0)??[],le=0;for(let Q of v?.childrenBackendIds??[]){if(j.includes(Q)){le=(r.childIds?.findIndex(ke=>G.get(parseInt(ke))?.backendDOMNodeId===Q)??0)+1;continue}let Xe=i.backendIdToNode[Q];if(!Xe||Xe?.tagName.toLowerCase()!=="svg")continue;let De=Math.floor(-1*Math.random()*1e7),Bt={nodeId:De.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:Q,frameId:W,role:{type:"string",value:"graphics-symbol"}};G.set(De,Bt),r.childIds||(r.childIds=[]),r.childIds.splice(le,0,De.toString()),le++}}if(r.childIds?.length===1&&v){let j=G.get(parseInt(r.childIds[0])),le=j?.role?.value,Q=v.childrenBackendIds;if(j&&le==="StaticText"&&Q.length===1){let Xe=i.backendIdToNode[Q[0]];if(Xe?.tagName?.toLowerCase()==="span"){let De=Math.floor(-1*Math.random()*1e7).toString(),Bt={nodeId:De,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Xe.backendNodeId,frameId:W,childIds:[j.nodeId]};j.parentId=De,G.set(parseInt(De),Bt),r.childIds=[De]}}}for(let j of r.childIds??[]){if(!j)continue;let le=G.get(parseInt(j));if(!le)continue;let Q=await LC({node:le,parent:w,domGraph:i,axGraph:o,frameId:W,frameContext:N,inputNodeMap:a,cdpClient:p,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:m,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});Q.length&&(w.children=w.children.concat(Q))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let j=w.name,le=w.children[0]?.name;(j===le||!le)&&(w.children=[])}let Ae=[];for(let j=w.children.length-1;j>=0;j--){let le=w.children[j];if(le.role!=="StaticText"){Ae.push(le);continue}if(j===0||w.children[j-1].role!=="StaticText"){Ae.push(le);continue}w.children[j-1].name+=le.name}if(w.children=Ae.reverse(),!w.isInteresting(m)&&r.parentId)return v&&(v.momenticIgnored=!0),w.children;for(let j of w.children)j.parent=w;return TB(w),v&&d&&Tg(v,i),[w]}function NC({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){r.id=l,l+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:Cg.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let m=Eg(d,i),g=m?c[m.hash]:void 0,p=g?g.description:void 0;g&&(r.properties["data-momentic-description"]=p)}for(let m of r.children)l=NC({node:m,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function DC({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:m,allowedA11yIgnoreReasonsOverride:g}){let p=t??"root",h=r[p]?.root;if(!h)throw new Error("A11y tree has no root");let f=iB(),E=w=>{let N=w.allNodes.filter(W=>!W.ignoredReasons?.find(Se=>(g??PC).includes(Se.name))),G=new Map;return N.forEach(W=>{G.set(parseInt(W.nodeId),W)}),G},b={};Object.entries(r).forEach(([w,N])=>{b[w]=E(N)});let x=await LC({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:p,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:g});if(x.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(x)}`);if(x.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},A={},_={};return NC({node:x[0],a11yIdNodeMap:v,dataMomenticIdMap:A,selectorToNodeMap:_,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:m}),new wg(x[0],v,A,_)}function bB(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<OC&&!mr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(kC(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 EB(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||lB.includes(a);if((mr.relevantElementAttributes.includes(a)||UC(a,t))&&!c){let u=bB(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&xC.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of xC)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 s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],m=`${c}: ${d}`;o.includes(m)||o.push(m)}}o.length>0&&(r.style=o.join("; "))}function TB(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(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(gt(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of r.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let g=u.children.filter(p=>p.tagName==="th");if(g.length){if(i=g.map(p=>gt(p.name,100,!1)),i.length===g.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(g=>g.tagName==="td"||g.tagName==="th"),m=d.length===i?.length;d.forEach((g,p)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=p+1),m&&(g.properties.col||(g.properties.col=i[p])))})}}}function vB(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function kC(r,e){if(e&&FC(r,e))return!0;if(mr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(mr.alwaysInterestingClassNames.includes(r))return!0;for(let t of mr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function UC(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 FC(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(),s,c;for(let u=0;u<2;u++)try{s=await k(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new R("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await q(ct),c=d}if(!s)throw c;let l=new r(s,e,t,n,o);try{await k(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new R("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}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 Promise.all([e.send("Accessibility.enable"),e.send("Page.enable"),e.send("DOM.enable"),e.send("Overlay.enable"),e.send("DOMSnapshot.enable"),e.send("CSS.enable")])}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await k(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new R("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 k(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 k(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new R("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 k(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 k(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 xi="<empty>";function AB(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 HC(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||AB(r.url)}async function wB(r,e){let t=await r.send({timeout:ee,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:ee,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:ee,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Mi({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:Ci,method:"Page.getFrameTree",params:{}}),r.send({timeout:Ci,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,m)=>{if(HC(d.frame))return null;try{return await GC({cdpClient:r,rawFrameTree:d,indices:[m],parent:n,warnings:o,logger:t})}catch(g){return o.push(`Failed to get child frame: ${g}`),null}}),u=await Promise.all(l);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function GC({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await wB(r,a),c=s.attributes??[],l=null,u=[];for(let p of["src","name","id","title","srcdoc","sandbox"]){let h=Fn(c,p);h&&(u.push(`${p}=${JSON.stringify(h)}`),p==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},g=(e.childFrames??[]).map(async(p,h)=>{if(HC(p.frame))return null;try{return await GC({cdpClient:r,rawFrameTree:p,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(g)).filter(p=>p!==null),d}async function CB(r){try{return await r.owner().count()===1}catch{return!1}}async function RB(r){try{return await r.count()===1}catch{return!1}}async function Vr(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 l of t){let u=!1;for(let d of[...l.locationData.attributeSelectors,xi]){let m=o.frameLocator(d===xi?"iframe":`iframe[${d}]`);if(await CB(m)){u=!0,o=m,i.push(d);break}}if(!u)throw new R("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...r.locationData.attributeSelectors,xi]){let u=o.locator(l===xi?"iframe":`iframe[${l}]`);if(await RB(u)){a=u,i.push(l);break}}if(!a)throw new R("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 s=await a.evaluateHandle(l=>l,{timeout:te}),c=await s.asElement().contentFrame();if(!c)throw new R("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function BC(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 VC({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===xi?s=s.length===1?s[0].childFrames:[]:s=s.filter(m=>m.locationData.attributeSelectors.includes(d)).map(m=>m.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===xi?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Vr(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 s=new RegExp(t.frameSrcRegex),c=BC(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Vr(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 s=new RegExp(t.frameUrlRegex),c=BC(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Vr(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 s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.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 Vr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Pr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function Zc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Rg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function WC(r){let e=Rg(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function jC(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 $C({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await xB({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 xB({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await ss({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 s=Date.now();for(;Date.now()-s<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(l=>setTimeout(l,250))}}),timeoutMs:be,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}import{create as MB,windowedFiniteBatchScheduler as _B}from"@yornaath/batshit";import{reduce as PB}from"lodash-es";var IB=100,OB=2e3;function qC(r){return MB({fetcher:async t=>{r(PB(t,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:_B({windowMs:OB,maxBatchSize:IB})})}async function KC({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=r.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(p=>p.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let m,g;if(l)try{let p=await n.frameElement();m=await k(p?.boundingBox(),{milliseconds:ee})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)g={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(p){i.warn({err:p},"Failed to construct iframe details for recorded action, using hardcoded URL only"),g={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:g,frameBoundingBox:m})}catch(p){i.error({err:p},"Failed to transform passive click action")}})()}import{randomUUID as Wr}from"crypto";import LB from"js-beautify";var NB=["Dead"],eu=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:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Wr(),type:"PRESET_ACTION",command:Kr(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,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={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"):l=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Kr(i);a={id:Wr(),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:l}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Kr(i);a={id:Wr(),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:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Kr(i);a={id:Wr(),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:fe(this.logger),boundingBox:l}}}};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=LB.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Lw(d,"data-momentic-interacted",4e4)}catch{}let m;try{m=(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,...fe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=s}let g=this.recordedSteps.get(u)?.step??a,p=g?.command;p&&"target"in p&&p.target?(p.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...g,command:p},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(NB.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Kr("TYPE");i={id:Wr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Kr("PRESS");i={id:Wr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,m=i.command.value;i={id:Wr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${m}`:`${d}${m}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:Wr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}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,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Kr(l);u.deltaY=Math.abs(i);let d={id:Wr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Kr(l);u.deltaX=Math.abs(i);let d={id:Wr(),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 xg}from"zod";var gve=xg.object({type:xg.literal("url"),url:xg.string()});var tu=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position","background-image"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let m of this.userControlledBrowserSettings.importantStyles){let g=m.split(":");if(g.length!==2){this.logger.warn({style:m},"Invalid style property passed to importantStyles");continue}let p=g[0]?.trim(),h=g[1]?.trim();if(p===void 0||h===void 0){this.logger.warn({style:m},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(p)||this.computedStylesToFetch.push(p)}}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.userControlledBrowserSettings.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=Rg(e),{frame:o,mPathSelectorTokens:i}=await Vr(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 Mi({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await VC({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 $C({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Mi({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[k(n.evaluate(e,t),{milliseconds:be})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(Vr(c,n).then(({frame:u})=>k(u.evaluate(e,t),{milliseconds:be})).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 Mi({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,s,c=null;if(this.frameConfig?.type==="url"){if(a=await pr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new R("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await pr({fn:()=>Mi({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);await pr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let l=await pr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await pr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await pr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:l,startingFrameId:c,frameContext:s,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(m=>m>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=l,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:Cn,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.userControlledBrowserSettings.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=wC({node:o,domGraph:this.domGraph});return CC(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:be});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await RC(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(vr(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,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Mi({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(l){if(s=l,l instanceof R&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await q(ct,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Zc(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=Fn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await Vr(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Vr(s,o)});break}}}if(a.length===1){let s=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new R("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await DC({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});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.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await Vr(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...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await it({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:be,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(Fn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Fn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:ee,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:ee,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:ee,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 s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(g){i.warn({err:g},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,l;for(let g=0;g<3;g++)try{l=await pr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(p){c=p,i.warn({err:p},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),m=[];for(;d.length>0;){let g=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:g,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${g.frameId} with url ${g.url}, allowing it to be fetched: ${h}`)}d.push(...g.childFrames);let p=async()=>{try{let h=await pr({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,logger:i});u[g.frameId]=h}catch(h){i.warn({err:h,url:g.url,src:g.src},`Error getting raw a11y tree for child frame ${g.frameId}, continuing...`)}};m.push(p())}return await Promise.all(m),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await pr({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,logger:this.logger})).nodes;else{let a=(await pr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:be}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await pr({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,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:ee}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await q(ct,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new R("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 AC({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=WC(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 ds=class r{static USER_AGENT=jc;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;pageLoadAbortControllers=new Set;pageLoadAbortListenerCleanup;clientCallbacks;harBatcher;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[]};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:m,onVideoPageChange:g}){Zb(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,this.iconKnowledgeBase=m,this.onVideoPageChange=g}registerAbortSignal(e){if(this.pageLoadAbortListenerCleanup&&(this.pageLoadAbortListenerCleanup(),this.pageLoadAbortListenerCleanup=void 0),this.abortSignal=e,!this.abortSignal)return;let t=()=>{for(let n of this.pageLoadAbortControllers)n.abort();this.pageLoadAbortControllers.clear()};if(this.abortSignal.aborted){t();return}this.abortSignal.addEventListener("abort",t),this.pageLoadAbortListenerCleanup=()=>{this.abortSignal?.removeEventListener("abort",t)}}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Vc]:this.userBrowserSettings.visualActions},i=[];if(this.userControlledBrowserSettings.extraHeaders&&i.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e){let u=["clipboard-read","clipboard-write","microphone","camera","geolocation"];Lr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:`${qp.htmlUtilsLibJs}
|
|
4229
|
+
${w||""}`}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:vg(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=vg(this.properties),e}},wg=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 l=c.shallowClone();if(e[c.id])return l.properties["data-momentic-summary"]=e[c.id],n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l;let u=[];for(let d of c.children){let m=a(d);m&&(u.push(m),m.parent=l)}return l.children=u,n[c.id]=l,c.dataMomenticId&&(o[c.dataMomenticId]=l),c.mPathSelector&&(i[c.mPathSelector]=l),l},s=a(t);return new r(s,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 s=e.has(`${i.id}`)||i.id===t?.id,c=i.shallowClone(),l=i.children,u=!1,d=[];for(let m of l){let g=n(m,s||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,s||u)return c;if(Cg.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=c=>c.role==="StaticText"||c.role==="ListMarker",o=new WeakMap,i=(c,l)=>{if(o.has(c))return o.get(c);let u=c.serialize({indentLevel:l,noChildren:!0});return o.set(c,u),u},a=(c,l,u)=>{let d=c.shallowClone();d.children=[];let m=i(c,l).length;if(u<=m)return{clone:d,used:m};if(n(c)||c.children.length===0)return{clone:d,used:m};let g=m,p=u-g;for(let h of c.children){let f=l+2,E=i(h,f).length;if(p<E)break;let{clone:b,used:x}=a(h,f,p);if(x>p)break;d.children.push(b),b.parent=d,g+=x,p-=x}return{clone:d,used:g}},{clone:s}=a(t,0,Math.max(1e4,e));return new r(s,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function SB(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 yB(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?(Rl({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?(Rl({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 LC({node:r,parent:e,frameId:t,frameContext:n,axGraph:o,domGraph:i,inputNodeMap:a,flagNotActionableNodes:s,showZeroOpacityElements:c,filterByViewport:l,viewportDetails:u,useMPaths:d,importantProperties:m,allowedA11yIgnoreReasonsOverride:g,cdpClient:p,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(j,le={})=>{},b=r.backendDOMNodeId,x=mB.includes(r.role?.value?.toLowerCase()??"");if(!x&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let v=b?i.backendIdToNode[b]:void 0;if(!x&&!v)try{let j=await k(p.send({method:"DOM.describeNode",params:{backendNodeId:b}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(j&&j.node.nodeName.toLowerCase()==="slot"&&j.node.distributedNodes?.length)h.debug({redirectedDomNode:v,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:j},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:j}),[]}catch(j){return E("Filtering out node since it doesn't exist in the DOM",{err:j}),[]}if(v&&e&&l&&u&&r.backendDOMNodeId&&!yB(v,u,h,f))return v.momenticIgnored=!0,[];if(v&&v.computedStyles.display==="none")return v.momenticIgnored=!0,[];if(v&&v.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&v.tagName.toLowerCase()!=="input")return v.momenticIgnored=!0,[];if(c===!1)return v.momenticIgnored=!0,[]}let A=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",_=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new Ag({domNode:v,id:parseInt(r.nodeId),role:r.role?.value||"",name:A,nameSources:r.name?.sources,content:_,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(j=>(g??PC).includes(j.name)||IC.includes(j.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+SB(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:m,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),N=n,G=a[t],W=t;if(v?.tagName.toLowerCase()==="iframe"&&v.ownedFrameId){let j=n.childFrames.find(Xe=>Xe.frameId===v.ownedFrameId),le=o[j?.frameId??""]?.root,Q=a[j?.frameId??""];if(j&&le&&Q){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Xe=le;r.childIds=Xe.childIds,N=j,G=Q,W=j.frameId}}let ye=v?.childrenBackendIds?.length??0,Se=(r.childIds??[]).filter(j=>!!G.get(parseInt(j))).length;if(ye>Se){let j=r.childIds?.map(Q=>G.get(parseInt(Q))).filter(Boolean).map(Q=>Q?.backendDOMNodeId).filter(Q=>Q!==void 0)??[],le=0;for(let Q of v?.childrenBackendIds??[]){if(j.includes(Q)){le=(r.childIds?.findIndex(ke=>G.get(parseInt(ke))?.backendDOMNodeId===Q)??0)+1;continue}let Xe=i.backendIdToNode[Q];if(!Xe||Xe?.tagName.toLowerCase()!=="svg")continue;let De=Math.floor(-1*Math.random()*1e7),Bt={nodeId:De.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:Q,frameId:W,role:{type:"string",value:"graphics-symbol"}};G.set(De,Bt),r.childIds||(r.childIds=[]),r.childIds.splice(le,0,De.toString()),le++}}if(r.childIds?.length===1&&v){let j=G.get(parseInt(r.childIds[0])),le=j?.role?.value,Q=v.childrenBackendIds;if(j&&le==="StaticText"&&Q.length===1){let Xe=i.backendIdToNode[Q[0]];if(Xe?.tagName?.toLowerCase()==="span"){let De=Math.floor(-1*Math.random()*1e7).toString(),Bt={nodeId:De,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Xe.backendNodeId,frameId:W,childIds:[j.nodeId]};j.parentId=De,G.set(parseInt(De),Bt),r.childIds=[De]}}}for(let j of r.childIds??[]){if(!j)continue;let le=G.get(parseInt(j));if(!le)continue;let Q=await LC({node:le,parent:w,domGraph:i,axGraph:o,frameId:W,frameContext:N,inputNodeMap:a,cdpClient:p,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:m,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});Q.length&&(w.children=w.children.concat(Q))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let j=w.name,le=w.children[0]?.name;(j===le||!le)&&(w.children=[])}let Ae=[];for(let j=w.children.length-1;j>=0;j--){let le=w.children[j];if(le.role!=="StaticText"){Ae.push(le);continue}if(j===0||w.children[j-1].role!=="StaticText"){Ae.push(le);continue}w.children[j-1].name+=le.name}if(w.children=Ae.reverse(),!w.isInteresting(m)&&r.parentId)return v&&(v.momenticIgnored=!0),w.children;for(let j of w.children)j.parent=w;return TB(w),v&&d&&Tg(v,i),[w]}function NC({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){r.id=l,l+=1,e[r.id]=r,r.dataMomenticId?t[r.dataMomenticId]=r:Cg.includes(r.role);let u=r.backendNodeId,d=u!==void 0?i.backendIdToNode[u]:void 0;if(a&&d&&d.mPathSelector&&(s[d.mPathSelector]=r,r.mPathSelector=d.mPathSelector),c&&d&&d.tagName?.toLowerCase()==="svg"){let m=Eg(d,i),g=m?c[m.hash]:void 0,p=g?g.description:void 0;g&&(r.properties["data-momentic-description"]=p)}for(let m of r.children)l=NC({node:m,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function DC({rawA11yGraph:r,domGraph:e,startingFrameId:t,logger:n,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,flagNotActionableNodes:s,importantProperties:c,viewportDetails:l,useMPaths:u,frameContext:d,iconKnowledgeBase:m,allowedA11yIgnoreReasonsOverride:g}){let p=t??"root",h=r[p]?.root;if(!h)throw new Error("A11y tree has no root");let f=iB(),E=w=>{let N=w.allNodes.filter(W=>!W.ignoredReasons?.find(Se=>(g??PC).includes(Se.name))),G=new Map;return N.forEach(W=>{G.set(parseInt(W.nodeId),W)}),G},b={};Object.entries(r).forEach(([w,N])=>{b[w]=E(N)});let x=await LC({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:p,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:g});if(x.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(x)}`);if(x.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let v={},A={},_={};return NC({node:x[0],a11yIdNodeMap:v,dataMomenticIdMap:A,selectorToNodeMap:_,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:m}),new wg(x[0],v,A,_)}function bB(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<OC&&!mr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(kC(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 EB(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||lB.includes(a);if((mr.relevantElementAttributes.includes(a)||UC(a,t))&&!c){let u=bB(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&xC.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of xC)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 s=a.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),u=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&u!==void 0&&(l==="*"||u===l)){let d=e.computedStyles[c],m=`${c}: ${d}`;o.includes(m)||o.push(m)}}o.length>0&&(r.style=o.join("; "))}function TB(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(l=>l.tagName==="tr");if(c){let l=c.children.filter(u=>u.tagName==="th");l.forEach((u,d)=>{u.properties["col-index"]||(u.properties["col-index"]=d+1),i?.push(gt(u.name,100,!1))}),i?.length!==l.length&&(i=void 0)}}let s=0;for(let c of r.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let u=c.children[l];if(u.tagName!=="tr")continue;if(l===0&&!i?.length){let g=u.children.filter(p=>p.tagName==="th");if(g.length){if(i=g.map(p=>gt(p.name,100,!1)),i.length===g.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(g=>g.tagName==="td"||g.tagName==="th"),m=d.length===i?.length;d.forEach((g,p)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=p+1),m&&(g.properties.col||(g.properties.col=i[p])))})}}}function vB(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function kC(r,e){if(e&&FC(r,e))return!0;if(mr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(mr.alwaysInterestingClassNames.includes(r))return!0;for(let t of mr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function UC(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 FC(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(),s,c;for(let u=0;u<2;u++)try{s=await k(i.newCDPSession(a),{milliseconds:o*u,fallback:()=>{throw new R("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await q(ct),c=d}if(!s)throw c;let l=new r(s,e,t,n,o);try{await k(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(u){throw l.cdpFullyDead=!0,new R("UserInfrastructureError",`Failed to initialize CDP client: ${u}`)}return l}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 Promise.all([e.send("Accessibility.enable"),e.send("Page.enable"),e.send("DOM.enable"),e.send("Overlay.enable"),e.send("DOMSnapshot.enable"),e.send("CSS.enable")])}async send({method:e,params:t,timeout:n=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await k(this.cdpInitializingPromise,{milliseconds:n});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new R("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 k(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 k(this.contextGetter().newCDPSession(n),{milliseconds:t,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${n.url()})`),new R("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 k(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 k(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 xi="<empty>";function AB(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 HC(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||AB(r.url)}async function wB(r,e){let t=await r.send({timeout:ee,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:ee,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:ee,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function Mi({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:Ci,method:"Page.getFrameTree",params:{}}),r.send({timeout:Ci,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,m)=>{if(HC(d.frame))return null;try{return await GC({cdpClient:r,rawFrameTree:d,indices:[m],parent:n,warnings:o,logger:t})}catch(g){return o.push(`Failed to get child frame: ${g}`),null}}),u=await Promise.all(l);return n.childFrames=u.filter(d=>d!==null),o.length&&t?.warn({warnings:o},"Got warnings when fetching frame tree"),n}async function GC({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await wB(r,a),c=s.attributes??[],l=null,u=[];for(let p of["src","name","id","title","srcdoc","sandbox"]){let h=Fn(c,p);h&&(u.push(`${p}=${JSON.stringify(h)}`),p==="src"&&(l=h))}let d={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:t,attributeSelectors:u},src:l,childFrames:[],parent:n,domNode:s},g=(e.childFrames??[]).map(async(p,h)=>{if(HC(p.frame))return null;try{return await GC({cdpClient:r,rawFrameTree:p,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(g)).filter(p=>p!==null),d}async function CB(r){try{return await r.owner().count()===1}catch{return!1}}async function RB(r){try{return await r.count()===1}catch{return!1}}async function Vr(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 l of t){let u=!1;for(let d of[...l.locationData.attributeSelectors,xi]){let m=o.frameLocator(d===xi?"iframe":`iframe[${d}]`);if(await CB(m)){u=!0,o=m,i.push(d);break}}if(!u)throw new R("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let l of[...r.locationData.attributeSelectors,xi]){let u=o.locator(l===xi?"iframe":`iframe[${l}]`);if(await RB(u)){a=u,i.push(l);break}}if(!a)throw new R("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 s=await a.evaluateHandle(l=>l,{timeout:te}),c=await s.asElement().contentFrame();if(!c)throw new R("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function BC(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 VC({page:r,frameTree:e,cache:t}){let n,o=e.childFrames,i=[];if(t.mPathSelectorTokens.length){let s=o;for(let u=0;u<t.mPathSelectorTokens.length-1;u++){let d=t.mPathSelectorTokens[u];d===xi?s=s.length===1?s[0].childFrames:[]:s=s.filter(m=>m.locationData.attributeSelectors.includes(d)).map(m=>m.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===xi?c=s:c=s.filter(u=>u.locationData.attributeSelectors.includes(l)),c.length===1)return n=c[0],i.push(`Found unique frame with mpath ${t.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Vr(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 s=new RegExp(t.frameSrcRegex),c=BC(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return n=c[0],i.push(`Found unique frame with src regex ${t.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Vr(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 s=new RegExp(t.frameUrlRegex),c=BC(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return n=c[0],i.push(`Found unique frame with url regex ${t.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Vr(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 s=0;s<t.indices.length-1;s++)a=a[t.indices[s]]?.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 Vr(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Pr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function Zc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function Rg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function WC(r){let e=Rg(r),t=r.src??"",n=r.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:t,desiredUrl:n}}function jC(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 $C({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await xB({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 xB({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await ss({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 s=Date.now();for(;Date.now()-s<1e3;){let c=i.scrollTop;if(c===a)break;a=c,await new Promise(l=>setTimeout(l,250))}}),timeoutMs:be,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}import{create as MB,windowedFiniteBatchScheduler as _B}from"@yornaath/batshit";import{reduce as PB}from"lodash-es";var IB=100,OB=2e3;function qC(r){return MB({fetcher:async t=>{r(PB(t,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:_B({windowMs:OB,maxBatchSize:IB})})}async function KC({event:r,transformer:e,enricher:t,frame:n,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:c}=r.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!c)return;let l=n.parentFrame()?n.url():void 0,d=n.page().frames().map(p=>p.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let m,g;if(l)try{let p=await n.frameElement();m=await k(p?.boundingBox(),{milliseconds:ee})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)g={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(p){i.warn({err:p},"Failed to construct iframe details for recorded action, using hardcoded URL only"),g={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:g,frameBoundingBox:m})}catch(p){i.error({err:p},"Failed to transform passive click action")}})()}import{randomUUID as Wr}from"crypto";import LB from"js-beautify";var NB=["Dead"],eu=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:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),t.onActionReceived?.(s,c)}},this.generator=n}reserveIndexForCommand(e){let t=this.nextStepOffset;return this.recordedSteps.set(t,{step:{id:Wr(),type:"PRESET_ACTION",command:Kr(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,s=n.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={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"):l=n.properties.boundingBox,t){case"CLICK":{i="CLICK";let h=Kr(i);a={id:Wr(),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:l}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Kr(i);a={id:Wr(),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:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Kr(i);a={id:Wr(),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:fe(this.logger),boundingBox:l}}}};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=LB.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=Lw(d,"data-momentic-interacted",4e4)}catch{}let m;try{m=(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,...fe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=s}let g=this.recordedSteps.get(u)?.step??a,p=g?.command;p&&"target"in p&&p.target?(p.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...g,command:p},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(NB.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Kr("TYPE");i={id:Wr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Kr("PRESS");i={id:Wr(),type:"PRESET_ACTION",command:{...d,value:t}}}let a,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,u=l?.command;if(n){if(u?.type===i.command.type){let d=u.value,m=i.command.value;i={id:Wr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${m}`:`${d}${m}`}},a=s}else if(u?.type==="CLICK"&&i.command.type==="TYPE")l.command={...i.command,target:u.target,cache:u.cache},i=c.step,a=s;else if(u?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let d=u.value;i={id:Wr(),type:"PRESET_ACTION",command:{...u,value:d.slice(0,d.length-1)}},a=s}}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,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,c=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_DOWN":"SCROLL_UP",u=Kr(l);u.deltaY=Math.abs(i);let d={id:Wr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},n=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,c=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,c=a):(c=this.nextStepOffset,this.nextStepOffset++);let l=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",u=Kr(l);u.deltaX=Math.abs(i);let d={id:Wr(),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 xg}from"zod";var hve=xg.object({type:xg.literal("url"),url:xg.string()});var tu=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position","background-image"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;allowedA11yIgnoreReasonsOverride;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:t,allowPartialAccessibilityTree:n,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:u,allowedA11yIgnoreReasonsOverride:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=t,this.allowPartialAccessibilityTree=n,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userControlledBrowserSettings=u,this.allowedA11yIgnoreReasonsOverride=d,this.userControlledBrowserSettings.importantStyles)for(let m of this.userControlledBrowserSettings.importantStyles){let g=m.split(":");if(g.length!==2){this.logger.warn({style:m},"Invalid style property passed to importantStyles");continue}let p=g[0]?.trim(),h=g[1]?.trim();if(p===void 0||h===void 0){this.logger.warn({style:m},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(p)||this.computedStylesToFetch.push(p)}}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.userControlledBrowserSettings.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=Rg(e),{frame:o,mPathSelectorTokens:i}=await Vr(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 Mi({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await VC({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 $C({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await Mi({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[k(n.evaluate(e,t),{milliseconds:be})],a=Array.from(o.childFrames);for(;a.length>0;){let c=a.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(a.push(...c.childFrames),i.push(Vr(c,n).then(({frame:u})=>k(u.evaluate(e,t),{milliseconds:be})).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 Mi({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,s,c=null;if(this.frameConfig?.type==="url"){if(a=await pr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new R("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await pr({fn:()=>Mi({cdpClient:this.cdpClient,page:this.pageGetter(),logger:n}),codePath:"getMomenticFrameTree",logObject:t,signal:o,logger:n}),c=null):(s={type:"root",page:i,childFrames:[]},c=null);await pr({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:n}),codePath:"addIdsToElement",logObject:t,signal:o,logger:n});let l=await pr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await pr({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:t,logger:n,signal:o}),codePath:"totalA11yFetch",logObject:t,signal:o,logger:n}),{tree:d}=await pr({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:u,domGraph:l,startingFrameId:c,frameContext:s,logger:n,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements,flagNotActionableNodes:e.flagNotActionableNodes}),codePath:"a11yProcess",logObject:t,signal:o,logger:n});return Object.values(t).some(m=>m>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=l,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:Cn,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.userControlledBrowserSettings.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=wC({node:o,domGraph:this.domGraph});return CC(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:be});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await RC(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(vr(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,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await Mi({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(l){if(s=l,l instanceof R&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await q(ct,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Zc(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,t){let n=t.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),c=s.domNode;i.push(...s.childFrames);let l=Fn(c.attributes??[],"src"),u=c.contentDocument?.documentURL;if(!l&&!u){this.logger.debug("Skipping frame with no URL or src");continue}for(let d of[l,u])if(d){if(n.startsWith("/")&&n.endsWith("/")){if(new RegExp(n.slice(1,-1)).test(d)){a.push({handle:s,matchType:"regex",...await Vr(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Vr(s,o)});break}}}if(a.length===1){let s=a[0];return this.userControlledBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${n}'. Please use a more specific selector.`):new R("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await DC({rawA11yGraph:t,startingFrameId:o,frameContext:i,domGraph:n,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:c,flagNotActionableNodes:l,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userControlledBrowserSettings.visualActions,allowedA11yIgnoreReasonsOverride:this.allowedA11yIgnoreReasonsOverride});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.userControlledBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(n??e,1);if(!this.userControlledBrowserSettings.autoExpandIframes||n)return;let a=Array.from(t),s=[];for(;a.length>0;){let c=a.shift();a.push(...c.childFrames);let l=async()=>{try{let{frame:u}=await Vr(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...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,t){if(this.userControlledBrowserSettings.visualActions)return t;let n=this.logger;return await it({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:be,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(Fn(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=Fn(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:ee,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:ee,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:ee,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 s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(g){i.warn({err:g},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,l;for(let g=0;g<3;g++)try{l=await pr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(p){c=p,i.warn({err:p},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let u={};if(u[t??"root"]=l,!this.userControlledBrowserSettings.autoExpandIframes)return u;let d=Array.from(n),m=[];for(;d.length>0;){let g=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:g,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${g.frameId} with url ${g.url}, allowing it to be fetched: ${h}`)}d.push(...g.childFrames);let p=async()=>{try{let h=await pr({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,logger:i});u[g.frameId]=h}catch(h){i.warn({err:h,url:g.url,src:g.src},`Error getting raw a11y tree for child frame ${g.frameId}, continuing...`)}};m.push(p())}return await Promise.all(m),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),u}async getRawA11yTreeForFrame({frameId:e,timeoutMs:t,logTimings:n}){let o;if(this.allowPartialAccessibilityTree)o=(await pr({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,logger:this.logger})).nodes;else{let a=(await pr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:be}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await pr({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,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:ee}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await q(ct,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new R("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 AC({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=WC(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 ds=class r{static USER_AGENT=jc;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;pageLoadAbortControllers=new Set;pageLoadAbortListenerCleanup;clientCallbacks;harBatcher;iconKnowledgeBase;cdpClient;debugData={logsPerPage:[]};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;onVideoPageChange;baseUrl;constructor({storage:e,enricher:t,browser:n,context:o,page:i,baseUrl:a,logger:s,userBrowserSettings:c,viewport:l,properties:u,clientCallbacks:d,iconKnowledgeBase:m,onVideoPageChange:g}){Zb(c),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.page=i,this.baseUrl=a,this.logger=s,this.userControlledBrowserSettings=c,this.viewport=l,this.properties=u,this.clientCallbacks=d,this.iconKnowledgeBase=m,this.onVideoPageChange=g}registerAbortSignal(e){if(this.pageLoadAbortListenerCleanup&&(this.pageLoadAbortListenerCleanup(),this.pageLoadAbortListenerCleanup=void 0),this.abortSignal=e,!this.abortSignal)return;let t=()=>{for(let n of this.pageLoadAbortControllers)n.abort();this.pageLoadAbortControllers.clear()};if(this.abortSignal.aborted){t();return}this.abortSignal.addEventListener("abort",t),this.pageLoadAbortListenerCleanup=()=>{this.abortSignal?.removeEventListener("abort",t)}}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Vc]:this.userBrowserSettings.visualActions},i=[];if(this.userControlledBrowserSettings.extraHeaders&&i.push(this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders)),e){let u=["clipboard-read","clipboard-write","microphone","camera","geolocation"];Lr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:`${qp.htmlUtilsLibJs}
|
|
4230
4230
|
//# sourceURL=momentic-injected/browser-scripts.js`}),this.context.addInitScript({content:hg(o,this.userBrowserSettings.disableFullStory)}),this.exposeRecordingBindings());let a=u=>this.handleNewPageEvent(u);this.context.on("page",a),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",a)});let s=!1;if(t){let u=async()=>{let d=Date.now();try{await Promise.all([this.page.addScriptTag({content:`${qp.htmlUtilsLibJs}
|
|
4231
4231
|
//# sourceURL=momentic-injected/browser-scripts.js`}),this.page.addScriptTag({content:hg(o,this.userBrowserSettings.disableFullStory)})])}catch(m){if(m instanceof Error&&m.message.includes("Content Security Policy"))this.logger.warn({err:m},"Content Security Policy error from adding Momentic scripts, reloading page instead"),s=!0;else throw m}(n??{})["add-init-scripts"]=Date.now()-d};i.push(u())}if(!this.properties.systemDevicePixelRatio)if(process.env.MOMENTIC_LOCAL_DEV==="1"&&HB()==="darwin"&&DB("system_profiler SPDisplaysDataType").toString().includes("Retina"))C.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2;else{let u=async()=>{let d=Date.now();this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio),(n??{})["fetch-dpr"]=Date.now()-d};i.push(u())}let c=Date.now();await k(Promise.all(i),{milliseconds:this.pageLoadTimeout,message:"Timed out attaching Chrome permissions and initialization scripts",signal:this.abortSignal});let l=Date.now();(n??{})["ops-attach"]=l-c,s&&await this.page.reload(),this.cdpClient=await Qc.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),(n??{})["cdp-init"]=Date.now()-l,await this.initializeScreencast(),this.stateManager=new tu({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings,allowedA11yIgnoreReasonsOverride:this.properties.allowedA11yIgnoreReasonsOverride}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let 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(e){let t=await cC(e),n=new r(t);return await n.initialize({grantPermissions:!0,runInitScripts:!1}),n}static async fromExistingContext({context:e,storage:t,enricher:n,userBrowserSettings:o,properties:i,logger:a,timingRecorder:s}){let c=e.pages()[0];if(!c)throw new Error("No page found in existing context");let l=c.viewportSize();if(!l){let m=Date.now();l=await c.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})),s["eval-viewport"]=Date.now()-m}let u=c?.url(),d=new r({browser:e.browser(),context:e,page:c,baseUrl:u,logger:a,storage:t,enricher:n,userBrowserSettings:o,viewport:l,properties:i,clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0,timingRecorder:s}),d}async handleAvailableTabsChangeHelper(){try{let e=await bg(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=_g(),o=`${e}-${n}`,i=Date.now(),a=!1,s=new AbortController;this.pageLoadAbortControllers.add(s);let c=async()=>{try{await k(t(),{signal:s.signal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&!this.closed&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],this.pageLoadAbortControllers.delete(s),a=!0}};this.pageLoadPromises[o]=c().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let 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()||!bo(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();this.logger.info({url:t},"Detected new page event, registering handlers and waiting for load to complete");try{this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let t=_g(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableConsoleLogs&&e.on("console",a=>{$w(e,o,this.debugData,a,this.logger)});let i=async()=>{!this.userBrowserSettings.disableBrowserMonitoring&&!this.userControlledBrowserSettings.disableNetworkLogs&&(Yw(this.logger,t,this.clientCallbacks?.onNetworkPage,e),!this.harBatcher&&this.clientCallbacks?.onNetworkLogs&&(this.harBatcher=qC(this.clientCallbacks.onNetworkLogs)),await e.route("**/*",async(a,s)=>{await lg({pageId:t,route:a,request:s,onHarEntry:(c,l)=>{this.harBatcher?.fetch({[c]:l}).catch(()=>{})},logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",eC(this.customHeaders,this.logger))),Lr&&await e.route("**/*",cs),await this.loadFrameAndRecordUrl({root:e,codePath:n}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(n,async()=>i())}async handleCollectSvgs(e){}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"||!bo(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}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a,url:t,codePath:o},"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){this.abortSignal=void 0,this.debugData.logsPerPage=[],this.pageLoadPromises={},await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await k(fg(this.getBrowserCallbacks()),{milliseconds:te})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0,this.cleanedUp=!0;try{this.pageLoadAbortListenerCleanup?.(),this.pageLoadAbortListenerCleanup=void 0,this.pageLoadAbortControllers.forEach(e=>e.abort()),this.pageLoadAbortControllers.clear(),this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.cleanedUp||this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,t,n){let o=Date.now(),i=0,a=0;for(;Date.now()-o<Ci;){a++,n?.throwIfAborted();try{if(await it({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:te,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){t.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await q(ct),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),it({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:ee,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 q(Eo),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 s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:t,optimizeForSpeed:!0},timeout:o??be}),c=Buffer.from(s.data,"base64"),l=await XC.fromBuffer(c),{width:u,height:d}=this.getViewport()??{};if(u&&d&&(l.bitmap.width!==u||l.bitmap.height!==d)&&(c=await l.resize({w:u,h:d}).getBuffer("image/jpeg")),n&&FB(n,c),this.lastScreenshotForRecording=c,!e)return c;let m=await e.boundingBox({timeout:ee});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:g,y:p,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");g=Math.floor(g),p=Math.floor(p),h=Math.floor(h),f=Math.floor(f);try{let E=await XC.fromBuffer(c),b=E.bitmap.width,x=E.bitmap.height;g=Math.max(0,Math.min(g,b-1)),p=Math.max(0,Math.min(p,x-1)),h=Math.max(1,Math.min(h,b-g)),f=Math.max(1,Math.min(f,x-p)),c=await E.crop({x:g,y:p,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${g}, ${p}) with size (${h}, ${f}): ${E}`)}finally{"dispose"in e&&await e?.dispose()}return c}getViewport(){if(this.viewport)return this.viewport;let e=this.page.viewportSize();return e||null}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){_w(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(l){if(a=l,this.abortSignal?.throwIfAborted(),this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await q(ct),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:te})}if(!i)throw new R("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(Bw.has(s))throw new R("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);await this.fixViewportForNewHeadless()}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async getActiveElementHandle(e){return e.evaluateHandle(()=>document.activeElement)}async getActiveElement(e){try{return await it({root:e,fn:()=>{let n=document.activeElement?.textContent??void 0;n&&n.length>100&&(n=n.slice(0,100)+"...[TRUNCATED]");let o=!1,i=window.getSelection();i&&!i.isCollapsed&&i.toString().trim().length>0&&(o=!0);let a=document.activeElement;return a&&"selectionStart"in a&&typeof a.selectionStart=="number"&&typeof a.selectionEnd=="number"&&a.selectionStart!==a.selectionEnd&&(o=!0),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:n,hasTextSelected:o}:{hasTextSelected:o}},arg:void 0,timeout:te,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 pC({root:o,text:e,options:t,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(n){let s=Date.now();for(;Date.now()-s<this.smartWaitingTimeout&&(!i||i.tag==="body");)await q(Eo),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}let a=i?.tag==="input"||i?.tag==="textarea";if(t.clearContent)if(a||t.forceClearContent)if(this.properties.isAndroid&&!a&&i?.textContent){this.logger.info("Clearing content using backspaces");let s=0,c=i.textContent?.length;for(;c&&s<50;){s++;let l=[...Array(c)].map(()=>"Backspace").join("+");await this.page.keyboard.press(l),i=await this.getActiveElement(o),c=i?.textContent?.length}c&&this.logger.warn("Content still remains after clearing existing")}else this.properties.isAndroid?await this.page.keyboard.press("Control+A"):process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25);else this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...");await this.page.keyboard.type(e,{delay:t.delay??of}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:be})}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(s=>setTimeout(s,250))}},void 0,{timeout:be})}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 Xc({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:te}),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 jw(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:te});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:te,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),n++}catch(s){this.logger.warn({err:s,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${n} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await Ww(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 Vw(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 R("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return bg(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,startingBoundingBox:o,allowNotActionableNodesOverride:i,logger:a=this.logger}){if(e&&this.saveA11yDetailsToCache(e,t),t.frameCache=this.stateManager.saveAutoFrameCacheDetails(t.frameCache),n)try{let s=await this.fetchHtmlAttributes({locator:n,logger:a,startingBoundingBox:o,allowNotActionableNodesOverride:i});s?(t.generatedSelectors=s.generatedSelectors,t.serializedHtml=s.serializedHtml,t.nodeOnlySerializedHtml=s.nodeOnlySerializedHtml,t.hybridSelector=s.hybridSelector):a.warn("Got undefined HTML attributes when trying to update cache")}catch(s){if(s instanceof Ir)throw a.warn({err:s},"Cache attributes disqualify found element"),s;a.warn({err:s},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:t,locator:n,logger:a,boundingBox:o})}catch(s){a.debug({err:s},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:t,logger:n,boundingBox:o}){if(!t)return{scrollPerformed:!1};if(!Xp.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:ee})),!o||!o.width||!o.height)return n.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:s=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let l=await this.screenshot({locator:t,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(l),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async getElementRequiredValues({logger:e,locator:t,requirements:n}){let o={},i=!!n?.position&&n.position!=="irrelevant",a=!!n?.shape&&n.shape!=="irrelevant";if(i||a){let s=await t.boundingBox({timeout:ee});if(!s||!s.width||!s.height)throw new R("ActionFailureError","Element does not have a bounding box as required");a&&(o.shape={width:s.width,height:s.height,tolerance:n.shape}),i&&(o.position={x1:s.x,y1:s.y,x2:s.x+s.width,y2:s.y+s.height,tolerance:n.position})}if(n?.text){let s=await t.textContent({timeout:ee});o.text=s?.trim()}if(n?.attributes&&n.attributes.length>0){let s={};for(let c of n.attributes){let l=c.trim().toLowerCase();if(!(!l||mr.bannedAiRequiredCacheAttributes.includes(l)))try{let u=await t.getAttribute(l,{timeout:ee});u!==null&&(s[c]=u)}catch(u){e.warn({err:u,attr:c},"Failed to fetch required attribute, continuing...")}}o.attributes=s}return o}async getAdditionalElementDetails({mainLocator:e,additionalElement: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 s=await this.fetchHtmlAttributes({locator:a,logger:o});if(!s?.generatedSelectors||s.generatedSelectors.length===0)return;let c={selectors:s.generatedSelectors};return t.requirements&&(c.requirements=await this.getElementRequiredValues({logger:o,locator:a,requirements:t.requirements})),c}async getAdditionalElementsDetails({mainElementId:e,mainLocator:t,additionalElements:n,root:o,logger:i}){let a=new Set,s=[];for(let c of n)try{if(c.id===e||a.has(c.id))continue;let l=await this.getAdditionalElementDetails({mainLocator:t,additionalElement:c,root:o,logger:i});if(a.add(c.id),!l)continue;s.push(l)}catch(l){this.logger.warn({err:l,additionalElement:c},"Failed to fetch additional element details, continuing...")}return s}async updateCacheWithAdditionalRequirements({mainElementId:e,requirements:t,additionalElements:n,target:o,locator:i,root:a,logger:s}){if(t)try{o.requirements=await this.getElementRequiredValues({logger:s,locator:i,requirements:t})}catch(c){s.warn({err:c},"Failed to generate required values for target")}n&&(o.additionalElements=await this.getAdditionalElementsDetails({mainElementId:e,mainLocator:i,additionalElements:n,root:a,logger:s}))}async createTargetFromA11yId({id:e,description:t,targetSource:n,skipSaveToCache:o,logger:i=this.logger,requirements:a,additionalElements:s}){if(e<0)throw new R("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new R("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,m,g;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let b=c.parentFrame,{cache:x,config:v}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=x,m=v,u=v.frame,g="auto iframe"}else c.parentFrame&&l?(m=l,u=await this.getActivePageOrFrame(),g="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),g="should not be possible");let p=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:fe(i),frameCache:d},f,E=!1;o||(m&&(i.info({frameConfigSource:g,frameConfig:jC(m)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(m),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:p,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,target:h,root:u,locator:p,logger:i}));try{return{resolution:{locator:p,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:m,frameConfigSource:g}}finally{E&&this.stateManager.setActiveFrameConfig(f)}}async resolveTarget(e,t,n={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowNotActionableNodesOverride:s}=n;if(t.frameCache&&this.userBrowserSettings.autoExpandIframes){let g,p=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),p=!0;break}catch(f){g=f,await q(ct,a)}if(!p)throw g}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let l=Date.now(),u=0,d=0,m;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let g=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{m=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,shouldLogOnFailure:g,logger:i,allowNotActionableNodesOverride:s,signal:a});break}catch(p){if(p instanceof aa)break;if(p instanceof Ir){if(d++,d>2)throw i.error({err:p},"Got multiple cache disqualification errors, giving up"),p;i.warn({err:p},"Got cache disqualification error, waiting and retrying resolution"),await q(ct,a)}a?.throwIfAborted(),g&&i.warn({err:p},`Could not resolve target using primary cache only (x${u})`),await q(ct,a)}}return m||(m=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:s}),i.info({decisions:m.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:m?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),m}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a,shouldLogOnFailure:s}){let c=_i(t),l=[],u,d=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),m;if(t.generatedSelectors||t.hybridSelector){let g;try{g=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s})}catch(p){m=p,p instanceof Pr&&(l.push(...p.decisions),u=p.cacheMissReason)}if(g)return{...g,pageState:void 0,decisions:[...l,...g.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:m?.message,selectors:_i(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw m;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let g=await this.resolveTargetWithSecondaryMethods({root:e,tree:d,target:t,decisions:l,logger:o,signal:i,allowNotActionableNodesOverride:a});if(g)return t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=fe(o),g;u=u??"secondary-resolution-failed"}throw new Pr(`Could not find any relevant node given target: ${JSON.stringify(c)}`,l,u)}async resolveTargetWithPrimaryMethods({root:e,target:t,logger:n,allowNotActionableNodesOverride:o,shouldLogOnFailure:i}){if(!t.nodeOnlySerializedHtml)throw new aa("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:Cn,s=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:Yp,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?t.boundingBox:void 0,requirements:t.requirements,additionalElements:t.additionalElements,importantProperties:{attributes:this.userControlledBrowserSettings.importantAttributes,classes:this.userControlledBrowserSettings.importantClasses,styles:this.userControlledBrowserSettings.importantStyles}},{css:l,hybrid:u}=await it({fn:A=>window.evaluatePrimaryCaches(A),arg:{cssParams:{selectors:t.generatedSelectors??[],cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c},hybridParams:s&&t.hybridSelector?{nodes:t.hybridSelector,cachedElementSerialized:t.nodeOnlySerializedHtml,opts:c}:void 0},root:e,timeout:ee,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,m,g=[];if(s==="prefer"&&u?.result){d=u.result;let A={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};g.push(A),m="HYBRID_SELECTOR"}else if(l?.result){d=l.result;let A=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,_=d.workingSelectors.slice(0,5);g.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:A,selectors:_}),n.debug({reason:A,workingSelectors:_},"Resolved with CSS selectors"),m="CSS_SELECTOR"}else throw g.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),u&&g.push({type:"HYBRID_SELECTOR",matched:!1,reason:u.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:u.logs}),l?.error&&n.error({err:new Error(l.error)},"Cache evaluation errored unexpectedly (CSS)"),u?.error&&n.error({err:new Error(u.error)},"Cache evaluation errored unexpectedly (Hybrid)"),new Pr("Cache evaluation failed",g,l.cacheMissReason);let p,h,f;if(this.userBrowserSettings.visualActions){let A=d.mPath;if(!A)throw new Error("Found element did not have an mPath despite using visual actions");let _=A.join(" > ");p=e.locator(_),h=this.stateManager.getNodeUsingMPathSelector(_)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?p=e.locator(d.workingSelectors[0]):p=e.locator(vr(f));else throw new R("InternalWebAgentError","Received an element resolution result with no identifying attributes");s&&t.hybridSelector&&(u?.logs.length===1?a.warn({hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution rejected, continuing..."):u?.result?l?.result&&u?.result&&u.result.serializedElement!==l.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(l.result.mPath)!==JSON.stringify(u.result.mPath)?n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):l.result.dataMomenticId!==u.result.dataMomenticId&&n.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):a.warn({originalCache:t,hybridResult:u,cssResult:l,hybridMode:s},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let[E,b]=await Promise.all([p.textContent(),p.boundingBox()]);if((E??"")!==(d.textContent??""))throw n.warn({currentTextContent:E,originalTextContent:d.textContent},"Retrying cache resolution because element's text content has changed since resolution"),new Error("Element's text has changed since cache was resolved");if(!b||Math.abs(b.height-d.boundingBox.height)>1||Math.abs(b.width-d.boundingBox.width)>1||Math.abs((b.x??0)-(d.boundingBox.x??0))>1||Math.abs((b.y??0)-(d.boundingBox.y??0))>1)throw n.warn({currentBoundingBox:b,originalBoundingBox:d.boundingBox},"Retrying cache resolution because element's bounding box has changed since resolution"),new Error("Element's bounding box has changed since cache was resolved");let x=_i(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:p,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let v=Pg(x,t);return v&&Object.keys(v).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=fe(n),t.cacheResolutionUpdateSource=m),{a11yNode:h,displayString:d.serializedElement,locator:p,decisions:g}}async resolveHardcodedCssSelector(e){let{ctx:t,selector:n,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),c=Date.now(),l=0,u,d=[];for(;Date.now()-c<a;){i?.throwIfAborted(),l++;let m=s.locator(n),g;try{return await m.waitFor({state:"attached",timeout:te}),g=await Ar(m,o,500)??"",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:m,displayString:g,decisions:d}}catch(p){let h=p.message;u=new R("ActionFailureError",`CSS selector '${n}' failed to resolve after ${l} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await q(ct,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 s=await a.locator.boundingBox({timeout:ee});if(!s){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:l,width:u,height:d}=s;if(Math.abs(u-o)>10||Math.abs(d-i)>10){this.logger.debug({newW:u,oldW:o,newH:d,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!t||!n||!c||!l){this.logger.debug({oldX:t,oldY:n,newX:c,newY:l,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-t)>100||Math.abs(l-n)>100){this.logger.debug({newX:c,newY:l,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<Uw){let l="Refusing to attempt HTML comparison since the saved element is too short.";n.push({type:"HTML_DISTANCE",matched:!1,reason:l})}else if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.length>50)try{let l=await it({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:be,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(Yp*t.nodeOnlySerializedHtml.length);if(l&&l.closestDistance&&l.closestDistance>=u){let d=`Closest HTML candidate still has too far distance (${l.closestDistance}) from threshold (${u})`;n.push({type:"HTML_DISTANCE",matched:!1,reason:d,distance:l.closestDistance,closestElement:l.closestNodeSerialized})}else{if(l?.error)throw new Error(l.error);if(l?.dataMomenticId||l?.mPathSelector){let d=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,m,g;if(d)m=this.stateManager.dataMomenticIdToNodeMap[d],g=e.locator(vr(d));else if(l.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),g=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let p=l.closestNodeSerialized??await Ar(g,o,500)??"unknown element";o.warn({result:l,originalTarget:t,displayString:p},"Resolved cached target to new node with pure html levenshtein distance");let h=_i(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:g,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=Pg(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=fe(o),t.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:l},"Updated cache after l-dist resolution")),n.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${u} string comparison distance of the saved element.`,logs:l.logs,distance:l.closestDistance,closestElement:p,savedElement:t.nodeOnlySerializedHtml}),{locator:g,a11yNode:m,displayString:p,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`)}}catch(l){o.info({err:l},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${l}`})}let s=t.screenshotUrl,c=t.role??"";if(s&&Xp.includes(c))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:t,screenshotUrl:s,signal:i,allowNotActionableNodesOverride:a});return{...l,decisions:[...n,...l.decisions],pageState:void 0}}catch(l){i?.throwIfAborted(),n.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`,elementImageUrl:s}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({screenshotUrl:e,oldTarget:t,signal:n,allowNotActionableNodesOverride:o}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let a=await this.screenshot({retries:0}),c=await(await fetch(e)).arrayBuffer(),l=WB(),u=await this.enricher.runTemplateMatching({id:l,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:m}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),g=d.boundingBox?.width,p=d.boundingBox?.height;if(!g||!p)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=_i(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:m,allowNotActionableNodesOverride:o});let b=Pg(E,t);return b&&Object.keys(b).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=fe(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:l,diffs:b,templateMatch:u},"Updated cache after template matching resolution")),{locator:m,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:te})??"",i=mC.some(a=>a===o.toLowerCase());return await Sg({targetingResult:t,options:{force:n.force,relativePosition:n.relativePosition},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks(),isAndroid:this.properties.isAndroid??!1}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return Sg({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks(),isAndroid:this.properties.isAndroid??!1})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),zc(s,t,n)){a=!0;break}await q(ct,this.abortSignal)}if(!a)throw new R("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${HA(t)} in ${o}ms.
|
|
4232
4232
|
Current tab: ${s}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,t,n={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await t.boundingBox({timeout:ee});if(!o)throw new R("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=n.steps??5;await this.page.mouse.move(i,a,{steps:s}),await q(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,be):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o){o&&await this.hover({locator:o}),await this.page.mouse.down();let i;if(o){let a=await o.boundingBox({timeout:ee});a&&(i={x:a.x+a.width/2,y:a.y+a.height/2})}i||(this.logger.warn("Could not get starting position from fromTarget, falling back to (0,0)"),i={x:0,y:0}),await this.page.mouse.move(i.x+e,i.y+t,{steps:n}),await q(Eo),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await vo({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:ee});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 vo({func:t=>t.locator.focus({timeout:be}),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 it({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:te,codePath:"blurring the active element"});return}await this.highlight(e.locator),await vo({func:t=>t.locator.blur({timeout:be}),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 vo({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 R("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:ee})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Jc(e,this.properties.isAndroid);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<n;o++)await this.page.keyboard.press(e,{delay:t.delayMs??0})}async keyDown(e,t){if(t.convertMeta){let n=Jc(e,this.properties.isAndroid);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=Jc(e,this.properties.isAndroid);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,shouldLogOnFailure:a}=e,s=e.abortSignal??this.abortSignal,c=!i,l=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements,u=a?n:Cn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:s});let d=0,m;for(;d<t;){d++;try{return await k(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:s,logger:n,filterByViewport:e.filterByViewport,showZeroOpacityElements:l,flagNotActionableNodes:c}),{milliseconds:this.pageLoadTimeout*d,signal:s,message:"Getting browser state took too long"})}catch(g){if(s?.throwIfAborted(),m=g instanceof Error?g.message:`${g}`,d>=t)throw g;u.warn({err:g,url:this.url()},"Error getting a11y tree, retrying...")}}throw new R("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${m}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await it({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:ee,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=m=>{i.value=Date.now()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let c=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let l=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",l);let u=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",u);let d=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",d);try{await this.waitForDOMStabilityHelper(i,t,n,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",l),this.cdpClient.removeListener("Page.navigatedWithinDocument",u),this.cdpClient.removeListener("Page.frameRequestedNavigation",d)}}async waitForDOMStabilityHelper(e,t,n,o){let i=!1,a=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,u=0;for(;Date.now()-a<n;){if(o?.throwIfAborted(),await q(Eo,this.abortSignal),s)try{let d=await this.screenshot(c);if(!d.equals(s)){s=d,l=!1;continue}l=!0}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(c)}catch(d){u++,u%3===0&&t.warn({err:d,screenshotErrors:u},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<kw)){i=!0;break}}i||t.warn({duration:Date.now()-a,stable:{a11y:i,screenshot:l}},"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 bC(this.page,e,t,n)}async mouseDragUsingVisualCoordinates(e,t,n,o,i){await yC({page:this.page,deltaX:e,deltaY:t,steps:n,delayMs:o,visualTarget:i,isAndroid:this.properties.isAndroid??!1})}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y,{steps:3})}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:ee}),n=await k(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:be});process.platform==="darwin"&&n===1&&(n=Nw);let o=t.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],c=a.backendNodeId||[],l=i.nodeIndex,u=i.bounds,d=-1;for(let b=0;b<s.length;b++)if(c[b]===e){d=l.indexOf(b);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,g=0,p=0,h=0]=u[d];m/=n,g/=n,p/=n,h/=n;let f=m+p/2,E=g+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return yg({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 yg({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,t){if(await this.stopScreencast(),this.recordUrlVisited(e.url()),this.onVideoPageChange){let n=await e.video()?.path();if(n){let o=JC(n);this.onVideoPageChange({videoName:o})}}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 q(ct)}}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 R("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)}.
|
|
@@ -4235,9 +4235,9 @@ Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!bo(o.url,this.logger)){
|
|
|
4235
4235
|
`),tokenLength:d}),u=[],d=0,m=g.length?[g[g.length-1].id]:[],p=!1);let h=c[l],f=wr(h);d+=f,h.length>a&&(h=h.slice(0,a));let x=Array.from(h.matchAll(eR)).map(K=>K&&K.length>=3?{tagName:K[1],id:K[2]}:void 0).filter(K=>!!K),A=Array.from(h.matchAll($B)).map(K=>K&&(K[2]||K[4])).filter(K=>!!K);A.reverse();let _=h.replace(/ id="[0-9]+"/g,"");u.push(_);for(let K of x)m.push(K.id),g.push(K);for(let K of A){let j=g[g.length-1];j&&j.tagName===K&&g.pop()}let w=g.some(K=>KB.includes(K.tagName)),N=c[l+1]??"",G=wr(N),ye=Array.from(N.matchAll(eR)).map(K=>K&&K.length>2?K[1]:void 0).filter(K=>!!K),Se=ye.some(K=>nR.includes(K)),Ae=ye.some(K=>qB.includes(K));d+G>=i&&(p=!0),d>=n&&(Se&&!w||A.some(K=>YB.includes(K)))&&(p=!0),d>=o&&Ae&&!w&&(p=!0),l++}return u.length&&s.push({ids:m,content:u.join(`
|
|
4236
4236
|
`),tokenLength:d}),s.forEach((h,f)=>{let E=h.ids[0],b=h.ids[h.ids.length-1];r.debug({tokenLength:h.tokenLength,minId:E,maxId:b},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var QB=75e4,ou=3e5;async function wo(r){let{options:e,fixtures:t,screenshot:n}=r,{aiPageFiltering:o}=e,{logger:i,generator:a,orgId:s,signal:c}=t,l=r.tree,u=r.serializedTree,d=wr(u);if(d>QB)try{let m=nu({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await ez({...r,tokenLimit:ou-1e4,chunks:m.chunks}),u=l.serialize();let g=wr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using keywords"),d=g}catch(m){i.warn({err:m},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(ou*Dn),u=l.serialize();let g=wr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using naive truncation"),d=g}if(d>ou)try{if(o){let m=nu({serializedTree:u,options:rR,logger:i}),g=JB();l=await k(ZB({...r,chunks:m.chunks,callId:g}),{milliseconds:12e3,signal:c}),u=l.serialize();let p=wr(u);i.info({oldTokens:d,newTokens:p,langfuseCallId:g},"Filtered page using AI chunk ranking"),d=p}else{let m=nu({serializedTree:u,options:tR,logger:i});l=await k(tz({...r,chunkResult:m,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=wr(u);i.info({oldTokens:d,newTokens:g},"Filtered page using RAG"),d=g}}catch(m){i.warn({err:m},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(ou*Dn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function ZB({type:r,callId:e,chunks:t,description:n,fixtures:o,tree:i}){let{generator:a,signal:s,logger:c}=o,l=await a.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:4e4,hardTokenLimit:8e4,callId:e},{abortSignal:s,logger:c,loggerTags:fe(c)}),u=[];return t.forEach((m,g)=>{l.indices.includes(g)&&(u=u.concat(m.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function ez(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 s=await o.getExtractedKeywords({goal:e},{logger:i,loggerTags:fe(i),abortSignal:a});i.info({keywordsResult:s},"Got keywords for page filtering");for(let c of s.keywords){let l=r.chunks.filter(g=>g.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((g,p)=>g+p.tokenLength,0)>r.tokenLimit&&l.length>1)continue;let d=l.flatMap(g=>g.ids);return n.pruneUsingRelevantIds(new Set(d))}throw new Error("No keywords were unique enough for page filtering")}async function tz(r){let{description:e,fixtures:t,chunkResult:n,tokenLimit:o,tree:i}=r,{generator:a,logger:s,signal:c}=t,l=await a.rankChunksWithRag({description:e,chunks:n.chunks,tokenLimit:o},{abortSignal:c,logger:s,loggerTags:fe(s)});if(l.ids.length===0)throw new Error("RAG returned no important ids");return i.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`)))}async function Og(r,e){if(!r.description)throw new R("UserConfigurationError","Cannot locate element with empty description");return gr({action:async()=>rz(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function rz(r,e){let{disableCache:t,testContext:n,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:c,logger:l,allowNotActionableNodesOverride:u}=r,{ctx:d,orgId:m,browser:g,localCodeEvalTools:p,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await is({orgId:m,s:E,context:n,localTools:p,signal:f,logger:l})),a&&(E=oz(E,a));let{serializedTree:x,tree:v}=await jr(g,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),A,_=Date.now(),w;for(;!A&&Date.now()-_<3e3;){f.throwIfAborted();try{A=await g.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Q){w=Q}}if(!A)throw new R("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${w?.message}`);let N=x,G=!1,ye=`data:image/jpeg;base64,${A.toString("base64")}`;N=await wo({type:"locator",description:E,screenshot:ye,serializedTree:x,options:{aiPageFiltering:c},tree:v,fixtures:{generator:h,signal:f,logger:l,orgId:m}}),N!==x&&(G=!0);let Se=await h.getElementLocation({browserState:N,goal:E,screenshot:ye,source:a,memory:b?s:void 0},{disableCache:t,abortSignal:f,loggerTags:fe(l),useMemory:b});l.debug({usedRag:G,result:Se},"Got locator result");let Ae=Se.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:Ae,pageState:N,ragUsed:G,thoughts:Se.thoughts}),!Ae)throw new fn(`Could not find any relevant element: ${Se.thoughts}`,Se.updatedMemory?{type:"GCS_TRACES",traces:Se.updatedMemory}:void 0);let{resolution:K,target:j,frameConfig:le}=await g.createTargetFromA11yId({id:Se.id,requirements:Se.requirements,additionalElements:Se.additionalElements,description:E,targetSource:"AI",logger:l});if(K.a11yNode?.properties?.hidden&&K.a11yNode?.properties?.hidden!=="false")throw new R("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: ${K.displayString}`);return b&&(Se.updatedMemory?j.memory={type:"GCS_TRACES",traces:Se.updatedMemory}:s&&(j.memory=s)),{thoughts:Se.thoughts,target:j,resolution:K,frameConfig:le,screenshot:ye}}var nz=["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:"],oR="<select> element:",iR="text input or contenteditable element:",aR="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:",sR="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:",Ig=[oR,iR,aR,sR,...nz];function lR(r,e){if(r===e)return!0;for(let t of Ig){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(Ig.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!Ig.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function oz(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${oR} ${r}`;case"TYPE":return`${iR} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${aR}
|
|
4237
4237
|
${r}`;case"ELEMENT_CHECK":return`${sR}
|
|
4238
|
-
${r}`;default:return r}}var iz=15;async function iu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=iz}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Bc(c),u=0,d=Date.now(),m,g,p;try{await gr({action:()=>s.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:s,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 q(l,n.abortSignal),h=Date.now();let f=!1;try{if(m=await gr({action:async()=>{let b=await cR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(g=b,uR({command:r,state:b,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:s}),m?.success){m?.updatedMemory&&as(r,m.updatedMemory,t);break}else throw m?.thoughts?new R("AssertionFailureError",m.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),p=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!m?.success)try{m=await gr({action:async()=>uR({command:r,state:await cR(s,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:s})}catch(f){n.abortSignal.throwIfAborted(),p=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(m?.updatedMemory&&as(r,m.updatedMemory,t),!m?.success){let f=`AI check still failing after ${u} attempts.`;throw p&&(f+=` Latest result: ${p.message}`),new R("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function cR(r,e,t){let[n,o]=await Promise.all([jr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function uR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:m}=t,g={type:"ASSERTION"},{serializedTree:p,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",v=p;x!=="VISION_ONLY"&&(v=await wo({type:"assertion",serializedTree:p,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),v!==p&&(g.ragUsed=!0),g.pageState=v);let A={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:v,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(N,G)=>d.getVisualAssertionResult(N,G):(N,G)=>d.getAssertionResult(N,G))(A,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:fe(l)});return(w.result||i)&&w.relevantElements&&(g.relevantElementsSerialized=w.relevantElements.map(N=>u.getSerializedFormFromA11yId(N)).filter(N=>!!N),await az(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function az(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 k(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 sz=75e4,au=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function dR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await lz(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof au?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await q(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function lz(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await q(o.smartWaitingTimeout,n);return}if(!e.description)throw new R("UserConfigurationError","Cannot locate element with empty description");await k(cz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function cz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await gr({action:async()=>uz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uz(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=r.description;t&&(d=await is({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await jr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(wr(m)>sz)throw new au;s.throwIfAborted();let p;try{p=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new R("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${p.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:fe(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as pR}from"lodash-es";async function gR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Wh(e.cache)?e.cache:void 0,a=i(),s=pR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=jA(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,m=500,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await q(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await mR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&Ns(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await mR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let p=i();return d.success&&p?.target&&!g&&(p.target=Fp(p.target),p.updatedAt=new Date),d}async function mR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!pn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Nc(t.assertion),l,u=!1,d=pR(r);try{let{elementInteractedDisplayString:m,result:g,thoughts:p}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>dz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ca(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:m,thoughts:p},u=!0,g.success||(s.warn({aiThoughts:p,elementString:m,err:g.err},"Element check found an element but failed"),l={...g,thoughts:p}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof R)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await mz(r,e.assertion)}async function mz(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:gt(a,500,!0)},!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:gt(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await r.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new R("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new R("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},zt*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:zt*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:zt*1e3});break}case"FOCUSED":{t=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"})(e.condition)}if(t=e.negated?!t:t,!t){let a=dr(e);n=new R("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The style property ${e.property} ${s}`):n=new R("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function hR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pz}from"jimp";async function ms(r,e){let t=await r.screenshot(e),n=await pz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as fR}from"jimp";import Lg from"jpeg-js";import gz from"pixelmatch";async function SR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!pn(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},l;t.target?.elementDescriptor?l=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async ye=>ms(o,{locator:ye.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await ms(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,t,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let W=`${l.width}x${l.height}`,ye=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${W}) does not match saved screenshot dimensions (${ye}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await fR.fromBuffer(l.buffer),m={width:l.width,height:l.height},g=await fR.fromBuffer(u.buffer),p={width:u.width,height:u.height},h,f=m.width*m.height,E=p.width*p.height,b=Math.abs(m.height-p.height),x=Math.abs(m.width-p.width);if(f>E){let W=d.cover({w:p.width,h:p.height});l.buffer=await W.getBuffer("image/jpeg"),h="current",l.width=p.width,l.height=p.height}else if(E>f){let W=g.cover({w:m.width,h:m.height});u.buffer=await W.getBuffer("image/jpeg"),h="saved"}let v={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},A=t.threshold??.1,w=gz(Lg.decode(u.buffer).data,Lg.decode(l.buffer).data,v.data,l.width,l.height,{threshold:A,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,N=w>A*100,G=`Visual diff of ${w.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${A*100}%.`;if(h&&(G+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),N)throw new R("ActionFailureError",G);return{fail:N,thoughts:G,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Lg.encode(v,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hz=3e4;function fz(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function su({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??hz/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,p])=>g&&p)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,p])=>g&&p).forEach(([g,p])=>{a.append(g,p)});let s=a.toString(),c;if(Ai(r.url)&&(c=r.url),t&&wi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await k((async()=>{let g=s?`${c}?${s}`:c;try{let p=fz(r);return await n(g,{headers:{...p.contentType?{"Content-Type":p.contentType}:{},...i},method:r.method,body:p.content})}catch(p){throw e.error({err:p},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${p}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let g;try{g=await u.text()}catch(p){g=`Failed to read response body: ${p}`}throw new R("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,p)=>{d[p]=g});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var Sz=5e3;async function bR({timeout:r=zt,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=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 lu(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await q(s,e.signal),s=Math.min(Math.floor(s*1.5),Sz);else return i}return i=await lu(e),i}async function lu({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(yR,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(yR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?rn.CONTAINS:nn.CONTAINS;a=new R("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function yR({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 yz=3e4;async function ER({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??yz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(Ai(r.url)&&(s=r.url),t&&wi(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let l=await k((async()=>{try{return await n(s,{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(!l)throw new R("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,m=await l.text();try{d=JSON.parse(m)}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=d}),{status:l.status,headers:u,json:await l.json()}}var cu=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([jr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await wo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...fe(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([jr(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")}`,m=await wo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),g={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...fe(a)},langfuseSessionId:s})}catch(p){throw new R("InternalWebAgentError",`Error generating command: ${p instanceof Error?p.message:p}`,{errOptions:{cause:p}})}}async getBrowserState(e){return jr(this.browser,e)}async locateElement(e){return await Og({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return gr({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,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:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let m=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async p=>p,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(p=>p.result)),m=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",g=u.map((p,h)=>p.thoughts?`${m(o[h])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(p=>p.elementInteractedDisplayString),thoughts:g}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new R("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 gr({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&&dd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(gd(i)||md(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(hd(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Ir&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof R?n:new R("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:s}=o;if(t.type!=="description")throw new R("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await q(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:m,source:g}=s,p=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=TR(e.cache);if((!b||l)&&!Yu(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(p.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!lR(o.elementDescriptor,b.inputDescription)&&(p.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let x=A=>!!A&&Ns(A),v=!0;if(!x(b)){v=!1,p.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await dR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:p,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let A;try{A=await Og({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:p},this.getControllerFixtures(t))}catch(N){if(N instanceof fn&&N.updatedLocatorMemory){let G={id:-1,...i,memory:N.updatedLocatorMemory};Dc({cmd:c,key:d,newTarget:G,logger:p,updatedWithAI:!0})}throw new R("ActionFailureError",N.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let _=s.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,p),w=await a(_);return Dc({cmd:c,key:d,newTarget:A.target,logger:p,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=fe(p)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:p,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let _=s.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,p),w=await a(_);if(Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.1"]),Dc({cmd:c,key:d,newTarget:b,logger:p,updatedWithAI:!1}),v){let N=A.decisions.filter(G=>G.matched);if(N.length!==1)p.warn({decisions:A.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let G=N[0].type;n.recordTargetAutoHeal({healType:G})}}return{result:w,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed();let _="unknown";A instanceof Pr&&A.cacheMissReason&&(_=A.cacheMissReason),Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.1",`missReason:${_}`]);let w=!1;if((A instanceof Ir||dd(A)||gd(A)||hd(A)||Jf(A)||md(A)||Qf(A))&&(w=!0),A instanceof R&&!w)throw p.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){p.info({err:A},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&Bh(b.memory)&&(N=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new R("ActionFailureError",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return ms(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await q(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new R("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&ff(n)?await this.browser.waitForDOMStability({timeout:be}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:te}),this.options?.autoFollowNewTabs&&await ZC({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{Lc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>ng(e)}}async resolveCommandTemplateStrings(e,t){return Oc({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 s=n.condition;return s?.assertion.trim()?iu({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new R("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new R("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return iu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=Qb(n.schema);if(f)throw new R("UserConfigurationError",f)}let p=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:p,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:fe(a)});if(f.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new R("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 R("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 R("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(!Ai(n.url)&&!wi(n.url,this.browser.baseUrl))throw new R("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:p=>this.browser.click(p,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 p,h;if(n.target&&xr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:v=>this.browser.hover(v),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});p=b,h=x}let f=this.browser.getViewport()?.height??En.height,E=this.browser.getViewport()?.width??En.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:p,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let p=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:p},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await q(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(xr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let p=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:x=>this.browser.click(x,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return Hc(p,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}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(xr(n.fromTarget)&&xr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(xr(n.fromTarget)||xr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:p,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:p[0],thoughts:h}}case"MOUSE_DRAG":{let p=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(p)||isNaN(h))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&xr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(p,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async A=>this.browser.mouseDrag(p,h,f,A.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=v}else await this.browser.mouseDrag(p,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!pn(n.target))throw new Error("Select with x/y is not supported yet");let p=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:p},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ca(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let p={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,p);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 p;try{n.environment==="BROWSER"?(p=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:p},"Executed JavaScript in browser")):p=await zr({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 R("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(p)}catch(h){throw new R("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:p}}case"TYPE":{if(n.target&&xr(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 p=this.browser.url(),h,f,E=TR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:v,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:_=>this.browser.typeIntoTarget(n.value,_,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!b,source:ca(n)}});h=v,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 x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Hc(p,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(xr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:p,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:p,thoughts:h}}case"FOCUS":{if(!pn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,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:p,thoughts:h}}case"BLUR":{if(n.target&&!pn(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:p,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:p,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 m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Hc(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;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 p=new Ez,h=bz(fetch,p),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await su({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:ul(p,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await ER({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return SR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,p=await Hw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,p=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!p)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...p,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p;if(!n.storageState.trim())p=void 0;else if(p=await zr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof p!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let h;try{h=yy.optional().parse(p)}catch(f){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let p=(n.timeout??zt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(hR(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 b=await iu({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: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{E.cache?.memory&&as(n,E.cache?.memory.traces,a)}}let f=await gR({command:n,tracer:t,timeoutMs:p,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 p=await gr({action:async()=>bR({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:!p.success,data:p.data,thoughts:p.success?"Page assertion passed.":p.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let p=new kn(n.requestMatcher),h=this.browser.registerRequestListener(p);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 p=this.registeredListeners[n.key];if(!p)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(p,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let p=new kn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>p.matches({url:h.request.url,method:h.request.method}),onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let p=this.recordedRequests[n.key];if(!p)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(p),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let p;return n.requestMatcher&&(p=new kn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,p),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new kn(n.requestMatcher),async(h,f)=>{let E=await zr({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"}),b=Uy.parse(E);return new Response(b.body,{status:b.status,headers:b.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(p=>{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:fe(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 eu({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:fe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:fe(this.logger)})}};import{cloneDeep as Tz}from"lodash-es";import RR from"truncate-json";var vR=1e3,AR=5e6,vz=5*1024*1024;function xR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=RR(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.type){case"MOBILE_PRESET_STEP":wR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":wR(n),xR(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function wR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function CR(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 uu(r,e){let t=Tz(r);if(xR(t,e),t.length>vR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,vR);let n=CR(t,e);if(n.length>AR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>AR;)t.pop(),n=CR(t,e);let{jsonString:o}=RR(n,vz);try{return Ut.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as Az}from"async_hooks";var ps=new Az;function wz(r){ps.enterWith({activeTracers:[r]})}function Cz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function Rz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ps.run({activeTracers:n},e)}var an={globalAls:ps,initializeRootTracerContext:wz,withChildTracer:Cz,withChildTracerAsync:Rz};var Co=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return an.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t,n){let o={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},i=new r(o);this.addSpan(o);try{let a;return n?.signal||n?.timeoutMs?a=await an.withChildTracerAsync(i,()=>k(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg??`Operation timed out after ${n?.timeoutMs??1/0}ms (${e})`})):a=await an.withChildTracerAsync(i,()=>t(i,o)),a}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}finally{i.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await k(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal,message:i?.timeoutMsg??`Operation timed out after ${i?.timeoutMs??1/0}ms${"name"in i?` (${i.name})`:""}`}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function re(){let r=an.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Co}async function MR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await k(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(s){t?.throwIfAborted(),n.warn({err:s,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=xz(i,o);if(a.length!==0)for(let s of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",s.toString()]}),n.info({packageName:o,taskId:s},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:s},"Failed to remove task from recents")}}}function xz(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,s]=a;if(!s)continue;let c=Number.parseInt(s,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}import{mkdirSync as $z}from"fs";import{tmpdir as qz}from"os";import NR from"path";import{diff as Wz}from"deep-object-diff";import{cloneDeep as jz}from"lodash-es";import IR from"fontoxpath";import Mz from"@prettier/plugin-xml";import _z from"prettier";import{DOMParser as Pz,XMLSerializer as Iz}from"slimdom";var Oz=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function gs(r){let e=r.toLowerCase();return e.endsWith("webview")||Oz.has(e)}function Lz(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var Nz=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Dz=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),kz=new Set(["text","hint"]),Uz=new Set(["live-region","drawing-order"]),Fz=new Set(["displayed","enabled"]);function Bz(r,e){let t={};for(let[n,o]of Object.entries(e))Nz.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Dz.has(n)&&o==="false"||kz.has(n)&&o===""||Fz.has(n)&&o==="true"||Uz.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function _R(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let m of e.attributes){let g=m.name,p=m.value;p!=null&&(l[g]=String(p))}let u=Bz(e.tagName,l);for(let[m,g]of Object.entries(u))t.setAttribute(m,g);if(o.set(c,e),i.set(c,t),gs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4238
|
+
${r}`;default:return r}}var iz=15;async function iu({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=iz}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Bc(c),u=0,d=Date.now(),m,g,p;try{await gr({action:()=>s.clearHighlights(),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:s,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 q(l,n.abortSignal),h=Date.now();let f=!1;try{if(m=await gr({action:async()=>{let b=await cR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(g=b,uR({command:r,state:b,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:s}),m?.success){m?.updatedMemory&&as(r,m.updatedMemory,t);break}else throw m?.thoughts?new R("AssertionFailureError",m.thoughts):new R("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),p=E instanceof Error?E:new Error(`${E}`),f?t.info(`AI check attempt ${u} failed (re-used previous result)`):t.info({err:E},`AI check assert attempt ${u} failed, retrying...`)}finally{u++}}if(!m?.success)try{m=await gr({action:async()=>uR({command:r,state:await cR(s,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:s})}catch(f){n.abortSignal.throwIfAborted(),p=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(m?.updatedMemory&&as(r,m.updatedMemory,t),!m?.success){let f=`AI check still failing after ${u} attempts.`;throw p&&(f+=` Latest result: ${p.message}`),new R("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function cR(r,e,t){let[n,o]=await Promise.all([jr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function uR({command:r,state:e,fixtures:t,useConsensus:n,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:c,logger:l}){let{browser:u,generator:d,abortSignal:m}=t,g={type:"ASSERTION"},{serializedTree:p,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",v=p;x!=="VISION_ONLY"&&(v=await wo({type:"assertion",serializedTree:p,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),v!==p&&(g.ragUsed=!0),g.pageState=v);let A={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:v,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(N,G)=>d.getVisualAssertionResult(N,G):(N,G)=>d.getAssertionResult(N,G))(A,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:fe(l)});return(w.result||i)&&w.relevantElements&&(g.relevantElementsSerialized=w.relevantElements.map(N=>u.getSerializedFormFromA11yId(N)).filter(N=>!!N),await az(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function az(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 k(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 sz=75e4,au=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function dR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await lz(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof au?t.warn("Skipping AI smart waiting due to excessive page size - falling back to naive waiting"):t.warn({err:a},"Unexpected error occurred during AI smart waiting");let s=o.smartWaitingTimeout-(Date.now()-i);s>0&&await q(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function lz(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await q(o.smartWaitingTimeout,n);return}if(!e.description)throw new R("UserConfigurationError","Cannot locate element with empty description");await k(cz(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function cz(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await gr({action:async()=>uz(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function uz(r,e){let{testContext:t,logger:n,filterByViewport:o,allowNotActionableNodesOverride:i}=r,{browser:a,abortSignal:s,localCodeEvalTools:c,orgId:l,generator:u}=e,d=r.description;t&&(d=await is({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await jr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(wr(m)>sz)throw new au;s.throwIfAborted();let p;try{p=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new R("ActionFailureError",`Failed to take screenshot of page to perform smart waiting. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${b instanceof Error?b.message:b}`)}let f=`data:image/jpeg;base64,${p.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:fe(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as pR}from"lodash-es";async function gR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Wh(e.cache)?e.cache:void 0,a=i(),s=pR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=jA(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,m=500,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await q(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await mR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new R("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&Ns(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await mR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let p=i();return d.success&&p?.target&&!g&&(p.target=Fp(p.target),p.updatedAt=new Date),d}async function mR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!pn(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=Nc(t.assertion),l,u=!1,d=pR(r);try{let{elementInteractedDisplayString:m,result:g,thoughts:p}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>dz(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:ca(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:m,thoughts:p},u=!0,g.success||(s.warn({aiThoughts:p,elementString:m,err:g.err},"Element check found an element but failed"),l={...g,thoughts:p}),{result:l,elementWasFound:u}}catch(m){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${m.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(m instanceof R)||m.reason!="ActionFailureError")throw m;return l={success:!1,err:m,data:void 0,thoughts:void 0},s.warn({err:m},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function dz(r,{command:e,fixtures:t}){return await t.browser.highlight(r),await mz(r,e.assertion)}async function mz(r,e){let t=!0,n,o;switch(e.type){case"ELEMENT_CONTENT":{let a=await r.textContent()??"";if(o={elementTextContent:gt(a,500,!0)},!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The content ${s} '${e.value}': ${a}`)}break}case"ELEMENT_ATTRIBUTE":{o={elementOuterHtml:gt(await r.evaluate(s=>s.cloneNode(!1).outerHTML),500,!0)};let a;try{a=await r.getAttribute(e.attr,{timeout:3e3})??""}catch(s){n=new R("AssertionFailureError",`The element does not have an attribute named ${e.attr}: ${s}`),t=!1;break}if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The attribute ${e.attr} ${s}`):n=new R("AssertionFailureError",`The attribute ${e.attr} ${s} '${e.value}': ${a}`)}break}case"ELEMENT_EXISTENCE":{switch(e.condition){case"VISIBLE":{t=await r.evaluate(async(s,c)=>{let l=Date.now();for(;Date.now()-l<c;){await new Promise(d=>setTimeout(d,250));let u=s.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(s).visibility!=="hidden"&&window.getComputedStyle(s).display!=="none")return!0}return!1},zt*1e3);break}case"EDITABLE":{t=await r.isEditable({timeout:zt*1e3});break}case"EXISTS":{t=!0;break}case"ENABLED":{t=await r.isEnabled({timeout:zt*1e3});break}case"FOCUSED":{t=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"})(e.condition)}if(t=e.negated?!t:t,!t){let a=dr(e);n=new R("AssertionFailureError",`The element ${a}`)}break}case"ELEMENT_NAME":{let a=await r.evaluate(s=>s.tagName);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})){let s=dr(e);t=!1,n=new R("AssertionFailureError",`The element tag name ${s} '${e.value}': ${a}`)}break}case"ELEMENT_STYLE":{let a=await r.evaluate((s,c)=>window.getComputedStyle(s).getPropertyValue(c),e.property);if(!Hr(a,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let s=dr(e);t=!1,e.operation==="EXISTS"?n=new R("AssertionFailureError",`The style property ${e.property} ${s}`):n=new R("AssertionFailureError",`The style property ${e.property} ${s} '${e.value}': ${a}`)}break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}return{thoughts:void 0,success:t,data:o,err:n}}function hR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as pz}from"jimp";async function ms(r,e){let t=await r.screenshot(e),n=await pz.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as fR}from"jimp";import Lg from"jpeg-js";import gz from"pixelmatch";async function SR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!pn(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},l;t.target?.elementDescriptor?l=(await i({ctx:r,tracer:e,command:t,target:t.target,cache:t.cache?.target,action:async ye=>ms(o,{locator:ye.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await ms(o,c);let u=await s.prepareGoldenScreenshotForComparison(a,t,l);if((l.height!==u.height||l.width!==u.width)&&a.warn({currHeight:l.height,currWidth:l.width,savedHeight:u.height,savedWidth:u.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-u.height)>10||Math.abs(l.width-u.width)>10){let W=`${l.width}x${l.height}`,ye=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${W}) does not match saved screenshot dimensions (${ye}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:u.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let d=await fR.fromBuffer(l.buffer),m={width:l.width,height:l.height},g=await fR.fromBuffer(u.buffer),p={width:u.width,height:u.height},h,f=m.width*m.height,E=p.width*p.height,b=Math.abs(m.height-p.height),x=Math.abs(m.width-p.width);if(f>E){let W=d.cover({w:p.width,h:p.height});l.buffer=await W.getBuffer("image/jpeg"),h="current",l.width=p.width,l.height=p.height}else if(E>f){let W=g.cover({w:m.width,h:m.height});u.buffer=await W.getBuffer("image/jpeg"),h="saved"}let v={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},A=t.threshold??.1,w=gz(Lg.decode(u.buffer).data,Lg.decode(l.buffer).data,v.data,l.width,l.height,{threshold:A,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,N=w>A*100,G=`Visual diff of ${w.toFixed(2)}% detected, which is ${N?"over":"under"} the threshold of ${A*100}%.`;if(h&&(G+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),N)throw new R("ActionFailureError",G);return{fail:N,thoughts:G,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:Lg.encode(v,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var hz=3e4;function fz(r){if(!r.body)return{};switch(r.body.type){case"json":return{content:r.body.content,contentType:"application/json"};case"form-urlencoded":{let e=new URLSearchParams;return Object.entries(r.body.content).forEach(([t,n])=>{e.append(t,n)}),{content:e.toString(),contentType:"application/x-www-form-urlencoded;charset=UTF-8"}}}}async function su({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??hz/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,p])=>g&&p)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,p])=>g&&p).forEach(([g,p])=>{a.append(g,p)});let s=a.toString(),c;if(Ai(r.url)&&(c=r.url),t&&wi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);e.info({url:c,searchParams:s,headers:i,body:r.body,method:r.method},"Making HTTP request");let u=await k((async()=>{let g=s?`${c}?${s}`:c;try{let p=fz(r);return await n(g,{headers:{...p.contentType?{"Content-Type":p.contentType}:{},...i},method:r.method,body:p.content})}catch(p){throw e.error({err:p},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${p}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let g;try{g=await u.text()}catch(p){g=`Failed to read response body: ${p}`}throw new R("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,p)=>{d[p]=g});let m={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{m.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(m.text=await u.text());return m}var Sz=5e3;async function bR({timeout:r=zt,...e}){let t=Date.now(),n=r*1e3,o=n+1e4,i,a=0,s=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 lu(e),a=Date.now();let l=a-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!i.success)await q(s,e.signal),s=Math.min(Math.floor(s*1.5),Sz);else return i}return i=await lu(e),i}async function lu({assertion:r,browser:e,autoExpandIframes:t}){switch(r.type){case"CONTENT":case"CONTENT":{let o,i=!1,a;try{let s;if(t){let c=await e.evaluateFunctionInAllFrames(yR,{value:r.value,negated:!!r.negated,returnHtml:!1});i=r.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(yR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?rn.CONTAINS:nn.CONTAINS;a=new R("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function yR({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 yz=3e4;async function ER({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??yz/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(Ai(r.url)&&(s=r.url),t&&wi(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let l=await k((async()=>{try{return await n(s,{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(!l)throw new R("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,m=await l.text();try{d=JSON.parse(m)}catch{throw new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new R("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}let u={};return l.headers.forEach((d,m)=>{u[m]=d}),{status:l.status,headers:u,json:await l.json()}}var cu=class{orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:t,logger:n,storage:o,orgId:i,localCodeEvalTools:a,uploadedFileStorage:s,visualDiffScreenshotStorage:c,options:l}){this.orgId=i,this.options=l,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=o,this.uploadedFileStorage=s,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=a,this.generator=t,this.logger=n}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:t,history:n,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[c,l]=await Promise.all([jr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${l.toString("base64")}`,d=await wo({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),m={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...fe(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:t,history:n,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,u]=await Promise.all([jr(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")}`,m=await wo({type:"ai-action",description:e,screenshot:d,serializedTree:l.serializedTree,tree:l.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:a,orgId:this.orgId}}),g={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...fe(a)},langfuseSessionId:s})}catch(p){throw new R("InternalWebAgentError",`Error generating command: ${p instanceof Error?p.message:p}`,{errOptions:{cause:p}})}}async getBrowserState(e){return jr(this.browser,e)}async locateElement(e){return await Og({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return gr({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,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:s,options:c,retriesWithAI:l=1}){let u=[];for(let d=0;d<i.length;d++){let m=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async p=>p,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(p=>p.result)),m=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",g=u.map((p,h)=>p.thoughts?`${m(o[h])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(p=>p.elementInteractedDisplayString),thoughts:g}}catch(d){if(this.throwIfClosed(),l>0)return this.logger.warn({err:d},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new R("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 gr({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&&dd(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(gd(i)||md(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(hd(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof Ir&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof R?n:new R("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:s}=o;if(t.type!=="description")throw new R("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),u=Date.now();for(;Date.now()-u<this.browser.smartWaitingTimeout;){l=Date.now();try{let d=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:t.elementDescriptor,targetName:s,logger:a});return{result:await n({locator:d.locator}),elementInteractedDisplayString:d.displayString}}catch(d){if(d.name==="AbortError")throw d;c=d,a.warn({err:d},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await q(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:t,tracer:n,target:o,originalCache:i,action:a,options:s,command:c}=e,{disableCache:l,useSelector:u,targetName:d,targetHealingInProgress:m,source:g}=s,p=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=TR(e.cache);if((!b||l)&&!Yu(o))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(p.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!lR(o.elementDescriptor,b.inputDescription)&&(p.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let x=A=>!!A&&Ns(A),v=!0;if(!x(b)){v=!1,p.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await dR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:p,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let A;try{A=await Og({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:p},this.getControllerFixtures(t))}catch(N){if(N instanceof fn&&N.updatedLocatorMemory){let G={id:-1,...i,memory:N.updatedLocatorMemory};Dc({cmd:c,key:d,newTarget:G,logger:p,updatedWithAI:!0})}throw new R("ActionFailureError",N.message)}A.frameConfig&&this.browser.setActiveFrameConfig(A.frameConfig);let _=s.disableGlobalLocatorRedirect?{locator:A.resolution.locator}:await this.attemptLocatorRedirect(A.resolution.locator,p),w=await a(_);return Dc({cmd:c,key:d,newTarget:A.target,logger:p,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),A.target.targetSource="AI_HEALED",A.target.targetUpdateTime=new Date().toUTCString(),A.target.targetUpdateLoggerTags=fe(p)),{result:w,elementInteractedDisplayString:A.resolution.displayString,thoughts:A.thoughts}}try{let A=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:p,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(A.locator);let _=s.disableGlobalLocatorRedirect?{locator:A.locator}:await this.attemptLocatorRedirect(A.locator,p),w=await a(_);if(Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.2"]),Dc({cmd:c,key:d,newTarget:b,logger:p,updatedWithAI:!1}),v){let N=A.decisions.filter(G=>G.matched);if(N.length!==1)p.warn({decisions:A.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let G=N[0].type;n.recordTargetAutoHeal({healType:G})}}return{result:w,elementInteractedDisplayString:A.displayString}}catch(A){this.throwIfClosed();let _="unknown";A instanceof Pr&&A.cacheMissReason&&(_=A.cacheMissReason),Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.9.2",`missReason:${_}`]);let w=!1;if((A instanceof Ir||dd(A)||gd(A)||hd(A)||Jf(A)||md(A)||Qf(A))&&(w=!0),A instanceof R&&!w)throw p.error({err:A},"Failed to execute action with cached target (fatal)"),A;if(f>0&&o){p.info({err:A},"Failed to execute action with cached target, retrying with AI");let N;return b.memory&&Bh(b.memory)&&(N=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:N,retriesWithAI:f,targetHealingInProgress:!0}})}throw new R("ActionFailureError",A.message,{errOptions:{cause:A}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return ms(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await q(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(n,o)}catch(l){throw this.throwIfClosed(),new R("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,t,n,o,i);return this.browser.userBrowserSettings.visualActions&&ff(n)?await this.browser.waitForDOMStability({timeout:be}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:te}),this.options?.autoFollowNewTabs&&await ZC({beforeUrl:s,command:n,beforePages:a.map(u=>u.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{Lc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>ng(e)}}async resolveCommandTemplateStrings(e,t){return Oc({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 s=n.condition;return s?.assertion.trim()?iu({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!n.assertion.trim())throw new R("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new R("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return iu({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=Qb(n.schema);if(f)throw new R("UserConfigurationError",f)}let p=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:p,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:fe(a)});if(f.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new R("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 R("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 R("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(!Ai(n.url)&&!wi(n.url,this.browser.baseUrl))throw new R("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:p=>this.browser.click(p,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 p,h;if(n.target&&xr(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:x}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:v=>this.browser.hover(v),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});p=b,h=x}let f=this.browser.getViewport()?.height??En.height,E=this.browser.getViewport()?.width??En.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:p,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new R("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let p=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:p},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new R("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await q(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(xr(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let p=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:x=>this.browser.click(x,this.createCallbacksForBrowser(this.orgId),n),options:{disableCache:i,targetName:"target",...n}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:E,data:f.downloadedFile?{downloadedFile:f.downloadedFile}:void 0};return Hc(p,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}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(xr(n.fromTarget)&&xr(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(xr(n.fromTarget)||xr(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:p,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:p[0],thoughts:h}}case"MOUSE_DRAG":{let p=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(p)||isNaN(h))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&xr(n.target)){await this.browser.mouseDragUsingVisualCoordinates(p,h,f,void 0,n.target.pixels);break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async A=>this.browser.mouseDrag(p,h,f,A.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=v}else await this.browser.mouseDrag(p,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!pn(n.target))throw new Error("Select with x/y is not supported yet");let p=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:p},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:ca(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let p={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,p);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 p;try{n.environment==="BROWSER"?(p=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:p},"Executed JavaScript in browser")):p=await zr({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 R("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(p)}catch(h){throw new R("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:p}}case"TYPE":{if(n.target&&xr(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 p=this.browser.url(),h,f,E=TR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:v,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:_=>this.browser.typeIntoTarget(n.value,_,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter,relativePosition:n.relativePosition}),options:{...n,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!b,source:ca(n)}});h=v,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 x={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Hc(p,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(xr(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:p,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:p,thoughts:h}}case"FOCUS":{if(!pn(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,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:p,thoughts:h}}case"BLUR":{if(n.target&&!pn(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:p,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:p,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 m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Hc(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;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 p=new Ez,h=bz(fetch,p),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await su({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:ul(p,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await ER({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return SR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,p=await Hw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,p=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!p)throw new R("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...p,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p;if(!n.storageState.trim())p=void 0;else if(p=await zr({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof p!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let h;try{h=yy.optional().parse(p)}catch(f){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let p=(n.timeout??zt)*1e3,h=this.generator.getAgentConfig()?.assertion;if(hR(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 b=await iu({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: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{E.cache?.memory&&as(n,E.cache?.memory.traces,a)}}let f=await gR({command:n,tracer:t,timeoutMs:p,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 p=await gr({action:async()=>bR({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:!p.success,data:p.data,thoughts:p.success?"Page assertion passed.":p.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let p=new kn(n.requestMatcher),h=this.browser.registerRequestListener(p);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 p=this.registeredListeners[n.key];if(!p)throw new R("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(p,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let p=new kn(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>p.matches({url:h.request.url,method:h.request.method}),onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Kc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let p=this.recordedRequests[n.key];if(!p)throw new R("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(p),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let p;return n.requestMatcher&&(p=new kn(n.requestMatcher)),this.browser.setHeader(n.name,n.value,p),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new kn(n.requestMatcher),async(h,f)=>{let E=await zr({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"}),b=Uy.parse(E);return new Response(b.body,{status:b.status,headers:b.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(p=>{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:fe(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 eu({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:fe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:fe(this.logger)})}};import{cloneDeep as Tz}from"lodash-es";import RR from"truncate-json";var vR=1e3,AR=5e6,vz=5*1024*1024;function xR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=RR(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.type){case"MOBILE_PRESET_STEP":wR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":wR(n),xR(n.steps,e);break;default:{let o=n;throw new Error("If Typescript complains about the line below, you missed a case or break in the switch above")}}}}function wR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function CR(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 uu(r,e){let t=Tz(r);if(xR(t,e),t.length>vR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,vR);let n=CR(t,e);if(n.length>AR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>AR;)t.pop(),n=CR(t,e);let{jsonString:o}=RR(n,vz);try{return Ut.array().parse(JSON.parse(o))}catch(i){throw e.error({serialized:n,err:i},"Could not parse serialized results into JSON structure after processing"),i}}import{AsyncLocalStorage as Az}from"async_hooks";var ps=new Az;function wz(r){ps.enterWith({activeTracers:[r]})}function Cz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function Rz(r,e){let t=ps.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return ps.run({activeTracers:n},e)}var an={globalAls:ps,initializeRootTracerContext:wz,withChildTracer:Cz,withChildTracerAsync:Rz};var Co=class r{spans;parentSection;finished=!1;startTime;endTime;constructor(e){this.startTime=e?.startTime??Date.now(),this.spans=e?.subSpans??[],this.parentSection=e}startSection(e,t){let n={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},o=new r(n);try{return an.withChildTracer(o,()=>t(o,n))}catch(i){throw n.error=i instanceof Error?i.message:String(i),i}finally{o.finish(),this.addSpan(n)}}async startAsyncSection(e,t,n){let o={type:"SECTION",name:e,startTime:Date.now(),endTime:void 0,subSpans:[],attributes:{}},i=new r(o);this.addSpan(o);try{let a;return n?.signal||n?.timeoutMs?a=await an.withChildTracerAsync(i,()=>k(t(i,o),{milliseconds:n?.timeoutMs??1/0,signal:n?.signal,message:n?.timeoutMsg??`Operation timed out after ${n?.timeoutMs??1/0}ms (${e})`})):a=await an.withChildTracerAsync(i,()=>t(i,o)),a}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}finally{i.finish()}}finish(){if(!this.finished){this.endTime=Date.now();for(let e of this.spans)e.endTime||(e.endTime=this.endTime,e.durationMs=e.endTime-e.startTime);this.parentSection&&(this.parentSection.endTime=this.endTime,this.parentSection.durationMs=this.parentSection.endTime-this.parentSection.startTime),this.finished=!0}}addSpan(e){this.spans.push(e)}startSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{a=t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}async startAsyncSpan(e,t,...n){let o={type:e,startTime:Date.now(),endTime:void 0,attributes:{}},i=n[0]??void 0;Object.assign(o,i??{}),this.addSpan(o);let a;try{i?.signal||i?.timeoutMs?a=await k(t(o),{milliseconds:i?.timeoutMs??1/0,signal:i?.signal,message:i?.timeoutMsg??`Operation timed out after ${i?.timeoutMs??1/0}ms${"name"in i?` (${i.name})`:""}`}):a=await t(o),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime}catch(s){throw o.error=s instanceof Error?s.message:String(s),o.endTime=Date.now(),o.durationMs=o.endTime-o.startTime,s}return a}getRootSpan(){return this.finished||this.finish(),{type:"SECTION",name:"root step span",startTime:this.startTime,endTime:this.endTime,subSpans:this.spans,attributes:{},durationMs:this.endTime?this.endTime-this.startTime:void 0}}};function re(){let r=an.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new Co}async function MR(r){let{driver:e,abortSignal:t,logger:n,packageName:o}=r,i;try{i=await k(e.execute("mobile: shell",{command:"dumpsys",args:["activity","recents"]}),{signal:t,milliseconds:1e4})}catch(s){t?.throwIfAborted(),n.warn({err:s,packageName:o},"Failed to read recents output while removing package");return}if(typeof i!="string"){n.warn({packageName:o,outputType:typeof i},"Unexpected dumpsys output when removing package from recents");return}let a=xz(i,o);if(a.length!==0)for(let s of a){t?.throwIfAborted();try{await e.execute("mobile: shell",{command:"am",args:["stack","remove",s.toString()]}),n.info({packageName:o,taskId:s},"Removed task from recents")}catch(c){t?.throwIfAborted(),n.warn({err:c,packageName:o,taskId:s},"Failed to remove task from recents")}}}function xz(r,e){let t=r.split("Task{");if(t.length<=1)return[];let n=new Set;for(let o of t.slice(1)){let i=`Task{${o}`;if(!i.includes(e)||i.includes("app.lawnchair/.LawnchairLauncher"))continue;let a=i.match(/taskId=(\d+)/);if(!a)continue;let[,s]=a;if(!s)continue;let c=Number.parseInt(s,10);Number.isNaN(c)||n.add(c)}return Array.from(n)}import{mkdirSync as $z}from"fs";import{tmpdir as qz}from"os";import NR from"path";import{diff as Wz}from"deep-object-diff";import{cloneDeep as jz}from"lodash-es";import IR from"fontoxpath";import Mz from"@prettier/plugin-xml";import _z from"prettier";import{DOMParser as Pz,XMLSerializer as Iz}from"slimdom";var Oz=new Set(["android.webkit.webview","com.facebook.react.views.webview.reactwebview","com.tencent.smtt.sdk.webview","com.tencent.smtt.sdk.x5webview","org.xwalk.core.xwalkview","com.uc.webview.export.webview"]);function gs(r){let e=r.toLowerCase();return e.endsWith("webview")||Oz.has(e)}function Lz(r){let e=["android.widget.","android.view.","android.webkit.","android.app.","android.support.","androidx.","com.android.inputmethod."];for(let t of e)if(r.startsWith(t))return r.substring(t.length);return r}var Nz=new Set(["index","package","a11y-important","screen-reader-focusabl"]),Dz=new Set(["selected","checked","checkable","clickable","enabled","focusable","focused","long-clickable","password","scrollable","selected","showing-hint","context-clickable","multiline","text-entry-key","heading","dismissable","screen-reader-focusable","content-invalid","a11y-focused"]),kz=new Set(["text","hint"]),Uz=new Set(["live-region","drawing-order"]),Fz=new Set(["displayed","enabled"]);function Bz(r,e){let t={};for(let[n,o]of Object.entries(e))Nz.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||Dz.has(n)&&o==="false"||kz.has(n)&&o===""||Fz.has(n)&&o==="true"||Uz.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function _R(r,e,t){let{prunedDocument:n,idToElement:o,prunedIdToElement:i,idCounter:a,opts:s}=r,c=a.value++;t.setAttribute("id",String(c));let l={};for(let m of e.attributes){let g=m.name,p=m.value;p!=null&&(l[g]=String(p))}let u=Bz(e.tagName,l);for(let[m,g]of Object.entries(u))t.setAttribute(m,g);if(o.set(c,e),i.set(c,t),gs(e.tagName)){let m=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&m.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);m.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4239
4239
|
${m}
|
|
4240
|
-
`));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let g=m.nodeType;if(g===3){let p=m.nodeValue;p&&p.trim().length>0&&t.appendChild(n.createTextNode(p));continue}if(g===1){let p=m;if(!Gz(p,s?.viewportBounds))continue;let h=n.createElement(Lz(p.tagName));_R(r,p,h),t.appendChild(h)}}}function zz(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;_R(a,e,s);let c=new Iz().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function PR(r,e){let t=new Pz,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:s,xml:c}=zz(t,i,o,e);return{xml:await _z.format(c,{parser:"xml",plugins:[Mz],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function Hz(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function du(r,e){let t=r.idToElement.get(e);if(t)return Hz(t)}function Ng(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Ro(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function Gz(r,e){if(!e)return!0;let t=Ro(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function Dg(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function LR({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Ro(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=du(t.graph,r.id)??"",a=Ng(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Dg(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:g,requirements:p})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=du(t.graph,g);return f?{xPath:f,requirements:{requiredText:p.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Dg(h,p.attributesRequired),requiredBounds:p.boundsRequired}}:void 0}).filter(g=>!!g));let m;return gs(n.tagName)&&r.inWebview!==!1?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},{target:m,resolvedNode:n}}var OR=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Ro(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function mu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=re();if(e.type==="WEBVIEW")return Vz(e,r);let a=IR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of m){let p=IR.evaluateXPathToFirstNode(g.xPath,o);if(!p)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);OR(p,g.requirements)}})}let s=Ro(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");OR(a,e.requirements,e.bounds);let c;for(let[m,g]of n.idToElement.entries())if(g===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=Ng(n,c)??l,u=du(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function Vz(r,e){let{stateManager:t,logger:n,signal:o}=e,i=re(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let s=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,l=await i.startAsyncSection("Resolve target in webview",()=>s.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:l}}}function Pi(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;gl(e)&&(e[t]={...e[t],[n]:ml.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function pu(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache};let{resolvedNode:e,...t}=r;return{...t}}var at=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let i=await t.startAsyncSection("Get emulator state",async()=>{let d=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),m=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:m}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let m=await this.generator.getElementLocation({description:e,screenXml:i.emulatorState.graph.xml,screenshot:i.screenshot},{logger:this.logger,loggerTags:fe(this.logger),abortSignal:this.aborter.controller?.signal});return d.result=m,m})}catch(d){throw this.throwIfAborted(),this.logger.error({err:d},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${d instanceof Error?d.message:d}`)}if(a.id===-1)throw new Sn(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=LR({aiResponse:a,description:e,emulatorState:i.emulatorState});if(s.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:s.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:{...s,resolvedNode:c},thoughts:a.thoughts};let{browserLocateResult:l,browserController:u}=await t.startAsyncSpan("TARGET_RESOLUTION",async d=>{let m=await this.stateManager.getActiveWebview();if(!m||!m.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await m.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:m.browserController}});return{resolvedTarget:{...s,controller:u,resolution:l.resolution,browserCache:l.target},thoughts:l.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c,skipFetchingFullWebviewContent:l=!1,removeWebviewContent:u=!1}=e,d=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,m=e.retriesWithAI??1,g=!1,p=jz(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,p=void 0),s&&(g=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:p?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,p=void 0),!p){m--,this.logger.info({description:n,cacheBustedBeforeAction:g},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u});h=E.thoughts;let b=await t(E.resolvedTarget);return Pi({command:o,cacheKey:i,targetName:a,updatedCache:E.resolvedTarget,updatedWithAI:!0}),{result:b,thoughts:h}}let f;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),f=await this.stateManager.getDomState();let{resolvedTarget:E,updatedCache:b}=await c.startAsyncSection("Resolve target cache",async(v,A)=>{let{resolvedTarget:_}=await mu({target:p,domState:f,stateManager:this.stateManager,logger:this.logger}),w=pu(_),N=Wz(p,w);return N&&Object.keys(N).length>0&&this.logger.info({cacheDiffs:N},"Successfully resolved target with cache"),A.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml,{resolvedTarget:_,updatedCache:w}}),x=await t(E);return Pi({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.1"]),{result:x,thoughts:"Successfully executed preset action with cache."}}catch(E){if(p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.1"]),this.throwIfAborted(),m>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:m-1});throw new Error(`ActionFailureError: ${E instanceof Error?E.message:E}`,{cause:E})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}getBoundsFromNativeCache(e){let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new Error(`ActionFailureError: Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n,edgeMarginPercent:o=.1}){let i=e.left+e.width/2,a=e.top+e.height/2;if(t==="up"||t==="down"){let s=e.height*o,c=e.top+s,l=e.top+e.height-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:i,startY:t==="down"?l:c,actualDelta:d}}else{let s=e.width*o,c=e.left+s,l=e.left+e.width-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:t==="right"?l:c,startY:a,actualDelta:d}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,c=t;o==="up"||o==="down"?c=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:c},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function Kz(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var Ii=class extends at{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=NR.join(qz(),"momentic","downloads"),s=NR.join(a,this.orgId,i);return $z(s,{recursive:!0}),s}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=re(),n=Kz(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:s,y:c})},{name:`Tap at coordinates ${s}, ${c}`}),{success:!0,message:`Tapped at ${s}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var zn=class extends at{async doPress({keycode:e,longPress:t}){await re().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var DR=25,gu=class extends at{async doType(e){let t=re();if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??DR};o.attributes.options=i;let{controller:a,resolution:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Ii(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=re(),n=e.keyPressDelayMs??DR;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){if(this.throwIfAborted(),await this.driver.isKeyboardShown())return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=re();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new zn(this.constructPerformerParams()).doPress({keycode:67})}};import $t from"zod";var kR=.8,Hn=.2,Yz=$t.object({navigationBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()}),statusBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()})}),Oi=class extends at{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Yz.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getInsetBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getInsetBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getInsetBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getInsetBoundsFromViewport(e){let t=Math.floor(e.width*Hn),n=Math.floor(e.height*Hn);return{left:e.x+t,top:e.y+n,width:Math.max(1,e.width-t*2),height:Math.max(1,e.height-n*2)}}getInsetBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n,c=Math.floor(a*Hn),l=Math.floor(s*Hn);return{left:t+c,top:n+l,width:Math.max(1,a-c*2),height:Math.max(1,s-l*2)}}async executeSwipe(e){let t=re();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>re().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*Hn),s=Math.floor(i*Hn);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+a,top:n.bounds[1]+s,width:Math.max(1,o-a*2),height:Math.max(1,i-s*2)}})}async swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,resolution:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",c=await i.locator.boundingBox();if(!c)throw new Error("Failed to get bounds for webview container");let l=Math.floor(c.width*Hn),u=Math.floor(c.height*Hn),d=Math.max(1,c.width-l*2),m=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+m/2},p=(s?m:d)*(t.viewportPercent??kR)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=p,await o.browser.mouseDragUsingVisualCoordinates(s?0:p,s?p:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=kR,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,s;t==="up"||t==="down"?(a=i.height*n,s=Math.floor(a/(o/1e3))):(a=i.width*n,s=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=s,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:s}])}};import{execSync as GR}from"child_process";import Qz from"pixelmatch";import{_android as Zz,chromium as e1}from"playwright";import{PNG as VR}from"pngjs";import{z as Ge}from"zod";var UR=Ge.object({"Android-Package":Ge.string(),Browser:Ge.string(),"Protocol-Version":Ge.string(),"User-Agent":Ge.string(),"V8-Version":Ge.string(),"WebKit-Version":Ge.string(),webSocketDebuggerUrl:Ge.string()}),FR=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),BR=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),zR=Ge.array(BR.extend({info:UR.optional(),pages:Ge.array(FR).optional()})),l_e=Ge.array(BR.extend({info:UR,pages:Ge.array(FR)}));function kg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=VR.sync.read(n),a=VR.sync.read(o);if(i.width!==a.width||i.height!==a.height)return 100;let s=i.width,c=i.height,l=Buffer.alloc(s*c*4);return Qz(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var hu=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,m;if(l)m=l;else{t.warn("No playwright device provided, using ADB to find device");let p=(await Zz.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(p.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(p.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);m=p[0]}return new r({driver:e,context:d,logger:t,device:m,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=2){let t=re(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:3e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await re().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1;for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(kg(c,u)<=o){l=!0;break}c=u,await q(250,t)}l||(a.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(l=>l.id===i))continue;let s=a.getAttribute("content-desc");(gs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Ro(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await re().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await re().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(c){this.logger.error({err:c},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let i=e?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,a=await this.getPageSource();return{graph:await PR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await re().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.getWindowRect();return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.getPageSource(),this.throwIfAborted();let e=await this.getCurrentPackage(),t=await this.getDetailedContexts();if(!t){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let n=Date.now(),o=new Set;for(let i of t){if(this.throwIfAborted(),i.webview==="NATIVE_APP")continue;let a=i.info["Android-Package"];if(e&&a!==e&&this.logger.warn({packageName:a,currentPkgName:e},"Ignoring webview not in the active package"),o.add(i.webview),!this.webviews.has(i.webview)||!this.webviews.get(i.webview)?.active){let s={contextId:i.webview,packageName:a,active:!1,lastSeen:n,socketName:i.proc.startsWith("@")?i.proc.substring(1):i.proc};this.logger.info({contextId:s.contextId,packageName:s.packageName,socketName:s.socketName},"New webview detected"),this.webviews.set(i.webview,s);let c;if(a==="com.android.chrome"?(this.logger.info({webviewInfo:s},`Connecting Playwright to Android Chrome: ${i.webview}`),c=await this.connectPlaywrightToChrome(s),this.logger.info(`Connected Playwright to Android Chrome: ${i.webview}`)):(this.logger.info({webviewInfo:s},`Connecting Playwright to webview: ${i.webview}`),c=await this.connectPlaywrightToWebview(a,s.socketName),c&&this.logger.info(`Connected Playwright to webview ${i.webview}`)),!c)continue;s.browserController=c,s.active=!0}}for(let[i,a]of this.webviews.entries())!o.has(i)&&a.active&&(this.logger.info(`Disconnecting dead webview ${i}`),this.disconnectPlaywrightFromWebview(a),a.active=!1)}async getActiveWebview(){await re().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=GR(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await re().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=zR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4240
|
+
`));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let g=m.nodeType;if(g===3){let p=m.nodeValue;p&&p.trim().length>0&&t.appendChild(n.createTextNode(p));continue}if(g===1){let p=m;if(!Gz(p,s?.viewportBounds))continue;let h=n.createElement(Lz(p.tagName));_R(r,p,h),t.appendChild(h)}}}function zz(r,e,t,n){let o=r.parseFromString("<hierarchy/>","text/xml"),i=new Map,a={prunedDocument:o,idToElement:t,prunedIdToElement:i,idCounter:{value:0},opts:n},s=o.documentElement;_R(a,e,s);let c=new Iz().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function PR(r,e){let t=new Pz,n=t.parseFromString(r,"text/xml"),o=new Map,i=n.documentElement;if(!i)throw new Error("No root element found in XML");if(i.tagName!=="hierarchy")throw new Error("No hierarchy element found in XML");let{prunedDocument:a,prunedIdToElement:s,xml:c}=zz(t,i,o,e);return{xml:await _z.format(c,{parser:"xml",plugins:[Mz],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function Hz(r){let e=[],t=r;for(;t;){let n=t.tagName,o=t.parentElement,i=1;if(o){let a=Array.from(o.children).filter(s=>s.tagName===n);for(let s=0;s<a.length;s++)if(a[s]===t){i=s+1;break}}e.unshift(`${n}[${i}]`),t=o}return`/${e.join("/")}`}function du(r,e){let t=r.idToElement.get(e);if(t)return Hz(t)}function Ng(r,e){let t=r.idToElement.get(e);if(!t)return;let n=t.cloneNode(!0);for(let o of Array.from(n.children)){let i=o;for(let a of Array.from(i.children))i.removeChild(a)}return n.outerHTML}function Ro(r){if(!r.hasAttribute("bounds"))return;let e=r.getAttribute("bounds");if(!e)return;let t=e.match(/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/);if(t){let n=parseInt(t[1],10),o=parseInt(t[2],10),i=parseInt(t[3],10),a=parseInt(t[4],10);if(Number.isFinite(n)&&Number.isFinite(o)&&Number.isFinite(i)&&Number.isFinite(a))return[n,o,i,a]}}function Gz(r,e){if(!e)return!0;let t=Ro(r);if(!t||t.length<4)return!0;let n=t[0],o=t[1],i=t[2],a=t[3];return!(i<=e.left||n>=e.right||a<=e.top||o>=e.bottom)}function Dg(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function LR({aiResponse:r,description:e,emulatorState:t}){let n=t.graph.idToElement.get(r.id);if(!n)throw new Error(`Could not find node with id: ${r.id}`);let o=Ro(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=du(t.graph,r.id)??"",a=Ng(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Dg(s,r.requirements?.attributesRequired),u={requiredText:r.requirements?.textRequired?s?.getAttribute("text")??void 0:void 0,requiredAttributes:c,requiredBounds:r.requirements?.boundsRequired},d=[];r.additionalElements&&(d=r.additionalElements.map(({id:g,requirements:p})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=du(t.graph,g);return f?{xPath:f,requirements:{requiredText:p.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Dg(h,p.attributesRequired),requiredBounds:p.boundsRequired}}:void 0}).filter(g=>!!g));let m;return gs(n.tagName)&&r.inWebview!==!1?m={type:"WEBVIEW",resolvedDescription:e,xPath:i}:m={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},{target:m,resolvedNode:n}}var OR=(r,e,t)=>{if(!e)return;let{requiredAttributes:n,requiredText:o,requiredBounds:i}=e;if(o!==void 0){let a=r.getAttribute("text")??void 0;if(a!==o)throw new Error(`ActionFailureError: Resolved element text mismatch: expected ${o}, got ${a}`)}if(n)for(let[a,s]of Object.entries(n)){let c=r.getAttribute(a)??void 0;if(c!==s)throw new Error(`ActionFailureError: Attribute ${a} mismatch: expected ${s}, got ${c}`)}if(i&&t){let a=Ro(r);if(!a||a.length!==t.length)throw new Error("ActionFailureError: Resolved element has no bounds or unexpected bounds format");if(!a.every((c,l)=>c===t[l]))throw new Error(`ActionFailureError: Bounds changed from [${t.join(",")} ] to [${a.join(",")} ]`)}};async function mu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=re();if(e.type==="WEBVIEW")return Vz(e,r);let a=IR.evaluateXPathToFirstNode(e.xPath,o,null,null);if(!a)throw new Error(`ActionFailureError: Could not resolve cached target via XPath: ${e.xPath}`);if(e.requiredRelatedElements){let m=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of m){let p=IR.evaluateXPathToFirstNode(g.xPath,o);if(!p)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);OR(p,g.requirements)}})}let s=Ro(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");OR(a,e.requirements,e.bounds);let c;for(let[m,g]of n.idToElement.entries())if(g===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=Ng(n,c)??l,u=du(n,c)??u),{resolvedTarget:{...e,resolvedNode:a,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function Vz(r,e){let{stateManager:t,logger:n,signal:o}=e,i=re(),a=await t.getActiveWebview();if(!a||!a.browserController)throw new Error("No browser controller is attached to the requested webview");let s=a.browserController.browser;if(!r.browserCache)throw new Error("No browser target available on cache");let c=r.browserCache,l=await i.startAsyncSection("Resolve target in webview",()=>s.resolveTarget(null,c,{logger:n,signal:o}));return{resolvedTarget:{...r,controller:a.browserController,resolution:l}}}function Pi(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;gl(e)&&(e[t]={...e[t],[n]:ml.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function pu(r){if(r.type==="WEBVIEW")return{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache};let{resolvedNode:e,...t}=r;return{...t}}var at=class{driver;generator;stateManager;logger;fixtures;aborter;orgId;constructor(e){this.stateManager=e.stateManager,this.generator=e.generator,this.driver=e.driver,this.logger=e.logger,this.fixtures=e.fixtures,this.aborter=e.aborter,this.orgId=e.orgId}async findElement({description:e,tracer:t,skipFetchingFullWebviewContent:n=!1,removeWebviewContent:o=!1}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let i=await t.startAsyncSection("Get emulator state",async()=>{let d=await this.stateManager.getDomState({skipFetchingFullWebviewContent:n,removeWebviewContent:o}),m=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:d,screenshot:m}}),a;try{a=await t.startAsyncSpan("AI_LOCATOR_CALL",async d=>{let m=await this.generator.getElementLocation({description:e,screenXml:i.emulatorState.graph.xml,screenshot:i.screenshot},{logger:this.logger,loggerTags:fe(this.logger),abortSignal:this.aborter.controller?.signal});return d.result=m,m})}catch(d){throw this.throwIfAborted(),this.logger.error({err:d},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${d instanceof Error?d.message:d}`)}if(a.id===-1)throw new Sn(a.thoughts??"No matching element found");let{target:s,resolvedNode:c}=LR({aiResponse:a,description:e,emulatorState:i.emulatorState});if(s.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:s.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:{...s,resolvedNode:c},thoughts:a.thoughts};let{browserLocateResult:l,browserController:u}=await t.startAsyncSpan("TARGET_RESOLUTION",async d=>{let m=await this.stateManager.getActiveWebview();if(!m||!m.browserController)throw new Error("No browser controller is attached to the requested webview");let g=await m.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return d.result={serializedElement:g.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:g,browserController:m.browserController}});return{resolvedTarget:{...s,controller:u,resolution:l.resolution,browserCache:l.target},thoughts:l.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c,skipFetchingFullWebviewContent:l=!1,removeWebviewContent:u=!1}=e,d=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,m=e.retriesWithAI??1,g=!1,p=jz(d),h;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),g=!0,p=void 0),s&&(g=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:p?.resolvedDescription},"Cache description mismatch, clearing it automatically"),g=!0,p=void 0),!p){m--,this.logger.info({description:n,cacheBustedBeforeAction:g},"Prompting AI for a new element location");let E=await this.findElement({description:n,tracer:c,skipFetchingFullWebviewContent:l,removeWebviewContent:u});h=E.thoughts;let b=await t(E.resolvedTarget);return Pi({command:o,cacheKey:i,targetName:a,updatedCache:E.resolvedTarget,updatedWithAI:!0}),{result:b,thoughts:h}}let f;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),f=await this.stateManager.getDomState();let{resolvedTarget:E,updatedCache:b}=await c.startAsyncSection("Resolve target cache",async(v,A)=>{let{resolvedTarget:_}=await mu({target:p,domState:f,stateManager:this.stateManager,logger:this.logger}),w=pu(_),N=Wz(p,w);return N&&Object.keys(N).length>0&&this.logger.info({cacheDiffs:N},"Successfully resolved target with cache"),A.attributes.serializedElement=_.type==="WEBVIEW"?_.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":_.elementOnlySerializedXml,{resolvedTarget:_,updatedCache:w}}),x=await t(E);return Pi({command:o,cacheKey:i,targetName:a,updatedCache:b,updatedWithAI:!1}),p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.2"]),{result:x,thoughts:"Successfully executed preset action with cache."}}catch(E){if(p.type!=="WEBVIEW"&&Et.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.9.2"]),this.throwIfAborted(),m>0)return this.logger.warn({err:E},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:m-1});throw new Error(`ActionFailureError: ${E instanceof Error?E.message:E}`,{cause:E})}}constructPerformerParams(){return{stateManager:this.stateManager,generator:this.generator,driver:this.driver,logger:this.logger,fixtures:this.fixtures,aborter:this.aborter,orgId:this.orgId}}getBoundsFromNativeCache(e){let[t,n,o,i]=e.bounds;if(t===void 0||n===void 0||o===void 0||i===void 0)throw new Error(`ActionFailureError: Native element cache has incomplete bounds: [${e.bounds.join(", ")}]`);return{left:t,top:n,width:o-t,height:i-n}}calculateSwipeCoordinates({containerBounds:e,direction:t,desiredDelta:n,edgeMarginPercent:o=.1}){let i=e.left+e.width/2,a=e.top+e.height/2;if(t==="up"||t==="down"){let s=e.height*o,c=e.top+s,l=e.top+e.height-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:i,startY:t==="down"?l:c,actualDelta:d}}else{let s=e.width*o,c=e.left+s,l=e.left+e.width-s,u=l-c,d=Math.min(Math.abs(n),u);return{startX:t==="right"?l:c,startY:a,actualDelta:d}}}invertDirection(e){if(e==="up")return"down";if(e==="down")return"up";if(e==="left")return"right";if(e==="right")return"left";throw new Error(`Unreachable code: ${e}`)}async performRawSwipe({startX:e,startY:t,deltaPixels:n,direction:o,durationMs:i=300}){let a=Math.abs(n),s=e,c=t;o==="up"||o==="down"?c=o==="up"?t-a:t+a:s=o==="left"?e-a:e+a,await this.driver.performActions([{type:"pointer",id:"finger1",parameters:{pointerType:"touch"},actions:[{type:"pointerMove",duration:0,x:e,y:t},{type:"pointerDown",button:0},{type:"pause",duration:100},{type:"pointerMove",duration:i,x:s,y:c},{type:"pointerUp",button:0}]}]),await this.driver.releaseActions()}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}get abortSignal(){return this.aborter.controller?.signal}};function Kz(r){let e={relativePosition:r.relativePosition};if(r.doubleTap&&r.longPress)throw new Error("UserConfigurationError: Cannot specify both doubleTap and longPress");return r.doubleTap?{...e,doubleTap:!0,doubleTapDelayMs:r.doubleTapDelayMs}:r.longPress?{...e,longPress:!0,longPressDurationMs:r.longPressDurationMs}:e}var Ii=class extends at{async tapOnAbsoluteCoordinates(e){let t=e.x,n=e.y;if(this.logger.info({x:t,y:n},"Tap at coordinates"),e.longPress)return await this.driver.executeScript("mobile: longClickGesture",[{x:t,y:n,duration:e.longPressDurationMs??2e3}]);if(e.doubleTap){await this.driver.tap({x:t,y:n});let o=e.doubleTapDelayMs??100;await new Promise(i=>setTimeout(i,o))}await this.driver.tap({x:t,y:n})}async tapOnNativeTarget(e,t){let[n,o,i,a]=e.bounds,s=i-n,c=a-o,l=t?.relativePosition?.x??s/2,u=t?.relativePosition?.y??c/2;l=Math.max(0,Math.min(l,s)),u=Math.max(0,Math.min(u,c));let d=n+l,m=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:m,...t}),{x:d,y:m}}async tapOnWebviewTarget(e,t){let{controller:n}=e;return(await n.browser.click(e.resolution,{createIsolatedFolder:()=>{let i=Math.random().toString(36).substring(4),a=NR.join(qz(),"momentic","downloads"),s=NR.join(a,this.orgId,i);return $z(s,{recursive:!0}),s}},{delayMs:t?.longPress?t?.longPressDurationMs??2e3:void 0,relativePosition:t?.relativePosition,doubleClick:t?.doubleTap})).coordinates}async tapOnTarget({target:e,options:t}){return await re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.attributes.options=t,"type"in e&&e.type==="NATIVE"?o.attributes.point=await this.tapOnNativeTarget(e,t):(o.withinWebview=!0,o.attributes.point=await this.tapOnWebviewTarget(e,t))},{name:"Tap on target"})}async executeTap({command:e}){let t=re(),n=Kz(e);if(e.target.type==="coordinates"){let a=await this.driver.getWindowSize(),s=e.target.xPercent*a.width,c=e.target.yPercent*a.height;return await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.tapOnAbsoluteCoordinates({...n,x:s,y:c})},{name:`Tap at coordinates ${s}, ${c}`}),{success:!0,message:`Tapped at ${s}, ${c}`}}let o=e.target.description,{thoughts:i}=await this.wrapTargetingAction({command:e,tracer:t,action:a=>this.tapOnTarget({target:a,options:n}),description:o});return{success:!0,message:i}}};var zn=class extends at{async doPress({keycode:e,longPress:t}){await re().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var DR=25,gu=class extends at{async doType(e){let t=re();if(!e.target){if(e.clearContent)throw new Error("UserConfigurationError: clearing content is only supported when a target is provided to the Type step");return await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for page to stabilize before typing"}),await this.sendKeys(e),{success:!0,message:"Successfully executed type action"}}if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Type step");let{thoughts:n}=await this.wrapTargetingAction({command:e,tracer:t,action:async o=>{"type"in o&&o.type==="NATIVE"?await this.doNativeType(e,o):await this.doWebviewType(e,o)},description:e.target.description});return{success:!0,message:n}}async doWebviewType(e,t){await re().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??DR};o.attributes.options=i;let{controller:a,resolution:s}=t;await a.browser.typeIntoTarget(e.text,s,i)},{name:"Typing within web view"})}async doNativeType(e,t){let n=new Ii(this.constructPerformerParams());e.clearContent?(await n.tapOnNativeTarget(t,{longPress:!0}),await this.clearContent()):await n.tapOnNativeTarget(t),await this.stateManager.waitForScreenshotStability({timeoutMs:3e3,signal:this.aborter.controller?.signal,reason:"Waiting for keyboard to appear before typing"}),await this.sendKeys(e)}async sendKeys(e){let t=re(),n=e.keyPressDelayMs??DR;await t.startAsyncSection("Waiting for system keyboard to open",async(o,i)=>{let a=Date.now();for(;Date.now()-a<3e3;){if(this.throwIfAborted(),await this.driver.isKeyboardShown())return;await new Promise(s=>setTimeout(s,500))}i.attributes.timedOut=!0}),n?await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.updateSettings({keyInjectionDelay:n}),await this.driver.keys(e.text),await this.driver.updateSettings({keyInjectionDelay:0})},{name:"Typing keys with a delay"}):await t.startAsyncSpan("EMULATOR_INTERACTION",async()=>{await this.driver.keys(e.text)},{name:"Typing keys"})}async clearContent(){let e=re();try{await e.startAsyncSection("Clearing any content from the focused field",()=>this.clearContentHelper())}catch(t){this.logger.warn({err:t},"Failed to find select all button, continuing...")}}async clearContentHelper(){let e=this.driver.$('//android.widget.LinearLayout[@content-desc="Select all" and @clickable="true"]');await e.waitForExist({timeout:750}),await e.click(),await new zn(this.constructPerformerParams()).doPress({keycode:67})}};import $t from"zod";var kR=.8,Hn=.2,Yz=$t.object({navigationBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()}),statusBar:$t.object({visible:$t.boolean(),x:$t.number(),y:$t.number(),width:$t.number(),height:$t.number()})}),Oi=class extends at{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=Yz.parse(await this.driver.executeScript("mobile: getSystemBars",[]));n=this.getInsetBoundsFromViewport(t),o.navigationBar.visible&&(n.height=Math.max(1,n.height-o.navigationBar.height)),o.statusBar.visible&&(n.top+=o.statusBar.height,n.height=Math.max(1,n.height-o.statusBar.height))}catch(o){this.logger.warn({err:o},"Failed to get system bars, using hardcoded bounds"),n=this.getInsetBoundsFromViewport(t)}break;case"OPEN_WEBVIEW":{let o=await this.stateManager.getActiveWebviewNodes();if(o.length===0)throw new Error("No active webviews found");if(o.length>1){let a=o.map(s=>({id:s.id,ele:s.originalElement.outerHTML,bounds:s.bounds}));throw new Error(`Multiple active webviews found. Momentic currently only supports a single active webview at a time. Discovered nodes: ${JSON.stringify(a)}`)}let i=o[0]?.bounds;if(!i)throw new Error("No bounds found for active webview");n=this.getInsetBoundsFromBounds(i);break}default:{let o=e;throw new Error("If Typescript complains about the line above, you missed a switch case")}}return n}getInsetBoundsFromViewport(e){let t=Math.floor(e.width*Hn),n=Math.floor(e.height*Hn);return{left:e.x+t,top:e.y+n,width:Math.max(1,e.width-t*2),height:Math.max(1,e.height-n*2)}}getInsetBoundsFromBounds(e){let t=e[0],n=e[1],o=e[2],i=e[3],a=o-t,s=i-n,c=Math.floor(a*Hn),l=Math.floor(s*Hn);return{left:t+c,top:n+l,width:Math.max(1,a-c*2),height:Math.max(1,s-l*2)}}async executeSwipe(e){let t=re();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:o,startY:i,deltaPixels:a}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async s=>{s.attributes.startX=o,s.attributes.startY=i,s.attributes.deltaPixels=a,s.attributes.direction=e.direction,await this.performRawSwipe({startX:o,startY:i,deltaPixels:a,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0,message:"Successfully executed swipe action"}}if(e.scrollableElement.type!=="CUSTOM"){let o=await this.driver.getWindowRect(),i=await this.getHardcodedScrollableElementBounds(e.scrollableElement,o);return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{await this.swipeByAbsoluteCoordinates({span:a,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:i})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0,message:"Successfully executed swipe action"}}let{thoughts:n}=await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async o=>re().startAsyncSpan("EMULATOR_INTERACTION",async a=>"type"in o&&o.type==="NATIVE"?this.scrollInNativeContainer({span:a,cmd:e,target:o}):(a.withinWebview=!0,this.swipeInWebview({span:a,cmd:e,target:o})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t});return{success:!0,message:n}}async scrollInNativeContainer({span:e,cmd:t,target:n}){let o=n.bounds[2]-n.bounds[0],i=n.bounds[3]-n.bounds[1],a=Math.floor(o*Hn),s=Math.floor(i*Hn);await this.swipeByAbsoluteCoordinates({span:e,direction:t.direction,percent:t.viewportPercent,durationMs:t.durationMs,containerBounds:{left:n.bounds[0]+a,top:n.bounds[1]+s,width:Math.max(1,o-a*2),height:Math.max(1,i-s*2)}})}async swipeInWebview({span:e,cmd:t,target:n}){let{controller:o,resolution:i}=n;if(!o.browser.getViewport())throw new Error("Failed to get viewport size from webview");let s=t.direction==="down"||t.direction==="up",c=await i.locator.boundingBox();if(!c)throw new Error("Failed to get bounds for webview container");let l=Math.floor(c.width*Hn),u=Math.floor(c.height*Hn),d=Math.max(1,c.width-l*2),m=Math.max(1,c.height-u*2),g={x:c.x+l+d/2,y:c.y+u+m/2},p=(s?m:d)*(t.viewportPercent??kR)*(s?t.direction==="down"?1:-1:t.direction==="right"?1:-1);e.attributes.startPoint=g,e.attributes.scrollPixelAmount=p,await o.browser.mouseDragUsingVisualCoordinates(s?0:p,s?p:0,10,t.durationMs,g)}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=kR,durationMs:o=500,containerBounds:i}){e.attributes.containerBounds=i;let a,s;t==="up"||t==="down"?(a=i.height*n,s=Math.floor(a/(o/1e3))):(a=i.width*n,s=Math.floor(a/(o/1e3))),e.attributes.pixelDelta=a,e.attributes.pixelsPerSecond=s,await this.driver.executeScript("mobile: swipeGesture",[{...i,direction:t,percent:n,speed:s}])}};import{execSync as GR}from"child_process";import Qz from"pixelmatch";import{_android as Zz,chromium as e1}from"playwright";import{PNG as VR}from"pngjs";import{z as Ge}from"zod";var UR=Ge.object({"Android-Package":Ge.string(),Browser:Ge.string(),"Protocol-Version":Ge.string(),"User-Agent":Ge.string(),"V8-Version":Ge.string(),"WebKit-Version":Ge.string(),webSocketDebuggerUrl:Ge.string()}),FR=Ge.object({description:Ge.string(),devtoolsFrontendUrl:Ge.string(),id:Ge.string(),title:Ge.string(),type:Ge.string(),url:Ge.string(),webSocketDebuggerUrl:Ge.string()}),BR=Ge.object({proc:Ge.string(),webview:Ge.string(),webviewName:Ge.string()}),zR=Ge.array(BR.extend({info:UR.optional(),pages:Ge.array(FR).optional()})),c_e=Ge.array(BR.extend({info:UR,pages:Ge.array(FR)}));function kg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=VR.sync.read(n),a=VR.sync.read(o);if(i.width!==a.width||i.height!==a.height)return 100;let s=i.width,c=i.height,l=Buffer.alloc(s*c*4);return Qz(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var hu=class r{driver;limbarClient;device;currentContext;logger;webviews=new Map;fixtures;orgId;options;aborter;constructor({driver:e,context:t,limbarClient:n,logger:o,device:i,fixtures:a,orgId:s,options:c,aborter:l}){this.driver=e,this.limbarClient=n,this.device=i,this.currentContext=t,this.logger=o,this.fixtures=a,this.orgId=s,this.options=c,this.aborter=l;for(let u of["SIGINT","SIGTERM"])process.on(u,async()=>{await this.cleanupWebviews()})}static async init({driver:e,logger:t,fixtures:n,limbarClient:o,orgId:i,adbPort:a,options:s,aborter:c,playwrightDevice:l}){let u=await e.getContext(),d=typeof u=="string"?u:u.id,m;if(l)m=l;else{t.warn("No playwright device provided, using ADB to find device");let p=(await Zz.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(p.length===0)throw new Error(`Momentic found no devices listening on port ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);if(p.length>1)throw new Error(`Momentic found multiple devices on the ports ${a} or ${a-1}. This can occur if Android Studio reuses existing emulators. Please run 'adb emu kill' and 'adb disconnect' and retry.`);m=p[0]}return new r({driver:e,context:d,logger:t,device:m,fixtures:n,orgId:i,options:s,aborter:c,limbarClient:o})}async getContexts(){let e=await this.driver.getContexts({}),t=Array.from(this.webviews.values());return{contexts:e,webviews:t.map(n=>({contextId:n.contextId,packageName:n.packageName,active:n.active,hasPlaywright:!!n.browserController,lastSeen:n.lastSeen,socketName:n.socketName}))}}async getRawScreenshotBase64(e=2){let t=re(),n;for(let o=0;o<e;o++)try{return await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>await this.driver.takeScreenshot(),{name:"Take screenshot",signal:this.aborter.controller?.signal,timeoutMs:3e3})}catch(i){if(n=i,o===e-1)throw i}throw new Error(`Failed to take screenshot: ${n}`)}async getCurrentScreenshotPngString(){return`data:image/png;base64,${await this.getRawScreenshotBase64(1)}`}async waitForScreenshotStability({timeoutMs:e,signal:t,reason:n,tolerancePercent:o=1}){await re().startAsyncSection("Waiting for stability",async(i,a)=>{a.attributes.reason=n;let s=Date.now(),c,l=!1;for(;Date.now()-s<e;){if(t?.throwIfAborted(),!c){c=await this.getRawScreenshotBase64();continue}let u=await this.getRawScreenshotBase64();if(kg(c,u)<=o){l=!0;break}c=u,await q(250,t)}l||(a.attributes.timedOut=!0,this.logger.warn({purpose:n},"Timed out waiting for screenshot stability"))})}async getCurrentPackage(){let e=await this.driver.execute("mobile: getCurrentPackage");return typeof e=="string"?e:void 0}async getActiveWebviewNodes(){await this.refreshWebviews();let t=(await this.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph,n=await this.getCurrentPackage(),o=[];for(let[i,a]of t.idToElement.entries()){if(o.some(l=>l.id===i))continue;let s=a.getAttribute("content-desc");(gs(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:Ro(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await re().startAsyncSpan("EMULATOR_READ_STATE",()=>t.getBrowserState({abortSignal:this.aborter.controller?.signal,serializationOpts:{noId:!0}}),{name:"Get webview content",signal:this.aborter.controller?.signal})).serializedTree}async getDomState(e){return await re().startAsyncSection("Get emulator state XML",async()=>{let n;if(!e?.skipFetchingFullWebviewContent)try{n=await this.getActiveWebviewContent()}catch(c){this.logger.error({err:c},"Could not get webview info to get the nested DOM state")}this.throwIfAborted();let i=e?.filterOffscreenElements??!0?await this.getViewportBounds():void 0,a=await this.getPageSource();return{graph:await PR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:i}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await re().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}async getViewportBounds(){let e=await this.driver.getWindowRect();return{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height}}async refreshWebviews(){try{await this.refreshWebviewsHelper()}catch(e){this.logger.warn({err:e},"Error refreshing webviews, continuing...")}}async refreshWebviewsHelper(){await this.getPageSource(),this.throwIfAborted();let e=await this.getCurrentPackage(),t=await this.getDetailedContexts();if(!t){this.logger.warn("No context details, not proceeding with refreshing webviews");return}let n=Date.now(),o=new Set;for(let i of t){if(this.throwIfAborted(),i.webview==="NATIVE_APP")continue;let a=i.info["Android-Package"];if(e&&a!==e&&this.logger.warn({packageName:a,currentPkgName:e},"Ignoring webview not in the active package"),o.add(i.webview),!this.webviews.has(i.webview)||!this.webviews.get(i.webview)?.active){let s={contextId:i.webview,packageName:a,active:!1,lastSeen:n,socketName:i.proc.startsWith("@")?i.proc.substring(1):i.proc};this.logger.info({contextId:s.contextId,packageName:s.packageName,socketName:s.socketName},"New webview detected"),this.webviews.set(i.webview,s);let c;if(a==="com.android.chrome"?(this.logger.info({webviewInfo:s},`Connecting Playwright to Android Chrome: ${i.webview}`),c=await this.connectPlaywrightToChrome(s),this.logger.info(`Connected Playwright to Android Chrome: ${i.webview}`)):(this.logger.info({webviewInfo:s},`Connecting Playwright to webview: ${i.webview}`),c=await this.connectPlaywrightToWebview(a,s.socketName),c&&this.logger.info(`Connected Playwright to webview ${i.webview}`)),!c)continue;s.browserController=c,s.active=!0}}for(let[i,a]of this.webviews.entries())!o.has(i)&&a.active&&(this.logger.info(`Disconnecting dead webview ${i}`),this.disconnectPlaywrightFromWebview(a),a.active=!1)}async getActiveWebview(){await re().startAsyncSection("Refresh webviews",async()=>{await this.refreshWebviews()});let e=await this.driver.execute("mobile: getCurrentPackage");e!==void 0&&typeof e!="string"&&this.logger.warn({currentPkg:e},"Unexpected getCurrentPackage result");let t=[];for(let n of this.webviews.values())n.packageName===e&&n.active&&t.push(n);if(t.length!==0){if(t.length>1)throw new Error("Multiple active webviews in a single package is currently not supported");return t[0]}}async executeRawADBCommand(e){let t=this.driver.capabilities,n=t.deviceUDID||t.udid||t["appium:udid"]||t["appium:deviceUDID"],o=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",i=n?`-s ${n}`:"",a=`${o} ${i} ${e}`;this.logger.info(`Executing ADB command: ${a}`);let s=GR(a,{encoding:"utf8"});return this.logger.info(`ADB command result: ${s}`),s}async cleanupWebviews(){for(let[e,t]of this.webviews.entries())this.logger.info(`Disconnecting webview ${e}`),this.disconnectPlaywrightFromWebview(t),t.active=!1}async getDetailedContexts(){return await re().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=zR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4241
4241
|
${o}
|
|
4242
4242
|
Raw: ${JSON.stringify(t)}`)}return n.filter(o=>{if(!o.webviewName)return!0;if(!o.info||!o.pages)return!1;let i=o.pages.filter(a=>{if(!a.title)return!1;let s=a.url;return!(!s||s===""||s.startsWith("about:blank")||s.startsWith("chrome-error:"))});return i?!!i:(this.logger.debug({context:o},"Webview has no qualified pages, skipping"),!1)})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await re().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await ds.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{autoExpandIframes:!0,visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new cu({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new _l})})}async connectPlaywrightToWebview(e,t){return re().startAsyncSection("Connect headless browser client to webview",async()=>{for(let o=0;o<2;o++)try{return await this.connectPlaywrightToWebviewHelper(e,t)}catch(i){this.logger.warn({err:i},"Failed to connect Playwright to webview, retrying...")}},{signal:this.aborter.controller?.signal,timeoutMs:8e3,timeoutMsg:"Timed out connecting Playwright to the webview"})}extractSocketNameFromWebview(e,t){if("_socketName"in e&&typeof e._socketName=="string")return e._socketName;if("_data"in e&&e._data?.socketName)return e._data.socketName;t.warn({pkg:e.pkg()},"Could not extract socket name from webview")}async connectPlaywrightToWebviewHelper(e,t){let n=this.device.webViews(),o=n.find(l=>!(l.pkg()!==e||this.extractSocketNameFromWebview(l,this.logger)!==t));if(!o){let l=`Could not find webview for ${e} with socket name ${t}`;throw this.logger.warn({webviews:n.map(u=>({pkg:u.pkg,name:this.extractSocketNameFromWebview(u,this.logger)}))},l),new Error(l)}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){let l=`Webview ${e} with socket ${t} is not a valid webview`;this.logger.warn({pageUrl:a},l);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await re().startAsyncSpan("EMULATOR_READ_STATE",async()=>this.connectPlaywrightToChromeHelper(e),{name:"Connect headless browser client to Chrome",signal:this.aborter.controller?.signal})}async connectPlaywrightToChromeHelper(e){let{contextId:t,socketName:n}=e;try{this.logger.info({contextId:t,socketName:n},"Connecting to Chrome webview");let o;e.forwardedPort?(o=`http://127.0.0.1:${e.forwardedPort}`,this.logger.info({contextId:t,endpoint:o,socketName:n},"Using existing forwarded port")):(o=`http://127.0.0.1:${await this.forwardDevToolsSocket(e.socketName)}`,this.logger.info({contextId:t,endpoint:o,socketName:n},`Forwarding DevTools socket for ${e.socketName}`)),this.logger.info({endpoint:o,socketName:n},"Connecting to CDP endpoint");let i=await e1.connectOverCDP({endpointURL:o,timeout:8e3}),a=i.contexts()[0];if(!a){this.logger.warn("No browser context available after CDP connection"),await i.close();return}return this.createBrowserController({context:a})}catch(o){this.logger.warn({err:o},`Error connecting Playwright to webview ${e.contextId}, continuing...`);return}}async disconnectPlaywrightFromWebview(e){try{e.browserController&&(this.logger.info(`Disconnecting Playwright from webview: ${e.contextId}`),await e.browserController.browser.cleanup(),e.browserController=void 0),e.forwardedPort&&await this.removeDevToolsForwarding(e.forwardedPort)}catch(t){this.logger.error({err:t},`Error disconnecting Playwright from webview ${e.contextId}:`)}}async forwardDevToolsSocket(e){this.logger.info("Setting up port forwarding for DevTools");let t=1e4+Math.floor(Math.random()*1e4),n=this.driver.capabilities,o=n.deviceUDID||n.udid||n["appium:udid"]||n["appium:deviceUDID"];this.logger.info({deviceId:o},`Device ID from capabilities: ${o||"not found"}`);let i=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb",a=o?`-s ${o}`:"",s=`${i} ${a} forward tcp:${t} ${`localabstract:${e}`||"localabstract:chrome_devtools_remote"}`;this.logger.info(`Executing command: ${s}`);let c=GR(s,{encoding:"utf8"});return this.logger.info(`ADB command result: ${c}`),this.logger.info(`Successfully forwarded DevTools socket to port ${t}`),t}async removeDevToolsForwarding(e){await this.executeRawADBCommand(`forward --remove tcp:${e}`),this.logger.info("Successfully removed port forwarding")}throwIfAborted(){this.aborter.controller?.signal.throwIfAborted()}};var WR=5,jR=.8,t1=1,fu=class extends Oi{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??jR,o=await this.tryUseCachedScrollPosition(e,t);return o||this.searchForElement(e,t,n)}async resolveContainer(e,t){let n=await this.driver.getWindowRect();if(e.type==="CUSTOM_COORDINATES")return{bounds:{left:0,top:0,width:n.width,height:n.height}};if(e.type!=="CUSTOM")return{bounds:await this.getHardcodedScrollableElementBounds(e,n)};let o=re(),i=e.target.description;if(t){let c=this.getBoundsFromNativeCache(t);return this.logger.info({bounds:c},"Got container bounds from native cache"),{bounds:c,cache:t}}let{resolvedTarget:a}=await this.findElement({description:i,tracer:o});if(a.type!=="NATIVE")throw new Error(`ActionFailureError: Custom scroll container "${i}" resolved to a webview element. Custom containers must be native elements.`);let s=this.getBoundsFromNativeCache(a);return this.logger.info({bounds:s},"Got container bounds from AI"),{bounds:s,cache:a}}async tryUseCachedScrollPosition(e,t){let n=e.cache?.target;return n?n.type==="WEBVIEW"?this.tryUseWebviewCache(e,t):n.scrollDetails?this.tryUseNativeScrollCache(e,t,n):null:null}async tryUseWebviewCache(e,t){let n=re();try{let{thoughts:o}=await this.wrapTargetingAction({command:e,tracer:n,description:t,action:async i=>{if(i.type==="NATIVE")throw new Error("Expected WEBVIEW target but got NATIVE");await this.scrollWebviewTargetIntoView(i)}});return{success:!0,message:o}}catch(o){return this.logger.warn({err:o},"Failed to use webview cache, falling back to search"),null}}async tryUseNativeScrollCache(e,t,n){let o=n.scrollDetails,i=re(),a=e.scrollStepPercent??jR,s=o.scrollableElement.type==="CUSTOM"?o.scrollableElement.cache:void 0;await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:o.direction,scrollStepPercent:a});try{let l=await this.tryFindElement({cmd:e,description:t,tracer:i,scrollDetails:o,useAIIfCacheFails:!1});if(l)return l;this.logger.info("Element not found at cached position, undoing scroll")}catch(l){this.logger.warn({err:l},"Error finding element at cached position, will undo scroll")}let c=o.direction==="down"?"up":"down";return this.logger.info({pixelDelta:o.pixelDelta,originalDirection:o.direction,undoDirection:c,scrollableElementType:o.scrollableElement.type},"Undoing scroll"),await this.scrollByPixelDelta({pixelDelta:o.pixelDelta,scrollableElement:o.scrollableElement,containerCache:s,direction:c,scrollStepPercent:a}),null}async tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:o,useAIIfCacheFails:i=!0}){let a,s,c=e.cache?.target;if(c&&c.resolvedDescription===t&&!e.disableCache){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"});let u=await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0});try{let{resolvedTarget:d}=await mu({target:c,domState:u,stateManager:this.stateManager,logger:this.logger});a=d,s="Successfully resolved scroll to target with cache.",this.logger.info("Successfully resolved scroll to target from cache")}catch(d){this.logger.warn({err:d},"Failed to resolve target from cache")}}if(!a&&!i)return null;if(!a)try{let u=await this.findElement({description:t,tracer:n});a=u.resolvedTarget,s=u.thoughts}catch(u){if(this.logger.warn({err:u},"Failed to find scroll-to target with AI"),u instanceof Sn)return null;throw u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),Pi({command:e,updatedCache:pu(a),updatedWithAI:!0}),{success:!0,message:s}):(Pi({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0}),{success:!0,message:s})}async searchForElement(e,t,n){let o=re(),i=await this.resolveContainer(e.scrollableElement);return this.scrollAndSearch(e,t,o,n,i)}async scrollAndSearch(e,t,n,o,i){let a=0,s=i.bounds,c=s.height*o,l=!0;for(let u=0;u<WR;u++){this.throwIfAborted();let d=this.buildScrollDetails(e,a,i.cache),m=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(m)return m;if(!l)throw new Error(`ActionFailureError: Could not find element "${t}" after scrolling to the end`);this.logger.debug({attempt:u,cumulativePixelDelta:a},"Element not found, scrolling further");let g=r1(e.scrollableElement);l=await this.scrollByPage({direction:e.direction,containerBounds:s,scrollStepPercent:o,rawCoordinates:g}),a+=e.direction==="down"?c:-c}throw new Error(`ActionFailureError: Could not find element "${t}" after ${WR} scroll attempts`)}buildScrollDetails(e,t,n){return e.scrollableElement.type==="CUSTOM"?{pixelDelta:t,scrollableElement:{type:"CUSTOM",target:e.scrollableElement.target,cache:n},direction:e.direction}:e.scrollableElement.type==="CUSTOM_COORDINATES"?{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}:{pixelDelta:t,scrollableElement:e.scrollableElement,direction:e.direction}}async scrollWebviewTargetIntoView(e){let{controller:t,resolution:n}=e;await t.browser.hover({locator:n.locator})}async scrollByPage({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o}){return re().startAsyncSpan("EMULATOR_INTERACTION",async a=>(a.attributes.containerBounds=t,a.attributes.direction=e,this.executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,rawCoordinates:o})),{name:`Scroll ${e} by one page`})}async scrollByPixelDelta({pixelDelta:e,scrollableElement:t,containerCache:n,direction:o,scrollStepPercent:i}){if(e===0)return;let a=re(),s,c,l;if(t.type==="CUSTOM_COORDINATES")s=t.startX,c=t.startY,l=t.deltaPixels;else{let m=(await this.resolveContainer(t,n)).bounds,g=m.height*i,p=this.calculateSwipeCoordinates({containerBounds:m,direction:o,desiredDelta:g});s=p.startX,c=p.startY,l=p.actualDelta}let u=Math.ceil(Math.abs(e)/l);this.logger.debug({pixelDelta:e,direction:o,scrollableElementType:t.type,startX:s,startY:c,maxScrollPerStep:l,numScrolls:u},"scrollByPixelDelta calculated parameters"),await a.startAsyncSpan("EMULATOR_INTERACTION",async d=>{d.attributes.pixelDelta=e,d.attributes.numScrolls=u,d.attributes.maxScrollPerStep=l,d.attributes.startX=s,d.attributes.startY=c;let m=0;for(let g=0;g<u;g++){this.throwIfAborted();let p=Math.abs(e)-m,h=Math.min(l,p);await this.performRawSwipe({startX:s,startY:c,deltaPixels:h,direction:this.invertDirection(o)}),m+=h}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=t1,rawCoordinates:i}){let a=await this.stateManager.getRawScreenshotBase64(),s,c,l;if(i)s=i.startX,c=i.startY,l=i.deltaPixels;else{let g=t.height*n,p=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:g});s=p.startX,c=p.startY,l=p.actualDelta}await this.performRawSwipe({startX:s,startY:c,deltaPixels:l,direction:this.invertDirection(e)});let u=await this.stateManager.getRawScreenshotBase64(),d=kg(a,u),m=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:m,direction:e,actualDelta:l,rawCoordinates:i},"Scroll gesture visual diff result"),m}};function r1(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as n1}from"crypto";import fs from"fs";import{tmpdir as o1}from"os";import Li from"path";var Su=class extends at{async doInstallApk(e){return await this.installApkFromUri(e.uri),{success:!0,message:"Installed APK."}}async installApkFromUri(e){let t=await this.resolveUriToLocalApk(e);try{await this.stateManager.executeRawADBCommand(`install ${Li.resolve(t.localPath)}`),this.logger.info({uri:e,localPath:t.localPath},"Installed APK on device")}finally{t.cleanup()}}async resolveUriToLocalApk(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.href.slice(7),o;if(fs.existsSync(n))o=n;else if(fs.existsSync(Li.join("/",n)))o=Li.join("/",n);else throw new Error(`APK not found at path: ${n}`);return this.assertFileExists(o),{localPath:o,cleanup:()=>{}}}if(t.protocol==="http:"||t.protocol==="https:"){let n=await this.fetchWithTimeout(t);if(!n.ok)throw new Error(`Failed to download APK from ${e} (status ${n.status})`);let o=await n.arrayBuffer(),i=Buffer.from(o),a=await this.writeBufferToTempFile(i,t.pathname);return{localPath:a,cleanup:()=>{try{fs.unlinkSync(a)}catch(s){this.logger.warn({err:s,path:a},"Failed to remove temporary APK file")}}}}throw new Error(`Unsupported URI scheme for APK installation: ${t.protocol}`)}catch(t){if(t instanceof TypeError){let n=Li.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{fs.accessSync(e)}catch{throw new Error(`APK not found at path: ${e}`)}}async fetchWithTimeout(e){let t=AbortSignal.timeout(9e4);return await fetch(e,{signal:t})}async writeBufferToTempFile(e,t){let n=Li.extname(t)||".apk",o=Li.join(o1(),`momentic-apk-${n1()}${n}`);return fs.writeFileSync(o,e),o}};import{existsSync as i1,readFileSync as a1}from"fs";import s1 from"zod";var l1=s1.string().url();async function $R(r){if(l1.safeParse(r).success){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),n;try{n=await fetch(r,{signal:e.signal})}catch(i){throw new Error(`Fetch failed or timed out for URL: ${r}`,{cause:i})}finally{clearTimeout(t)}if(!n.ok)throw new Error(`Failed to fetch file from URL: ${r}, status: ${n.status}`);let o=await n.arrayBuffer();return Buffer.from(o).toString("base64")}if(!i1(r))throw new Error(`File does not exist at path: ${r}`);return a1(r).toString("base64")}import{cloneDeep as qR}from"lodash-es";var c1=5e3,u1={getTextContent:async r=>await r.textContent()??"",getAttribute:async(r,e)=>await r.getAttribute(e,{timeout:3e3})??"",getTagName:async r=>await r.evaluate(e=>e.tagName),isEditable:async r=>await r.isEditable({timeout:zt*1e3}),isEnabled:async r=>await r.isEnabled({timeout:zt*1e3}),isFocused:async r=>await r.evaluate(e=>e===document.activeElement),getStyleProperty:async(r,e)=>await r.evaluate((t,n)=>window.getComputedStyle(t).getPropertyValue(n),e)},KR=r=>{let e=[],t=r.getAttribute("text")??"",n=r.getAttribute("hint")??"",o=r.getAttribute("showing-hint")==="true";t.trim()&&!o&&t.trim()!==n.trim()&&e.push(t.trim());for(let i of Array.from(r.childNodes??[]))if(i.nodeType===3){let a=i.nodeValue??"";a.trim()&&e.push(a.trim())}else if(i.nodeType===1){let a=KR(i);a.trim()&&e.push(a.trim())}return e.join(" ").trim()},d1={getTextContent:async r=>KR(r),getAttribute:async(r,e)=>r.getAttribute(e)??"",getTagName:async r=>r.tagName,isEditable:async r=>{throw new Error("Cannot perform editable check on native element")},isEnabled:async r=>r.getAttribute("enabled")==="true",isFocused:async r=>r.getAttribute("focused")==="true",getStyleProperty:async(r,e)=>{throw new Error("Cannot perform computed style checks on native element")}},yu=class extends at{async executeElementCheck(e){let t=Date.now(),n=(e.timeout??zt)*1e3,o=n+1e4,i,a=0,s=500,c=qR(e.cache);if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Element Check step");for(;a-t<n;){if(Date.now()-t>o){this.logger.warn("Exceeded max system timeout for element check, exiting...");break}if(this.throwIfAborted(),i=await this.executeElementCheckHelper(e),a=Date.now(),!i.success)e.cache=c,c=qR(c),await q(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),c1);else return i}let l=await this.executeElementCheckHelper(e,{cacheIsInvalidAfterResolution:!0});return l.success||c&&(e.cache=this.restoreCachePreserveMemory(c,e.cache)),l}restoreCachePreserveMemory(e,t){return t?.target?.memory&&e?.target?.memory&&e.target.memory!==t.target.memory?{...e,target:{...e.target,memory:t.target.memory},updatedAt:t.updatedAt}:e}async executeElementCheckHelper(e,t){let n=re();if(e.target.type!=="description")throw new Error("UserConfigurationError: x/y targets are not supported for the Element Check step");let o=Nc(e.assertion);try{return(await this.wrapTargetingAction({...t??{},command:e,tracer:n,action:async a=>"type"in a&&a.type==="NATIVE"?await this.executeNativeElementCheck(e,a):await this.executeWebviewElementCheck(e,a),description:e.target.description,skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).result}catch(i){return o&&(i instanceof Sn||i instanceof fn)?{success:!0}:{success:!1,message:`Failed to evaluate element content assertion: ${i instanceof Error?i.message:`${i}`}`}}}async executeNativeElementCheck(e,t){let n=re(),{assertion:o}=e,i=t.resolvedNode;return await n.startAsyncSection("Execute native element check",async(a,s)=>await this.executeElementAssertion({assertion:o,element:i,elementCallbacks:d1,trace:s}))}async executeWebviewElementCheck(e,t){let n=re(),o=t.resolution.locator,i=e.assertion;return await n.startAsyncSection("Execute webview element check",async(a,s)=>(await t.controller.browser.highlight(o),await this.executeElementAssertion({assertion:i,element:o,elementCallbacks:u1,trace:s})))}async executeElementAssertion({assertion:e,element:t,elementCallbacks:n,trace:o}){switch(e.type){case"ELEMENT_CONTENT":{let i=await n.getTextContent(t)??"";return o.attributes.elementTextContent=gt(i,500,!0),Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})?{success:!0}:{success:!1,message:`The content ${dr(e)} '${e.value}': ${i}`}}case"ELEMENT_ATTRIBUTE":{"evaluate"in t&&(o.attributes.elementOuterHtml=gt(await t.evaluate(a=>a.cloneNode(!1).outerHTML),500,!0));let i;try{i=await n.getAttribute(t,e.attr)}catch(a){return{success:!1,message:`The element does not have an attribute named ${e.attr}: ${a}`}}if(!Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=dr(e);return{success:!1,message:`The attribute ${e.attr} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}case"ELEMENT_EXISTENCE":{let i=!1;switch(e.condition){case"EDITABLE":i=await n.isEditable(t);break;case"VISIBLE":case"EXISTS":i=!0;break;case"ENABLED":{i=await n.isEnabled(t);break}case"FOCUSED":i=await n.isFocused(t);break;default:throw e.condition,new Error("Unrecognized element condition type")}return i=e.negated?!i:i,i?{success:!0}:{success:!1,message:`The element ${dr(e)}`}}case"ELEMENT_NAME":{let i=await n.getTagName(t);return Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!0})?{success:!0}:{success:!1,message:`The element tag name ${dr(e)} '${e.value}': ${i}`}}case"ELEMENT_STYLE":{let i=await n.getStyleProperty(t,e.property);if(!Hr(i,e.value,e.operation,{negated:!!e.negated,ignoreCase:!1})){let a=dr(e);return{success:!1,message:`The style property ${e.property} ${a}${e.operation==="EXISTS"?"":` '${e.value}': ${i}`}`}}return{success:!0}}default:throw new Error("Unrecognized element assertion type")}}};var m1=5e3,bu=class extends at{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??zt)*1e3,i=o+1e4,a=0,s=500;for(;a-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}this.throwIfAborted();let c=await this.executeScreenCheckHelper(e);if(a=Date.now(),!c.success)await q(s,this.abortSignal),s=Math.min(Math.floor(s*1.5),m1);else return c}return await this.executeScreenCheckHelper(e)}async executeScreenCheckHelper(e){return await re().startAsyncSection("Execute screen check",async(n,o)=>{let[i,a]=await Promise.all([this.executeNativeScreenCheckHelper({span:o,command:e}),this.executeWebviewScreenCheckHelper(e)]);return a?e.assertion.negated?i.success&&a.success?i:i.success?a:i:i.success?i:a:i})}async executeNativeScreenCheckHelper({span:e,command:t}){let{assertion:n}=t;switch(n.type){case"CONTENT":try{let o=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!o)throw new Error("Failed to get screen HTML");let i=o.includes(n.value)===!n.negated;return o.length>1e4&&(o=o.slice(0,1e4)+"...TRUNCATED"),i?{success:!0}:(e.attributes.screenContent=o,{success:!1,message:`The screen ${Dp(n)}.`})}catch(o){return{success:!1,message:`Failed to evaluate screen content assertion: ${o instanceof Error?o.message:`${o}`}`}}default:return n.type,{success:!1,message:`Unsupported screen check assertion type: ${n.type}`}}}async executeWebviewScreenCheckHelper(e){let t=await this.stateManager.getActiveWebview();if(!t||!t.browserController)return;let n=t.browserController.browser;return await lu({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};var Eu=class extends at{async doUninstallApk(e){return await this.uninstallApkPackage(e.packageName),{success:!0,message:"Uninstalled APK."}}async uninstallApkPackage(e){let t=e.replace(/^package:/,""),n=await this.stateManager.executeRawADBCommand(`shell pm list packages | grep -E "^package:${t}$" || true`);if(n.length===0)throw new Error(`Package ${t} not found`);if(n.split(`
|
|
4243
4243
|
`).filter(i=>!!i).length>1)throw new Error(`Multiple packages found for ${t}`);try{await this.stateManager.executeRawADBCommand(`uninstall ${t}`)}catch(i){throw new Error(`Failed to uninstall package ${t}: ${i}`)}}};var Ni=class r extends at{options;appsWithGrantedPermissions=new Set;adbPort;constructor(e){super(e),this.options=e.options??{},this.adbPort=e.adbPort}static async init({driver:e,generator:t,logger:n,fixtures:o,orgId:i,options:a,abortController:s,adbPort:c,limbarClient:l,playwrightDevice:u}){let d={controller:s},m=await hu.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:l,options:a?.emulator??{},aborter:d,adbPort:c,playwrightDevice:u}),g=new r({driver:e,generator:t,stateManager:m,logger:n,fixtures:o,options:a,aborter:d,orgId:i,adbPort:c});return await g.initializeSettings(),g}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${g1.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await Oc({obj:e.command,context:this.fixtures.testContext,bannedKeys:t,orgId:this.orgId,logger:this.logger,signal:this.abortSignal,localTools:this.fixtures.localCodeEvalTools})}catch(o){throw this.throwIfAborted(),new Error(`ActionFailureError: Failed to substitute template strings in command: ${o.message}`,{cause:o})}try{return await this.executeCommandHelper(e)}catch(o){throw o.name!=="AbortError"&&this.logger.error({err:o},"Error thrown in action controller"),o}finally{Lc(e.command,n)}}async executeCommandHelper({command:e}){let t=re();switch(e.type){case"TAP":return new Ii(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new gu(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Bc(o),a=Date.now(),s=0,c,l=!1,u;for(;s<15&&!l;){this.throwIfAborted(),l||c&&c-a>=o&&(l=!0),s!==0&&await q(i,this.abortSignal),c=Date.now();try{let d="",m="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,m=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let g=await t.startAsyncSpan("AI_ASSERTION_CALL",async p=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:m},{logger:this.logger,loggerTags:fe(this.logger)});return p.result={thoughts:h.thoughts,result:h.result},h});if(g.result)return{success:g.result,message:g.thoughts};{let p=`AssertionFailureError: ${g.thoughts}`;u=new Error(p)}}catch(d){this.throwIfAborted(),this.logger.info({err:d},`AI check assert attempt ${s} failed, retrying...`),u=d instanceof Error?d:new Error(`${d}`)}finally{s++}}return{success:!1,message:u?.message}}case"SWIPE":return new Oi(this.constructPerformerParams()).executeSwipe(e);case"SCREEN_CHECK":return new bu(this.constructPerformerParams()).executeScreenCheck(e);case"ELEMENT_CHECK":return await new yu(this.constructPerformerParams()).executeElementCheck(e);case"SCROLL_TO":return new fu(this.constructPerformerParams()).executeScrollTo(e);case"JAVASCRIPT":{let n=await zr({orgId:this.orgId,code:e.code,fragment:!1,context:this.fixtures.testContext,timeoutMs:e.timeout?e.timeout*1e3:void 0,logger:this.logger,localTools:this.fixtures.localCodeEvalTools,signal:this.abortSignal});try{JSON.stringify(n)}catch(o){throw new Error(`UserConfigurationError: Return value is not serializable: ${o instanceof Error?o.message:`${o}`}`)}return{success:!0,output:n}}case"REQUEST":{let n;try{n=new URL(e.url).hostname}catch(l){throw new Error(`UserConfigurationError: Invalid URL: ${l}`)}let o=new h1,i=p1(fetch,o),a=Date.now(),s=await su({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=ul(o,n);return{output:{...s,cookies:c},success:!0,message:`Successfully executed request in ${Date.now()-a}ms`}}case"OPEN_NOTIFICATION_DRAWER":return await new zn(this.constructPerformerParams()).doPress({keycode:83}),{success:!0};case"OPEN_APP":{let n=e.activityName;if(!n){let i=["resolve-activity","--brief","-a","android.intent.action.MAIN","-c","android.intent.category.LAUNCHER",e.packageName],a=await k(this.driver.execute("mobile: shell",{command:"pm",args:i}),{signal:this.abortSignal,milliseconds:1e4});if(typeof a!="string")throw new Error(`Could not find main activity name for package ${e.packageName}. Unexpected output: ${a}`);if(a.includes("No activity found"))throw new Error(`No activity found for package ${e.packageName}.`);if(n=a.trim().split(`
|
|
@@ -4274,22 +4274,22 @@ Momentic users value the following:
|
|
|
4274
4274
|
b) There is a loading state that blocks you from proceeding with generation, and you need to wait until the state changes. In this case, you can generate an AI_CHECK step for the anticipated "done" state (e.g. "There is no loading spinner visible"). Unless explicitly specified by the user, you can generate and retry an assertion up to 3 times with a timeout up to 30 seconds each.
|
|
4275
4275
|
If the max. allowed retries is exceeded, fail the generation cycle by calling "finish".
|
|
4276
4276
|
</rules>
|
|
4277
|
-
`;import{tool as R1}from"ai";import{randomUUID as x1}from"crypto";import M1 from"zod";import{tool as w1}from"ai";import C1 from"zod";var ix=r=>{let e=w1({description:"Get the current state of the emulator (XML + screenshot)",inputSchema:C1.object({}),toModelOutput:t=>t,execute:async()=>{let{controller:t,logger:n,contextManager:o}=r;return o.recordGenericToolCall(Ug),n.info("AI action tool called (get_emulator_state)"),Fg(t)}});return{name:Ug,tool:e}};async function Fg(r){let e=await r.getA11yTree(),t=await r.getScreenshotBase64();return{type:"content",value:[{type:"text",text:"<emulatorXml>"},{type:"text",text:e},{type:"text",text:"</emulatorXml>"},{type:"text",text:"<screenshot>"},{type:"media",data:t,mediaType:"image/png"},{type:"text",text:"</screenshot>"}]}}var ax=r=>({name:"create_execute_step",tool:R1({description:"Create and immediately execute a new Momentic step in the Android emulator, returning the result from the step and the state of the emulator after the step finished executing.",inputSchema:M1.object({step:Zd}),toModelOutput:t=>t,execute:async({step:t})=>{let{contextManager:n,logger:o,controller:i}=r;o.info({step:t},"AI action tool called (create_execute_step)");let a=Ry(t),s={id:x1(),type:"MOBILE_PRESET_STEP",command:a},c=await n.createAndExecuteStep(s);c.status==="SUCCESS"&&await i.waitForScreenshotStability({reason:"Waiting for stability after executing AI-generated sub-step"});let l={...c,trace:void 0,beforeSnapshot:void 0,afterSnapshot:void 0},u=await Fg(i);return{type:"content",value:[{type:"text",text:"<result>"},{type:"text",text:JSON.stringify(l,null,2)},{type:"text",text:"</result>"},{type:"text",text:"<stateAfter>"},...u.value,{type:"text",text:"</stateAfter>"}]}}})});import{tool as _1}from"ai";import Bg from"zod";var sx=r=>{let e=_1({description:"Signal that the AI action has reached a terminal state (either success or failure).",inputSchema:Bg.object({message:Bg.string(),success:Bg.boolean()}),toModelOutput:t=>t,execute:async({message:t,success:n})=>{let{contextManager:o,logger:i}=r;return i.info({message:t,success:n},"AI action tool called (finish)"),o.finalState={message:t,status:n?"SUCCESS":"FAILED"},{type:"content",value:[{type:"text",text:"Done"}]}}});return{name:vu,tool:e}};var lx=[ax,ix,sx];function cx(r){let{logger:e,controller:t,contextManager:n,aiActionSessionId:o}=r,i={};for(let c of lx){let l=c({contextManager:n,logger:e,controller:t});i[l.name]=l.tool}let a=t.generator.getVercelAnthropicModelFactory({loggerTags:fe(e),sessionId:o}),s=c=>{let{messages:l}=c,u=!1;for(let d=l.length-1;d>=0;d--){let m=l[d];for(let g of m.content)if(!(typeof g!="object"||!("type"in g))&&!(g.type!=="tool-result"||g.output.type!=="content")&&!(g.output.value.length<3))for(let p=0;p<g.output.value.length;p++){let h=g.output.value[p];if(h.type==="text"&&h.text.includes("<emulatorXml>"))if(u){let f=g.output.value[p+1];f.type==="text"?f.text="TRUNCATED DUE TO CONVERSATION LENGTH":e.warn({msg:f},"Got unexpected part when truncating emulator state message")}else{u=!0;continue}}}return c};return{model:a("claude-haiku-4-5-20251001"),tools:i,prepareStep:s,stopWhen:[I1(15),P1(vu)],system:ox(!1)}}async function ux(r){let e=Date.now(),{controller:t,logger:n}=r.fixtures;try{return await N1(r)}catch(o){let i=t.isAborted()||o instanceof DOMException&&o.name==="AbortError";return i||n.error({err:o},"Failed to execute mobile AI action"),{...r.aiActionParams.step,steps:[],type:"MOBILE_AI_ACTION_STEP",startTime:e,endTime:Date.now(),status:i?"CANCELLED":"FAILED",message:i?"Step cancelled.":`${o}`}}}async function N1(r){let{step:e,stepTracer:t,executeMobileStepList:n}=r.aiActionParams,{controller:o,logger:i}=r.fixtures,{step:a}=r.callbacks,s=await t.startSubSteps(),c=L1(),l=i.child({stepId:e.id,aiActionSessionId:c}),u=Date.now(),d=async(f,E)=>{let b=await n({...r,listParams:{steps:[f],tracer:s,containerName:`AI action sub-step ${E}`}});if(b.results.length!==1)throw new Error("InternalWebAgentError: Expected exactly one result from executeMobileStepList");return b.results[0]},m={stepId:e.id,parentStepIdChain:t.getParentStepIdChain()},g=new Tu({controller:o,callbacks:{onAiActionEvent:a?.onAiActionEvent,executeStep:d},logger:l,rootStep:m}),p=cx({controller:o,logger:l,contextManager:g,aiActionSessionId:c}),h=O1({...p,messages:[{role:"user",content:e.text}],abortSignal:o.abortSignal});for await(let f of h.fullStream)switch(o.throwIfAborted(),f.type){case"text-delta":a?.onAiActionEvent?.({type:"LLM_TEXT_OUTPUT",text:f.text,rootStep:m})}if(await h.response,o.throwIfAborted(),!g.finalState)throw new Error("InternalWebAgentError: The AI agent never reached a final state. This could be because the maximum number of steps was reached.");return{...e,status:g.finalState.status,startTime:u,endTime:Date.now(),message:g.finalState.message,steps:g.results}}var D1=60*60*1e3;async function Au(r){let{fixtures:e,inputs:t,listParams:n,work:o}=r,{containerName:i,steps:a,tracer:s}=n,{logger:c,controller:l,usageTracker:u}=e,d=s.getParentStepIdChain(),m=[],g,p="SUCCESS",{fromStep:h,toStep:f}=t;for(let E=0;E<a.length;E++){let b=a[E];if(b.skipped)continue;if(o.fastForwardingToStep&&h){let w=JSON.stringify(d);if(b.id===h.fromStepId&&w===JSON.stringify(h.parentStepIdChain))o.fastForwardingToStep=!1;else if(!Rw({currentStep:b,currentParentChain:d,desiredStepId:h.fromStepId,desiredStepParentChain:h.parentStepIdChain}))continue}let x=0,v=1,A=Date.now();b.retries&&b.retries>0&&(v+=b.retries);let _=[];for(;x<v&&Date.now()-A<D1;){x++;let w=`Executing step index ${E} in ${i} - ${Bp(b)}`;x!==1&&(w+=` (attempt ${x})`),c.info(w);let N=Date.now(),G=await s.startStep({logger:c,step:b,attempt:x,parentStepIdChain:d});u.trackStepExecution(b);let W=await k1({step:b,stepTracer:G,params:r}),{trace:ye}=await G.finish({parentStepIdChain:d,result:W});if(W.trace=ye,w=`Finished step index ${E} in ${i} - ${Bp(b)}`,x!==1&&(w+=` (attempt ${x})`),c.info({step:{id:b.id},trace:W.trace,status:W.status},w),W.status!=="SUCCESS"&&x<v){_.push(W),Date.now()-N<1e3&&await q(1e3-(Date.now()-N));continue}if(_.length>0&&(W.previousAttempts=_),m.push(W),W.status!=="SUCCESS")return p=W.status,g=W,{results:m,status:p,terminalResult:g};if(b.envKey&&l.context.setVariable(b.envKey,W.data),f){let Se=JSON.stringify(d);if(b.id===f.toStepId&&Se===JSON.stringify(f.parentStepIdChain))return o.shouldStopExecuting=!0,{results:m,status:p,terminalResult:g}}if(o.shouldStopExecuting)return{results:m,status:p,terminalResult:g};break}}return{results:m,status:p,terminalResult:g}}async function k1({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o,callbacks:i,work:a}=t,s;switch(r.type){case"MOBILE_PRESET_STEP":{s=await rx({fixtures:n,inputs:o,step:r,stepTracer:e,callbacks:i,work:a});break}case"RESOLVED_MOBILE_MODULE":{s=await ex({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Au}});break}case"MOBILE_AI_ACTION_STEP":{s=await ux({...t,aiActionParams:{step:r,stepTracer:e,executeMobileStepList:Au}});break}}return s}async function wu(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:s}=r.fixtures,c=a.child({testId:r.inputs.testMetadata.id,testName:r.inputs.testName});await i.resolveEntries({logger:c,testId:o.id,stepLists:{steps:n}});let l=F1(n);c.info({testMetadata:Er.parse(o)},"Starting mobile test");let u=await e.startMainStepList(),d=EE(c),m=ZR(s,c);c.info({cpu:d?.cpuMetadata,platform:d?.platform},`Starting execution of ${t}`);let{status:g,results:p}=await Au({...r,listParams:{containerName:t,tracer:u,steps:l}});if(clearInterval(d?.interval),clearInterval(m),g==="SUCCESS"){let h=U1(l,n);if(h&&Object.keys(h).length>0){c.info({diffs:JSON.stringify(h)},"Saving mobile step cache entries post-success");let{cachesToSave:f}=await Ln({steps:l,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:c,testId:o.id,entries:f})}else c.info("No cache entries to update");return{status:"PASSED",results:p}}return g==="CANCELLED"?{status:"CANCELLED",results:p}:{status:"FAILED",results:p}}var zg=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new Co,an.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...eE.parse(e),trace:om.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Di({parentStep:this.step,socket:this.socket,parentTracer:this})}},Di=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new zg({step:e.step,parentTracer:this,socket:this.socket})}},Cu=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Di({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Di({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Di({parentStep:null,parentTracer:null,socket:this.socket})}};var B1=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let s=t.getSession(n.id);if(!s)throw new Error("No active Android session found");let c=e.child({testId:i.testMetadata.id}),l=await o(r.orgId),u=s.controller;u.resetAbortController();let d=new Cu(n),m=await wu({work:{fastForwardingToStep:!!i.fromStep},fixtures:{controller:u,logger:c,cacheStorage:l,usageTracker:new ll},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testName:r.testName,testMetadata:i.testMetadata,interactive:!0},tracer:d,callbacks:{step:{onAiActionEvent:p=>{n.emit("aiActionEvent",p)}}}});await d.finish();let g={results:Ut.array().parse(m.results),status:m.status};a?.(g)},dx={event:"execute",createHandler:B1};import{debounce as z1}from"ts-debounce";var H1=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=z1(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&(o.local||n(o.emulatorName))}},mx={event:"keepalive",createHandler:H1};var px=[dx,JR,mx,QR];function gx(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new G1(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async s=>{let c=s.id,l=e.child({sessionId:c});l.info({event:"connection",transport:s.conn.transport.name},"Android websocket connection initiated"),s.on("disconnect",async()=>{await XR({socket:s,globalStateManager:n,logger:l})});let u;try{u=await YR({...r,socket:s,globalStateManager:n,logger:l})}catch(d){l.error({err:d},"Failed to setup Android connection"),s.emit("error",{message:d instanceof Error?d.message:JSON.stringify(d)}),s.disconnect(!0);return}px.forEach(d=>a(d,{...r,socket:s,metadata:u,logger:l}))});let a=(s,c)=>{let l=s.createHandler(c),u=(...d)=>{s.event!=="keepalive"&&c.logger.debug({event:s.event},`Websocket event (${s.event})`);let m=g=>{c.logger.error({event:s.event,err:g instanceof Error?g:new Error(`${g}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:g instanceof Error?g.message:typeof g=="string"?g:JSON.stringify(g)})};try{let g=l.apply(this,d);g&&typeof g.catch=="function"&&g.catch(m)}catch(g){m(g)}};c.socket.on(s.event,u)};return{server:o,dispose:i}}import{randomUUID as $G}from"crypto";import{diff as xNe}from"deep-object-diff";import FNe from"yaml";import{z as zNe}from"zod";import{execSync as V1}from"child_process";function Gn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,C.debug({postSaveCommand:n},"Executing post-save hook command");try{V1(n,{encoding:"utf-8"})}catch(o){C.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as oNe}from"deep-object-diff";import{cloneDeep as aNe}from"lodash-es";import{v4 as yNe}from"uuid";import ENe from"yaml";import W1 from"@dotenvx/dotenvx";import j1 from"fs";import hx from"path";function fx(r,e){return(r.config.environments??[]).map(t=>Ss(t.name,r,e))}function $1(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 q1(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 s=$1(i);s&&(n[o]=s);continue}let a;try{a=j1.readFileSync(hx.resolve(t.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else n[o]=a}return Object.keys(n).length>0&&C.debug(n,"Set environment variables with interpolation from project configuration"),n}function K1(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=W1.config({path:hx.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 Ss(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`);let o={},i=q1({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=K1({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}}import{existsSync as sH,readFileSync as lH,readdirSync as cH,writeFileSync as uH}from"fs";import{glob as dH}from"glob";import Mo,{dirname as bx}from"path";import{cwd as jg}from"process";import Ex from"yaml";import{z as _e}from"zod";import Sx from"fs";import{glob as Y1}from"glob";import ys from"path";import X1 from"yaml";import{z as Hg}from"zod";var yx=!1,Gg=["**/*.test.yaml","**/*.module.yaml"],Vg=Hg.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Wg=15,J1=Hg.object({fileType:Hg.nativeEnum(Ie)});async function hr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Gg,o=Array.from(r.config.exclude??[]).concat(Al),i=AbortSignal.timeout(5e3),a;try{a=await Y1(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Wg,nodir:!0,signal:i})}catch(s){throw C.error({err:s},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:s})}for(let s of a){let c=Q1(r.rootDir,s,t,e?Cn:C);c&&(t.duplicateEntities[c.id]=c.paths)}return yx=!0,t}function Q1(r,e,t,n){let o=ys.join(r,e),i=Z1(o,n);if(!i)return;let a=eH(i,o,n);if(!a)return;let s=J1.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=tH(o,n);if(!l)return;let u=rH(e,o,l);switch(c){case Ie.TEST:try{return nH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Ie.MODULE:try{return oH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case Ie.MOBILE_TEST:try{return aH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case Ie.MOBILE_MODULE:try{return iH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function Z1(r,e){try{return Sx.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function eH(r,e,t){try{let n=X1.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 tH(r,e){try{return Sx.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function rH(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ys.sep,fullPathSegments:e.split(ys.sep),relativePathSegments:r.split(ys.sep),fileName:ys.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function nH(r,e,t,n,o){let i=ti.parse(r),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:Ie.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function oH(r,e,t,n,o){let i=Zt.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:Ie.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!yx&&Xr(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function iH(r,e,t,n,o){let i=Aa.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:Ie.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function aH(r,e,t,n,o){let i=Er.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:Ie.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}var ki="momentic.config.yaml",$g="momentic.workspace.yaml",mH=_e.object({projects:_e.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),pH=_e.union([_e.string(),_e.object({fromFile:_e.string(),json:_e.boolean().optional()})]),gH=_e.object({name:Vg,baseUrl:_e.string().optional().describe("Optional for mobile tests"),envFile:_e.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:_e.record(_e.string(),pH).optional(),inheritFromShell:_e.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:to.optional().describe("NB: most things should use project-level configuration only")}),hH=_e.object({postSave:_e.string().optional()}),fH=_e.object({name:Vg,include:_e.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:_e.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:_e.string().optional(),reporterDir:_e.string().optional(),outputDir:_e.string().optional(),recordVideo:_e.boolean().optional(),retries:_e.number().optional().describe("number of retries per test"),parallel:_e.number().optional().describe("degree of parallelism"),environments:_e.array(gH).optional(),gitMainBranch:_e.string().optional(),gitProtectedBranches:_e.string().array().optional(),ai:pm.optional(),browser:to.optional(),emulator:rm.optional(),advanced:gm.optional(),hooks:hH.optional()});function Tx(r,e){let t;try{t=lH(r,"utf-8")}catch(o){C.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=Ex.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){C.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function qg(r){let e=Tx(r,"project configuration");if(e!==void 0)try{return fH.parse(e)}catch(t){C.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function SH(r){let e=Tx(r,"workspace configuration");if(e!==void 0)try{return mH.parse(e)}catch(t){C.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function yH(){let r=[],e=jg(),t=Mo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Mo.basename(e);if(vl.includes(i))return C.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of cH(e))if(a.endsWith(ki)){let s=Mo.join(e,a),c=qg(s);c&&r.push({configFilePath:s,config:c,rootDir:bx(s)})}if(r.length)return r;if(e=Mo.dirname(e),e===t)break}return r}async function bs(r={}){let{configFilePath:e,nameFilter:t}=r,n=await EH(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:
|
|
4278
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return C.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function bH(r){let e=SH(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${ki}`)),n=AbortSignal.timeout(2e3),o;try{o=await dH(t,{absolute:!1,cwd:jg(),dotRelative:!1,maxDepth:Wg,nodir:!0,signal:n})}catch(a){throw C.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${$g} is misconfigured.`),a}let i=[];for(let a of o){let s=Mo.join(jg(),a),c=qg(s);c&&i.push({configFilePath:s,config:c,rootDir:bx(s)})}return i}async function EH(r){if(r){r=Mo.resolve(r);let t=qg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Mo.dirname(r)}]}if(sH($g)){let t=await bH($g);if(t)return t}return yH()}function vx(r,e){let t=Ex.stringify(r);uH(e,t)}import{z as Kg}from"zod";var Ax="test-results";var
|
|
4277
|
+
`;import{tool as R1}from"ai";import{randomUUID as x1}from"crypto";import M1 from"zod";import{tool as w1}from"ai";import C1 from"zod";var ix=r=>{let e=w1({description:"Get the current state of the emulator (XML + screenshot)",inputSchema:C1.object({}),toModelOutput:t=>t,execute:async()=>{let{controller:t,logger:n,contextManager:o}=r;return o.recordGenericToolCall(Ug),n.info("AI action tool called (get_emulator_state)"),Fg(t)}});return{name:Ug,tool:e}};async function Fg(r){let e=await r.getA11yTree(),t=await r.getScreenshotBase64();return{type:"content",value:[{type:"text",text:"<emulatorXml>"},{type:"text",text:e},{type:"text",text:"</emulatorXml>"},{type:"text",text:"<screenshot>"},{type:"media",data:t,mediaType:"image/png"},{type:"text",text:"</screenshot>"}]}}var ax=r=>({name:"create_execute_step",tool:R1({description:"Create and immediately execute a new Momentic step in the Android emulator, returning the result from the step and the state of the emulator after the step finished executing.",inputSchema:M1.object({step:Zd}),toModelOutput:t=>t,execute:async({step:t})=>{let{contextManager:n,logger:o,controller:i}=r;o.info({step:t},"AI action tool called (create_execute_step)");let a=Ry(t),s={id:x1(),type:"MOBILE_PRESET_STEP",command:a},c=await n.createAndExecuteStep(s);c.status==="SUCCESS"&&await i.waitForScreenshotStability({reason:"Waiting for stability after executing AI-generated sub-step"});let l={...c,trace:void 0,beforeSnapshot:void 0,afterSnapshot:void 0},u=await Fg(i);return{type:"content",value:[{type:"text",text:"<result>"},{type:"text",text:JSON.stringify(l,null,2)},{type:"text",text:"</result>"},{type:"text",text:"<stateAfter>"},...u.value,{type:"text",text:"</stateAfter>"}]}}})});import{tool as _1}from"ai";import Bg from"zod";var sx=r=>{let e=_1({description:"Signal that the AI action has reached a terminal state (either success or failure).",inputSchema:Bg.object({message:Bg.string(),success:Bg.boolean()}),toModelOutput:t=>t,execute:async({message:t,success:n})=>{let{contextManager:o,logger:i}=r;return i.info({message:t,success:n},"AI action tool called (finish)"),o.finalState={message:t,status:n?"SUCCESS":"FAILED"},{type:"content",value:[{type:"text",text:"Done"}]}}});return{name:vu,tool:e}};var lx=[ax,ix,sx];function cx(r){let{logger:e,controller:t,contextManager:n,aiActionSessionId:o}=r,i={};for(let c of lx){let l=c({contextManager:n,logger:e,controller:t});i[l.name]=l.tool}let a=t.generator.getVercelAnthropicModelFactory({loggerTags:fe(e),sessionId:o}),s=c=>{let{messages:l}=c,u=!1;for(let d=l.length-1;d>=0;d--){let m=l[d];for(let g of m.content)if(!(typeof g!="object"||!("type"in g))&&!(g.type!=="tool-result"||g.output.type!=="content")&&!(g.output.value.length<3))for(let p=0;p<g.output.value.length;p++){let h=g.output.value[p];if(h.type==="text"&&h.text.includes("<emulatorXml>"))if(u){let f=g.output.value[p+1];f.type==="text"?f.text="TRUNCATED DUE TO CONVERSATION LENGTH":e.warn({msg:f},"Got unexpected part when truncating emulator state message")}else{u=!0;continue}}}return c};return{model:a("claude-haiku-4-5-20251001"),tools:i,prepareStep:s,stopWhen:[I1(15),P1(vu)],system:ox(!1)}}async function ux(r){let e=Date.now(),{controller:t,logger:n}=r.fixtures;try{return await N1(r)}catch(o){let i=t.isAborted()||o instanceof DOMException&&o.name==="AbortError";return i||n.error({err:o},"Failed to execute mobile AI action"),{...r.aiActionParams.step,steps:[],type:"MOBILE_AI_ACTION_STEP",startTime:e,endTime:Date.now(),status:i?"CANCELLED":"FAILED",message:i?"Step cancelled.":`${o}`}}}async function N1(r){let{step:e,stepTracer:t,executeMobileStepList:n}=r.aiActionParams,{controller:o,logger:i}=r.fixtures,{step:a}=r.callbacks,s=await t.startSubSteps(),c=L1(),l=i.child({stepId:e.id,aiActionSessionId:c}),u=Date.now(),d=async(f,E)=>{let b=await n({...r,listParams:{steps:[f],tracer:s,containerName:`AI action sub-step ${E}`}});if(b.results.length!==1)throw new Error("InternalWebAgentError: Expected exactly one result from executeMobileStepList");return b.results[0]},m={stepId:e.id,parentStepIdChain:t.getParentStepIdChain()},g=new Tu({controller:o,callbacks:{onAiActionEvent:a?.onAiActionEvent,executeStep:d},logger:l,rootStep:m}),p=cx({controller:o,logger:l,contextManager:g,aiActionSessionId:c}),h=O1({...p,messages:[{role:"user",content:e.text}],abortSignal:o.abortSignal});for await(let f of h.fullStream)switch(o.throwIfAborted(),f.type){case"text-delta":a?.onAiActionEvent?.({type:"LLM_TEXT_OUTPUT",text:f.text,rootStep:m})}if(await h.response,o.throwIfAborted(),!g.finalState)throw new Error("InternalWebAgentError: The AI agent never reached a final state. This could be because the maximum number of steps was reached.");return{...e,status:g.finalState.status,startTime:u,endTime:Date.now(),message:g.finalState.message,steps:g.results}}var D1=60*60*1e3;async function Au(r){let{fixtures:e,inputs:t,listParams:n,work:o}=r,{containerName:i,steps:a,tracer:s}=n,{logger:c,controller:l,usageTracker:u}=e,d=s.getParentStepIdChain(),m=[],g,p="SUCCESS",{fromStep:h,toStep:f}=t;for(let E=0;E<a.length;E++){let b=a[E];if(b.skipped)continue;if(o.fastForwardingToStep&&h){let w=JSON.stringify(d);if(b.id===h.fromStepId&&w===JSON.stringify(h.parentStepIdChain))o.fastForwardingToStep=!1;else if(!Rw({currentStep:b,currentParentChain:d,desiredStepId:h.fromStepId,desiredStepParentChain:h.parentStepIdChain}))continue}let x=0,v=1,A=Date.now();b.retries&&b.retries>0&&(v+=b.retries);let _=[];for(;x<v&&Date.now()-A<D1;){x++;let w=`Executing step index ${E} in ${i} - ${Bp(b)}`;x!==1&&(w+=` (attempt ${x})`),c.info(w);let N=Date.now(),G=await s.startStep({logger:c,step:b,attempt:x,parentStepIdChain:d});u.trackStepExecution(b);let W=await k1({step:b,stepTracer:G,params:r}),{trace:ye}=await G.finish({parentStepIdChain:d,result:W});if(W.trace=ye,w=`Finished step index ${E} in ${i} - ${Bp(b)}`,x!==1&&(w+=` (attempt ${x})`),c.info({step:{id:b.id},trace:W.trace,status:W.status},w),W.status!=="SUCCESS"&&x<v){_.push(W),Date.now()-N<1e3&&await q(1e3-(Date.now()-N));continue}if(_.length>0&&(W.previousAttempts=_),m.push(W),W.status!=="SUCCESS")return p=W.status,g=W,{results:m,status:p,terminalResult:g};if(b.envKey&&l.context.setVariable(b.envKey,W.data),f){let Se=JSON.stringify(d);if(b.id===f.toStepId&&Se===JSON.stringify(f.parentStepIdChain))return o.shouldStopExecuting=!0,{results:m,status:p,terminalResult:g}}if(o.shouldStopExecuting)return{results:m,status:p,terminalResult:g};break}}return{results:m,status:p,terminalResult:g}}async function k1({step:r,stepTracer:e,params:t}){let{fixtures:n,inputs:o,callbacks:i,work:a}=t,s;switch(r.type){case"MOBILE_PRESET_STEP":{s=await rx({fixtures:n,inputs:o,step:r,stepTracer:e,callbacks:i,work:a});break}case"RESOLVED_MOBILE_MODULE":{s=await ex({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:Au}});break}case"MOBILE_AI_ACTION_STEP":{s=await ux({...t,aiActionParams:{step:r,stepTracer:e,executeMobileStepList:Au}});break}}return s}async function wu(r){let{tracer:e,containerName:t}=r,{steps:n,testMetadata:o}=r.inputs,{cacheStorage:i,logger:a,controller:s}=r.fixtures,c=a.child({testId:r.inputs.testMetadata.id,testName:r.inputs.testName});await i.resolveEntries({logger:c,testId:o.id,stepLists:{steps:n}});let l=F1(n);c.info({testMetadata:Er.parse(o)},"Starting mobile test");let u=await e.startMainStepList(),d=EE(c),m=ZR(s,c);c.info({cpu:d?.cpuMetadata,platform:d?.platform},`Starting execution of ${t}`);let{status:g,results:p}=await Au({...r,listParams:{containerName:t,tracer:u,steps:l}});if(clearInterval(d?.interval),clearInterval(m),g==="SUCCESS"){let h=U1(l,n);if(h&&Object.keys(h).length>0){c.info({diffs:JSON.stringify(h)},"Saving mobile step cache entries post-success");let{cachesToSave:f}=await Ln({steps:l,cacheCreationParams:{orgId:r.inputs.orgId,testId:o.id}});await i.saveEntries({logger:c,testId:o.id,entries:f})}else c.info("No cache entries to update");return{status:"PASSED",results:p}}return g==="CANCELLED"?{status:"CANCELLED",results:p}:{status:"FAILED",results:p}}var zg=class{parentTracer=null;socket;step;interactionTracer;constructor({step:e,socket:t,parentTracer:n}){this.socket=t,this.parentTracer=n,this.step=e,this.interactionTracer=new Co,an.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...eE.parse(e),trace:om.parse(t)};switch(n.result.status){case"SUCCESS":this.socket.emit("success",n);break;case"FAILED":this.socket.emit("failure",n);break;case"CANCELLED":this.socket.emit("cancelled",n);break}return{trace:t}}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}async startSubSteps(){return new Di({parentStep:this.step,socket:this.socket,parentTracer:this})}},Di=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:t,parentTracer:n}){this.parentTracer=n,this.parentStep=e,this.socket=t}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:e.parentStepIdChain,attempt:e.attempt}),new zg({step:e.step,parentTracer:this,socket:this.socket})}},Cu=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Di({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Di({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Di({parentStep:null,parentTracer:null,socket:this.socket})}};var B1=({metadata:r,logger:e,globalStateManager:t,socket:n,cacheStorageFactory:o})=>async(i,a)=>{let s=t.getSession(n.id);if(!s)throw new Error("No active Android session found");let c=e.child({testId:i.testMetadata.id}),l=await o(r.orgId),u=s.controller;u.resetAbortController();let d=new Cu(n),m=await wu({work:{fastForwardingToStep:!!i.fromStep},fixtures:{controller:u,logger:c,cacheStorage:l,usageTracker:new ll},containerName:"entire test",inputs:{steps:i.steps,fromStep:i.fromStep,toStep:i.toStep,orgId:r.orgId,testName:r.testName,testMetadata:i.testMetadata,interactive:!0},tracer:d,callbacks:{step:{onAiActionEvent:p=>{n.emit("aiActionEvent",p)}}}});await d.finish();let g={results:Ut.array().parse(m.results),status:m.status};a?.(g)},dx={event:"execute",createHandler:B1};import{debounce as z1}from"ts-debounce";var H1=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=z1(t,3e4,{maxWait:6e4});return async()=>{let o=e.getSession(r.id);if(!o)throw new Error("No active Android session found");o.emulatorName&&(o.local||n(o.emulatorName))}},mx={event:"keepalive",createHandler:H1};var px=[dx,JR,mx,QR];function gx(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new G1(t,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0}),i=async()=>{await n.removeAllSessions(e)};o.on("connection",async s=>{let c=s.id,l=e.child({sessionId:c});l.info({event:"connection",transport:s.conn.transport.name},"Android websocket connection initiated"),s.on("disconnect",async()=>{await XR({socket:s,globalStateManager:n,logger:l})});let u;try{u=await YR({...r,socket:s,globalStateManager:n,logger:l})}catch(d){l.error({err:d},"Failed to setup Android connection"),s.emit("error",{message:d instanceof Error?d.message:JSON.stringify(d)}),s.disconnect(!0);return}px.forEach(d=>a(d,{...r,socket:s,metadata:u,logger:l}))});let a=(s,c)=>{let l=s.createHandler(c),u=(...d)=>{s.event!=="keepalive"&&c.logger.debug({event:s.event},`Websocket event (${s.event})`);let m=g=>{c.logger.error({event:s.event,err:g instanceof Error?g:new Error(`${g}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:g instanceof Error?g.message:typeof g=="string"?g:JSON.stringify(g)})};try{let g=l.apply(this,d);g&&typeof g.catch=="function"&&g.catch(m)}catch(g){m(g)}};c.socket.on(s.event,u)};return{server:o,dispose:i}}import{randomUUID as qG}from"crypto";import{diff as MNe}from"deep-object-diff";import BNe from"yaml";import{z as HNe}from"zod";import{execSync as V1}from"child_process";function Gn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,C.debug({postSaveCommand:n},"Executing post-save hook command");try{V1(n,{encoding:"utf-8"})}catch(o){C.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as iNe}from"deep-object-diff";import{cloneDeep as sNe}from"lodash-es";import{v4 as bNe}from"uuid";import TNe from"yaml";import W1 from"@dotenvx/dotenvx";import j1 from"fs";import hx from"path";function fx(r,e){return(r.config.environments??[]).map(t=>Ss(t.name,r,e))}function $1(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 q1(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 s=$1(i);s&&(n[o]=s);continue}let a;try{a=j1.readFileSync(hx.resolve(t.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{n[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else n[o]=a}return Object.keys(n).length>0&&C.debug(n,"Set environment variables with interpolation from project configuration"),n}function K1(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=W1.config({path:hx.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 Ss(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`);let o={},i=q1({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=K1({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}}import{existsSync as sH,readFileSync as lH,readdirSync as cH,writeFileSync as uH}from"fs";import{glob as dH}from"glob";import Mo,{dirname as bx}from"path";import{cwd as jg}from"process";import Ex from"yaml";import{z as _e}from"zod";import Sx from"fs";import{glob as Y1}from"glob";import ys from"path";import X1 from"yaml";import{z as Hg}from"zod";var yx=!1,Gg=["**/*.test.yaml","**/*.module.yaml"],Vg=Hg.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Wg=15,J1=Hg.object({fileType:Hg.nativeEnum(Ie)});async function hr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??Gg,o=Array.from(r.config.exclude??[]).concat(Al),i=AbortSignal.timeout(5e3),a;try{a=await Y1(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Wg,nodir:!0,signal:i})}catch(s){throw C.error({err:s},"Failed to list all Momentic files in the current directory. This usually indicates the 'include' and 'exclude' globs are misconfigured in your momentic.config.yaml, or that your machine is severely resource constrained."),new Error("Listing Momentic files timed out after 5 seconds.",{cause:s})}for(let s of a){let c=Q1(r.rootDir,s,t,e?Cn:C);c&&(t.duplicateEntities[c.id]=c.paths)}return yx=!0,t}function Q1(r,e,t,n){let o=ys.join(r,e),i=Z1(o,n);if(!i)return;let a=eH(i,o,n);if(!a)return;let s=J1.safeParse(a);if(s.success===!1){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=tH(o,n);if(!l)return;let u=rH(e,o,l);switch(c){case Ie.TEST:try{return nH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case Ie.MODULE:try{return oH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case Ie.MOBILE_TEST:try{return aH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case Ie.MOBILE_MODULE:try{return iH(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile module metadata: ${d}`);return}default:{let d=c;return}}}function Z1(r,e){try{return Sx.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function eH(r,e,t){try{let n=X1.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 tH(r,e){try{return Sx.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function rH(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:ys.sep,fullPathSegments:e.split(ys.sep),relativePathSegments:r.split(ys.sep),fileName:ys.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function nH(r,e,t,n,o){let i=ti.parse(r),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,n]}}return e.tests[i.id]={type:Ie.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function oH(r,e,t,n,o){let i=Zt.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:Ie.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!yx&&Xr(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function iH(r,e,t,n,o){let i=Aa.parse(r),a;if(e.mobileModules[i.moduleId]){let c=e.mobileModules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[c,n]}}let s=t.fileName.replace(".module.yaml","");return e.mobileModules[i.moduleId]={type:Ie.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function aH(r,e,t,n,o){let i=Er.parse(r),a;if(e.mobileTests[i.id]){let c=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[c,n]}}let s=t.fileName.replace(".test.yaml","");return e.mobileTests[i.id]={type:Ie.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}var ki="momentic.config.yaml",$g="momentic.workspace.yaml",mH=_e.object({projects:_e.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),pH=_e.union([_e.string(),_e.object({fromFile:_e.string(),json:_e.boolean().optional()})]),gH=_e.object({name:Vg,baseUrl:_e.string().optional().describe("Optional for mobile tests"),envFile:_e.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:_e.record(_e.string(),pH).optional(),inheritFromShell:_e.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:to.optional().describe("NB: most things should use project-level configuration only")}),hH=_e.object({postSave:_e.string().optional()}),fH=_e.object({name:Vg,include:_e.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:_e.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:_e.string().optional(),reporterDir:_e.string().optional(),outputDir:_e.string().optional(),recordVideo:_e.boolean().optional(),retries:_e.number().optional().describe("number of retries per test"),parallel:_e.number().optional().describe("degree of parallelism"),environments:_e.array(gH).optional(),gitMainBranch:_e.string().optional(),gitProtectedBranches:_e.string().array().optional(),ai:pm.optional(),browser:to.optional(),emulator:rm.optional(),advanced:gm.optional(),hooks:hH.optional()});function Tx(r,e){let t;try{t=lH(r,"utf-8")}catch(o){C.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=Ex.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){C.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function qg(r){let e=Tx(r,"project configuration");if(e!==void 0)try{return fH.parse(e)}catch(t){C.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function SH(r){let e=Tx(r,"workspace configuration");if(e!==void 0)try{return mH.parse(e)}catch(t){C.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function yH(){let r=[],e=jg(),t=Mo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=Mo.basename(e);if(vl.includes(i))return C.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of cH(e))if(a.endsWith(ki)){let s=Mo.join(e,a),c=qg(s);c&&r.push({configFilePath:s,config:c,rootDir:bx(s)})}if(r.length)return r;if(e=Mo.dirname(e),e===t)break}return r}async function bs(r={}){let{configFilePath:e,nameFilter:t}=r,n=await EH(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:
|
|
4278
|
+
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return C.debug(`Found valid project configuration at ${n[0].configFilePath}`),n[0]}async function bH(r){let e=SH(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${ki}`)),n=AbortSignal.timeout(2e3),o;try{o=await dH(t,{absolute:!1,cwd:jg(),dotRelative:!1,maxDepth:Wg,nodir:!0,signal:n})}catch(a){throw C.error({err:a},`Failed to list the available Momentic projects in the current directory. This usually indicates the 'include' or 'exclude' option in your ${$g} is misconfigured.`),a}let i=[];for(let a of o){let s=Mo.join(jg(),a),c=qg(s);c&&i.push({configFilePath:s,config:c,rootDir:bx(s)})}return i}async function EH(r){if(r){r=Mo.resolve(r);let t=qg(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:Mo.dirname(r)}]}if(sH($g)){let t=await bH($g);if(t)return t}return yH()}function vx(r,e){let t=Ex.stringify(r);uH(e,t)}import{z as Kg}from"zod";var Ax="test-results";var CDe=Kg.object({width:Kg.number(),height:Kg.number()});import{execFile as TH}from"node:child_process";import{promisify as vH}from"node:util";import AH from"simple-git";var Le=AH(),wx=vH(TH);async function wH(r){let e=await Ne(r,Le.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
4279
4279
|
`)){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 CH(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 wx("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await wx("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function RH(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return CH(r,e,t);if(o)return}catch{}}function Ru(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 Ne(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function xH(){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 MH(r){let[e,t,n]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]),o=process.env.GITHUB_SERVER_URL&&process.env.GITHUB_REPOSITORY?`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}`:void 0;return{ciProvider:"GithubActions",gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function _H(r){let[e,t,n]=await Promise.all([Ne(r,Le.listRemote(["--get-url","origin"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]);return{ciProvider:"GitlabCI",gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:n,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function PH(r){let[e,t,n,o]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.listRemote(["--get-url","origin"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]),i=process.env.CIRCLE_REPOSITORY_URL??t,a=i?.includes("github.com"),s=i?.includes("gitlab.com"),c=i?Ru(i):void 0;return{ciProvider:"CircleCI",gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:i,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:a?c:void 0,gitlabProjectPath:s?c:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function IH(r){let[e,t,n]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ru(o):void 0;return{ciProvider:"Buildkite",gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function OH(r){let[e,t,n]=await Promise.all([Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ru(o):void 0;return{ciProvider:"AzureDevOps",gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["System.PullRequest.SourceBranch"]??process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:n,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function LH(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Ne(r,Le.revparse(["HEAD"])),Ne(r,Le.revparse(["--short","HEAD"])),Ne(r,Le.revparse(["--abbrev-ref","HEAD"])),Ne(r,Le.listRemote(["--get-url","origin"])),Ne(r,Le.show(["--no-patch","--format=%ci"])),Ne(r,Le.show(["-s","--pretty=%B"])),Ne(r,Le.show(["-s","--pretty=%an"])),e?Ne(r,Le.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),wH(r)]),d=l?await Ne(r,Le.show(["--no-patch","--format=%ci",l])):void 0,m=i?.includes("github.com"),g=i?.includes("gitlab.com"),p=i?Ru(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await RH(r,i,u)??E??void 0;return{ciProvider:"none",gitCommitSha:t,gitCommitShaShort:n,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:m?p:void 0,gitlabProjectPath:g?p:void 0,pipelineId:void 0}}async function NH(){let r=process.env._HEAD_REPO_URL;return{ciProvider:"GCPCloudBuild",gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl: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 DH(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function Es(r,e){let t=xH();if(!t)return LH(r,e);switch(t){case"GithubActions":return MH(r);case"GitlabCI":return _H(r);case"CircleCI":return PH(r);case"Buildkite":return IH(r);case"AzureDevOps":return OH(r);case"GCPCloudBuild":return NH()}}async function kH(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 UH(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 FH(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await UH(r,e,n,o,t)}else if(t.gitlabProjectPath)return await kH(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Ui(r,e,t){let n=await DH(t),o=await Es(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 FH(r,e,i);return{...n,...o,...a}}import{diff as Cx}from"deep-object-diff";import Vn from"fs";import{cloneDeep as BH}from"lodash-es";import xu from"path";import{v4 as zH}from"uuid";import Ts from"yaml";function Rx({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!Vn.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=Vn.readFileSync(i,"utf-8"),s=Ts.parse(a),c={...s,...r,schemaVersion:e},l=yo({fileType:Ie.MOBILE_MODULE,...Aa.parse(c),steps:ir.array().parse(r.steps)}),u=Cx(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=Ts.stringify(l);Vn.writeFileSync(i,d,"utf-8"),Gn(i,n.config)}function xx({moduleId:r,patch:e,momenticFiles:t,project:n,logger:o}){let i=t.mobileModules[r]?.fullFilePath;if(!i)throw new Error(`Tried to update mobile module ${r} that could not be found on disk`);let a=vs(i,o),s={...a,...e},c=yo({fileType:Ie.MOBILE_MODULE,...yl.parse(s)}),l=Cx(c,a);if(l&&Object.keys(l).length===0)return;let u=Ts.stringify(c);Vn.writeFileSync(i,u,"utf-8");let d;if(e.name){let m=`${Xr(e.name)}.module.yaml`;if(d=xu.join(xu.dirname(i),m),Vn.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);Vn.renameSync(i,d)}Gn(d||i,n.config)}async function Mx({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=Xr(r),s=xu.join(o,`${a}.module.yaml`),c=zH(),{stepsToSave:l}=await Ln({steps:n}),u={schemaVersion:yn,moduleId:c,description:e,enabled:t},d={fileType:Ie.MOBILE_MODULE,...u,steps:l},m=Ts.stringify(Dy.parse(d));return Vn.writeFileSync(s,m,"utf-8"),Gn(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function vs(r,e){let t=Vn.readFileSync(r,"utf-8"),n=Ts.parse(t);try{return{...yl.parse(n),name:xu.basename(r,".module.yaml")}}catch(o){throw e.error({err:o,moduleFilePath:r,moduleContents:t},`${r} does not parse as a valid Momentic mobile module`),o}}async function Yg(r,e,t,n){let o=vs(r.fullFilePath,t),{resolvedSteps:i}=await Fc({rawSteps:o.steps,resolvedModuleCache:n||{},onFetchModule:async s=>{let c=e.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Could not find mobile module with id ${s}`);return vs(c,t)},logger:t,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion}}),a={...o,name:r.name,description:o.description||void 0,steps:i};return n&&(n[r.id]=BH(a)),a}async function _x(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Yg(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as HH}from"crypto";import _o from"fs";import Jg from"path";import Mu from"yaml";import Xg from"zod";function Px({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${Xr(r)}.test.yaml`,s=Jg.join(o,a);if(_o.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:Ie.MOBILE_TEST,id:HH(),description:e,schemaVersion:Zn,settings:n,steps:t},l=Mu.stringify(c);return _o.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function GH(r){if(!_o.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=_o.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4280
4280
|
`),t=Mu.parse(e);if(!t.steps||!Array.isArray(t.steps))throw new Error(`Test ${r} is missing steps`);return t}async function _u(r,e,t){let n=GH(r),o;try{o=Er.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await vw({rawStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},logger:e,testMetadata:o,onFetchModule:async s=>{let c=t.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Mobile module ${s} not found`);return vs(c,e)}});return{...o,steps:i.steps}}async function Ix({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i,schemaVersion:a}){let s=Jg.isAbsolute(r)?r:Jg.join(n,r);if(!_o.existsSync(s))throw new Error(`Test file not found: ${s}`);let c=_o.readFileSync(s,"utf-8").replace(/\r\n|\r/g,`
|
|
4281
|
-
`),l=Mu.parse(c),u=nm.extend({steps:Xg.record(Xg.string(),Xg.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Ie.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Ln({steps:e}));let m={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=Mu.stringify(m);for(let p of d?.moduleUpdates??[])Rx({content:p,schemaVersion:Zn,momenticFiles:i,project:o});_o.writeFileSync(s,g,"utf-8"),Gn(s,o.config)}import{randomUUID as VH}from"crypto";import Wn from"fs";import Fi from"path";var Ox=new Set([".DS_Store","__MACOSX"]),Lx={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 WH(r,e,t){if(Lx[t]){let i=Lx[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 Qg=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function Nx(r,e){try{let t=Fi.join(e,"metadata.json");return Il.parse(JSON.parse(Wn.readFileSync(t,"utf-8")))}catch{throw new Qg(r,e)}}function Dx(r,e,t){let n=VH(),o=r.child({runGroupId:n});Wn.rmSync(e,{recursive:!0,force:!0});let i=Wn.readdirSync(t).filter(c=>!Ox.has(c)).map(c=>Fi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Wn.mkdirSync(e,{recursive:!0});let a={...Nx(t,i[0]),id:n};for(let c of i){let l=Fi.join(c,"runs");if(!Wn.existsSync(l))continue;let u=Nx(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let g=m;a[g]=WH(a,u,g)}let d=Wn.readdirSync(l);for(let m of d){if(Ox.has(m))continue;let g=Fi.join(l,m),p=Fi.join(e,"runs",m);Wn.cpSync(g,p,{recursive:!0})}}let s=Fi.join(e,"metadata.json");Wn.writeFileSync(s,JSON.stringify(a,null,2))}import Ux from"adm-zip";import oh from"fs";import{z as JH}from"zod";var U="v1",Zg="mobile-cli",Po="0.9.1";var jH=9e4,$H=3,qH=1500,KH=15e3,Cr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function YH(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var eh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Po&&(e[Ml]=Po),Zg&&(e[lb]=Zg),e}async sendRequest(e,t){let{retries:n=$H,requestTimeoutMs:o=jH,initialRetryDelayMs:i=qH,maxRetryDelayMs:a=KH,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Cr&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new Rn),c===0)throw u;let g=l-c,p=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,p))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await YH(u);throw new Cr(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},$r=class extends eh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[sb]:this.mode??""}}};import{createAnthropic as XH}from"@ai-sdk/anthropic";var Pu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[Ml]:Po??"",...t&&{[ub]:t},...n||{}};return o&&(a[cb]=JSON.stringify(o)),XH({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var Io=class extends $r{agentConfig;constructor(e,t){let n={...sy,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return KS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Po,...e},signal:t.abortSignal});return qS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return JH.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(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return gb.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(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return fm.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return pb.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return mb.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(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return fm.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return db.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/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(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Rd.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return hb.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return wd.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return RS.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return xS.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ud.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return ay.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return TS.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return wS.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return AS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return kh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as th}from"zod";var Rr=class extends $r{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{C.warn(`API key check failed: ${t.message}`)}});return Mb.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return wb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Sb.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return bb.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Eb.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return fb.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return xb.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _b.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Wb.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/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(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Pb.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return VS.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/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(`/${U}/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(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ib.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Ob.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Lb.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Nb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return qb.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/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(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ia.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ia.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Em.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(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ia.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ia.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Em.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return th.record(th.string(),th.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Db.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/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(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return kb.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/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(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Ub.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fb.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function rh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return C.debug("Got auth info from API"),n}var Iu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Bi=class extends $r{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Uh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var zi=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 QH,en as ZH}from"@faker-js/faker";var Hi="v1",Gi=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 QH({locale:ZH}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Hi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Cr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Hi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Hi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Hi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Hi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Hi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function kx(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ou=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await kx(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}};var Vi=class extends $r{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return cy.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return my.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Lu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Pl:new nh(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var nh=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{regenerateCache:i,alwaysSaveCache:a}=o,{gitBranchName:s,gitProtectedBranches:c}=n;this.cacheHeaders=Sm(n),this.readCaches=!i;let l=s&&c.includes(s);a||!l?this.writeCaches=!0:this.writeCaches=!1}cacheHeaders;readCaches;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.warn({err:o},"Failed to save mobile step cache entries, continuing...")}}async resolveEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&kp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Ln({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Nu from"path";function eG(r){let e=new Ux,t=Nu.join(r,"metadata.json"),n=Il.parse(JSON.parse(oh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of oh.readdirSync(Nu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new Ux(Nu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Nu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Du(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!oh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Ou(e);try{let{runGroupId:i,buffer:a}=eG(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;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 tG from"adm-zip";import Tt from"fs";import qt from"path";var As=class r{constructor(e){this.filePath=e;Tt.rmSync(this.filePath,{recursive:!0,force:!0}),Tt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(qt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){Tt.mkdirSync(qt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=qt.join(this.filePath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.filePath,t);try{Tt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=qt.join(this.filePath,e);return Tt.createWriteStream(t)}createRunArchive(e){return new ih(qt.join(this.filePath,"runs"),e)}},ih=class{constructor(e,t){this.filePath=e;this.tempPath=qt.join(e,`.${t}`),this.finalPath=qt.join(e,`${t}.zip`),Tt.rmSync(this.tempPath,{recursive:!0,force:!0}),Tt.rmSync(this.finalPath,{recursive:!0,force:!0}),Tt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=qt.join(this.tempPath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}mkdir(e){Tt.mkdirSync(qt.join(this.tempPath,e),{recursive:!0})}cd(e){return new As(qt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.tempPath,t);Tt.writeFileSync(o,n)}createFileStream(e){let t=qt.join(this.tempPath,e);return Tt.createWriteStream(t)}close(){let e=new tG;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();Tt.writeFileSync(this.finalPath,t),Tt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import Wu from"fs";import Zx from"body-parser";import vG from"cors";import AG from"dedent";import{Router as iG}from"express";import Ft from"fs";import{globSync as aG}from"glob";import ht from"path";import ku from"fs";import rG from"path";var nG=new $c(30,60*1e3),ch="https://api.momentic.ai",sh,Bx=r=>{ch=r},uh=()=>ch,ws=()=>sh;var Wi,lh,Fx,zx=async r=>{if(sh&&Wi&&Fx)return Wi;let e=new Rr({baseUrl:ch,apiKey:r,logger:C});sh=e;try{let t=await e.getAuthInfo();return Wi=t.orgId,lh=t.userId,Fx=r,Wi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ji=()=>{if(!Wi)throw new Error("Your organization ID is invalid.");return Wi},Uu=()=>{if(!lh)throw new Error("Your user ID is invalid.");return lh};var dh,ah,Hx=(r,e)=>{dh=r,ah?.abort(),ah=new AbortController;let t=ah.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=rG.resolve(r.rootDir,o.envFile);try{if(ku.lstatSync(i).isSymbolicLink())return;ku.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{oG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ve=()=>dh;function oG({filesToWatch:r,revalidator:e,signal:t,project:n}){C.debug("Starting watch on the following files:"),r.forEach(o=>{C.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(nG.increment("setLocalProject")&&C.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.`),dh=await Promise.resolve(e(n.configFilePath)))};ku.watchFile(o,{persistent:!1},i);let a=()=>{ku.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function $e(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Rs=iG();function Cs(r){let e=Ve(),t=ht.dirname(e.configFilePath);return ht.join(t,...r)}function sG(r){let e=Ve(),t=ht.dirname(e.configFilePath),n=ht.relative(t,r);return n?n.split(ht.sep):[]}function lG(r,e){let t=Ft.statSync(r),n=sG(r);return um.parse({name:e,absolutePath:r,relativePath:n.join(ht.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Rs.post("/",$e(async(r,e,t)=>{let n;try{n=qy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Cs(n);if(!Ft.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ht.sep)}`});return}if(!Ft.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}let a=Ve(),s=Array.from(a.config.exclude??[]).concat(Al),l=aG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=ht.join(o,d);return lG(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Rs.put("/",$e(async(r,e,t)=>{let n;try{n=Ky.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Cs(n);if(Ft.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ht.sep)}`,pathSegments:n});return}Ft.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ht.sep)}`,pathSegments:n};e.status(201).json(i)}));Rs.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=Yy.parse(r.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=Cs(n),a=Cs(o);if(!Ft.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ht.sep)}`});return}if(Ft.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ht.sep)}`});return}let s=ht.dirname(a);Ft.existsSync(s)||Ft.mkdirSync(s,{recursive:!0}),Ft.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ht.sep)} to ${o.join(ht.sep)}`,pathSegments:o};e.status(200).json(c)}));Rs.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=Xy.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=Cs(n);if(!Ft.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ht.sep)}`,pathSegments:n});return}if(!Ft.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}if(o)Ft.rmSync(i,{recursive:!0,force:!0});else{if(Ft.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Ft.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var mh=Rs;import{Router as dG}from"express";import{hostname as cG}from"os";var uG="0.9.1",xs=ai({app:"desktop-server",hostname:cG(),disableConsoleLogs:!0}).child({cliVersion:uG});(async()=>{try{let r=await Es(xs);r.gitBranchName&&xs.addBinding("branch",r.gitBranchName)}catch{}})();var Gx=dG();Gx.get("/",async(r,e)=>{let t=Ve(),n=ws();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ui(xs,n,t);e.status(200).json(o)});var ph=Gx;import wG from"events";import eM,{Router as CG}from"express";import RG from"http";import xG from"path";var Fu=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var Vx=new Fu;import{Router as pG}from"express";import{existsSync as gG}from"fs";import hG from"path";import{hostname as mG}from"os";var gh="0.9.1",vt=ai({app:"mobile-desktop-server",hostname:mG(),disableConsoleLogs:!0}).child({cliVersion:gh});(async()=>{try{let r=await Es(vt);r.gitBranchName&&vt.addBinding("branch",r.gitBranchName)}catch{}})();var hh=pG();hh.get("/",$e(async(r,e)=>{let t=ws();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));hh.post("/upload-url",$e(async(r,e)=>{let t;try{t=rb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ws();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=hG.resolve(t.filePath);if(!gG(o)){e.status(400).json({error:`File not found: ${o}`});return}await Pc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:vt}),e.sendStatus(204)}));var Wx=hh;import{Router as yG}from"express";import{Router as fG}from"express";import jx from"fs";import SG from"path";var Ms=fG();async function fh(r){return(await _x(r,vt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){C.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}Ms.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(n);e.status(200).json(o)}));Ms.get("/:moduleId",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await hr(Ve()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Yg(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ms.patch("/:moduleId/metadata",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=nb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await hr(n);xx({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));Ms.post("/",$e(async(r,e)=>{let t;try{t=ob.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{la(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ve(),i=(await hr(n)).mobileModules;if(Object.values(i).find(c=>c.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=SG.join(n.rootDir,t.folderPath??"");if(!jx.existsSync(a)||!jx.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Mx({...t,folder:a,project:n});e.status(201).json(s)}));var $x=Ms;var qx=yG();qx.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(n),i=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),c={labels:a,modules:o,tests:s};e.status(200).json(c)}));var Kx=qx;import{Router as bG}from"express";var Sh=bG();Sh.get("/",$e((r,e)=>{let t=fx(Ve(),vt);e.status(200).json(t)}));Sh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var Yx=Sh;import{Router as EG}from"express";var Xx=EG();Xx.get("/",(r,e)=>{e.status(200).json({userId:Uu(),orgId:ji(),cliVersion:gh??"0.0.0"})});var Jx=Xx;import{Router as TG}from"express";import yh from"path";var Bu=TG();Bu.patch("/:testPath",$e(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=tb.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=Ve(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await hr(o);await Ix({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:Zn});let s={message:"ok"};e.status(200).json(s)}));Bu.post("/",$e((r,e)=>{let t;try{t=eb.parse(r.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{la(n)}catch(p){e.status(400).json({error:p.message});return}let s=Ve(),c=yh.join(s.rootDir,...a),{fullPath:l,testId:u}=Px({name:n,description:o,steps:[],settings:i,folder:c}),d=yh.basename(l),m=yh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(g)}));Bu.get("/:fileName",$e(async(r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,o=Ve(),i=await hr(o),s=await _u(n,vt,i);e.status(200).json(s)}));var Qx=Bu;var zu=class extends zi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return Ss(t,o,C)}};var tM="10mb";async function rM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&Bx(n),await zx(t);let u=ji(),d=Uu(),m=r.logger.child({orgId:u,userId:d});Hx(i,w=>bs({configFilePath:w}));let g=eM();g.use(vG()),g.use(Zx.json({limit:tM})),g.use(Zx.urlencoded({extended:!1,limit:tM}));let p=CG();if(p.use("/folders",mh),p.use("/entities",Kx),p.use("/identify",Jx),p.use("/mobile-tests",Qx),p.use("/mobile-modules",$x),p.use("/assets",Wx),p.use("/git",ph),p.use("/environments",Yx),g.use("/api",p),g.use((w,N,G)=>{C.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),N.on("close",()=>{N.statusCode>=400&&(C.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"),vt.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"))}),G()}),g.use((w,N,G,W)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){G.status(400).send("Client disconnected");return}C.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vt.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),G.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=eM.static(o,{setHeaders:N=>{N.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(w),g.use("*",(N,G)=>{G.sendFile(xG.join(o,"index.html"))})}let h=RG.createServer(g),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),w()})}catch(N){N.message.includes("EADDRINUSE")?MG(e):C.error(`An unexpected error occurred while starting the server: ${N.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:uh(),apiKey:t,logger:m},x=new Rr(b),v=Ve(),A={...b,mode:"interactive"},{dispose:_}=gx({baseServer:h,logger:m,authorization:b,globalStateManager:Vx,getOrgId:()=>ji(),androidDriverFactory:async({socket:w,logger:N,creationOpts:G})=>{let W=Math.floor(Math.random()*1e4)+4e4,ye=await Dl(W,"appium");return _c({logger:N,driverLogLevel:a,apiClient:x,creationOpts:G,socket:w,appiumPort:ye,sessionId:w.id,orgId:ji(),onStatusUpdate:Se=>{w.emit("connectionStatusUpdate",{message:Se})}})},mobileGeneratorFactory:async w=>new Vi({baseUrl:uh(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async w=>new Io(v.config.ai?.agentConfig,A),browserEnricherFactory:async w=>new Bi(A,new Io(v.config.ai?.agentConfig,A)),storageFactory:async w=>new zu(x,w),cacheStorageFactory:async w=>{let N=await Ui(m,x,v);return Lu({orgId:w,client:x,gitMetadata:N,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Gi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:v.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await Et.flush()}catch(w){C.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{C.info("SIGTERM in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{C.info("SIGINT in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}})}wG.setMaxListeners(25);process.on("warning",r=>{vt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{vt.error({err:r},"Uncaught exception on mobile-desktop-server"),C.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{vt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),C.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function MG(r){C.error(AG`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4281
|
+
`),l=Mu.parse(c),u=nm.extend({steps:Xg.record(Xg.string(),Xg.unknown()).array()}).parse({...l,schemaVersion:a});if(u.fileType!==Ie.MOBILE_TEST)throw new Error(`File at '${s}' is not a mobile test (fileType=${u.fileType}).`);let d;e&&(d=await Ln({steps:e}));let m={...u,...d?.stepsToSave!==void 0?{steps:d.stepsToSave}:{steps:u.steps},...t!==void 0?{settings:t}:{}},g=Mu.stringify(m);for(let p of d?.moduleUpdates??[])Rx({content:p,schemaVersion:Zn,momenticFiles:i,project:o});_o.writeFileSync(s,g,"utf-8"),Gn(s,o.config)}import{randomUUID as VH}from"crypto";import Wn from"fs";import Fi from"path";var Ox=new Set([".DS_Store","__MACOSX"]),Lx={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 WH(r,e,t){if(Lx[t]){let i=Lx[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 Qg=class extends Error{constructor(e,t){let n=`${e} contains invalid Momentic results: ${t}. Please ensure that the path points to a folder containing only valid results. If you passed \`--output-dir test-results/results-1\` to the \`run\` command, your results path for merging should be \`test-results\`.`;super(n),this.name="InvalidMomenticResultsPathError"}};function Nx(r,e){try{let t=Fi.join(e,"metadata.json");return Il.parse(JSON.parse(Wn.readFileSync(t,"utf-8")))}catch{throw new Qg(r,e)}}function Dx(r,e,t){let n=VH(),o=r.child({runGroupId:n});Wn.rmSync(e,{recursive:!0,force:!0});let i=Wn.readdirSync(t).filter(c=>!Ox.has(c)).map(c=>Fi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);Wn.mkdirSync(e,{recursive:!0});let a={...Nx(t,i[0]),id:n};for(let c of i){let l=Fi.join(c,"runs");if(!Wn.existsSync(l))continue;let u=Nx(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let g=m;a[g]=WH(a,u,g)}let d=Wn.readdirSync(l);for(let m of d){if(Ox.has(m))continue;let g=Fi.join(l,m),p=Fi.join(e,"runs",m);Wn.cpSync(g,p,{recursive:!0})}}let s=Fi.join(e,"metadata.json");Wn.writeFileSync(s,JSON.stringify(a,null,2))}import Ux from"adm-zip";import oh from"fs";import{z as QH}from"zod";var U="v1",Zg="mobile-cli",Po="0.9.2";var jH=9e4,$H=3,qH=1500,KH=15e3,Cr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function YH(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var eh=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Po&&(e[Ml]=Po),Zg&&(e[lb]=Zg),e}async sendRequest(e,t){let{retries:n=$H,requestTimeoutMs:o=jH,initialRetryDelayMs:i=qH,maxRetryDelayMs:a=KH,onFailedRequest:s}=t,c=n,l=n,u,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;c>0;)try{return c--,await this.sendSingleRequestHelper(e,t,o)}catch(m){u=m;try{s?.(u)}catch{}if(m instanceof Cr&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new Rn),c===0)throw u;let g=l-c,p=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,p))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,t,n){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),n),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s,{once:!0});let c=Date.now(),l={...this.getHeaders(),...t.extraHeaders};try{let u=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!u.ok){let m=await YH(u);throw new Cr(u.status,m,`Request to ${t.method} ${e} failed with status ${u.status}: ${m}`)}let d;if(u.status===204)d={};else{let m=await u.text();try{d=JSON.parse(m)}catch{d=m}}return this.logger&&t.logResponse===!0&&d&&this.logger.debug({result:d,status:u.status,durationMs:Date.now()-c,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},$r=class extends eh{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[sb]:this.mode??""}}};import{createAnthropic as XH}from"@ai-sdk/anthropic";function JH(r){let{apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o}=r,i={Authorization:`Bearer ${e}`,[Ml]:Po??"",...t&&{[ub]:t},...n||{}};return o&&(i[cb]=JSON.stringify(o)),i}var Pu=r=>e=>{let t=JH(r);return XH({baseURL:`${r.baseUrl}/v1/llm/anthropic/${e}`,headers:t,apiKey:r.apiKey})(e)};var Io=class extends $r{agentConfig;constructor(e,t){let n={...sy,...e};super(t),this.agentConfig=n}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/recommend-chunks-ai`,{method:"POST",body:n,signal:t.abortSignal});return KS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Po,...e},signal:t.abortSignal});return qS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return QH.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(`/${U}/web-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return gb.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(`/${U}/web-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return fm.parse(o)}async getLintStepResult(e,t){let n={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/step`,{method:"POST",body:n,signal:t.abortSignal});return pb.parse(o)}async getLintMcpCopilotMessageResult(e,t){let n={message:e.message,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/lint/mcp-copilot`,{method:"POST",body:n,signal:t.abortSignal});return mb.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(`/${U}/web-agent/visual-assertion`,{method:"POST",body:n,signal:t.abortSignal});return fm.parse(o)}async getAiActionCommand(e,t){let n=await this.sendRequest(`/${U}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return db.parse(n)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${U}/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(`/${U}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Rd.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${U}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return hb.parse(n)}async getTextExtraction(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${U}/web-agent/text-extraction`,{method:"POST",body:n,signal:t.abortSignal});return wd.parse(o)}async getPageSummary(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/page-summary`,{method:"POST",body:n,signal:t.abortSignal});return RS.parse(o)}async getSmartWaitingDecision(e,t){let n={...e,disableCache:t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/web-agent/smart-waiting`,{method:"POST",body:n,signal:t.abortSignal});return xS.parse(o)}async getTestResultClassification(e,t){let n=await this.sendRequest(`/${U}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return ud.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return ay.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return TS.parse(n)}async getFailureRecoveryProposal(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return wS.parse(n)}async getFailureRecoveryPlan(e,t){let n=await this.sendRequest(`/${U}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return AS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return kh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as th}from"zod";var Rr=class extends $r{constructor(e){super({...e,mode:void 0})}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${U}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3,onFailedRequest:t=>{C.warn(`API key check failed: ${t.message}`)}});return Mb.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return wb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Sb.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${U}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return bb.parse(n)}async updateMobileStepCaches(e,t){await this.sendRequest(`/${U}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,t){let n=await this.sendRequest(`/${U}/mobile-cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Eb.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return fb.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return xb.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return _b.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${U}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return Wb.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${U}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${U}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${U}/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(`/${U}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Pb.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},n=await this.sendRequest(`/${U}/run-groups/status`,{method:"POST",body:t,retries:3,requestTimeoutMs:5e3});return VS.array().parse(n)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${U}/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(`/${U}/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(`/${U}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ib.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${U}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let n=await this.sendRequest(`/${U}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Ob.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Lb.parse(e)}async startProcessingResultsUpload(e,t){let n=await this.sendRequest(`/${U}/results/uploads/${e}/process`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Nb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return qb.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${U}/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(`/${U}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ia.parse(a)}async getCommitFromGithub(e,t,n){let o=await this.sendRequest(`/${U}/git/github/${e}/${t}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ia.parse(o)}async getMergedBranchFromGithub(e,t,n,o){let i=encodeURIComponent(n),a=await this.sendRequest(`/${U}/git/github/${e}/${t}/${i}/${o}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Em.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(`/${U}/git/gitlab/${i}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ia.parse(a)}async getCommitFromGitlab(e,t){let n=encodeURIComponent(e),o=await this.sendRequest(`/${U}/git/gitlab/${n}/commits/${t}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ia.parse(o)}async getMergedBranchFromGitlab(e,t,n){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=await this.sendRequest(`/${U}/git/gitlab/${i}/${o}/${n}/merged-branch`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Em.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return th.record(th.string(),th.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Db.parse(e)}async quarantineTest(e,t,n){await this.sendRequest(`/${U}/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(`/${U}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...n??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${U}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return kb.parse(t)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${U}/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(`/${U}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Ub.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${U}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${U}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Fb.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function rh(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(C.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),C.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return C.debug("Got auth info from API"),n}var Iu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Bi=class extends $r{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let n=await this.sendRequest(`/${U}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Uh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var zi=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 ZH,en as eG}from"@faker-js/faker";var Hi="v1",Gi=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 ZH({locale:eG}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Hi}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Cr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Hi}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Hi}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Hi}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Hi}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Hi}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Cr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function kx(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ou=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await kx(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}};var Vi=class extends $r{constructor(e){super(e)}async getElementLocation(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/locate-element`,{method:"POST",body:n,signal:t.abortSignal});return cy.parse(o)}async evaluateAssertion(e,t){let n={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${U}/mobile-agent/assertion`,{method:"POST",body:n,signal:t.abortSignal});return my.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return Pu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Lu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new Pl:new nh(r,e,t,{alwaysSaveCache:o,regenerateCache:n})}var nh=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{regenerateCache:i,alwaysSaveCache:a}=o,{gitBranchName:s,gitProtectedBranches:c}=n;this.cacheHeaders=Sm(n),this.readCaches=!i;let l=s&&c.includes(s);a||!l?this.writeCaches=!0:this.writeCaches=!1}cacheHeaders;readCaches;writeCaches;async saveEntries({entries:e,testId:t,logger:n}){if(!this.writeCaches){n.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateMobileStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){n.warn({err:o},"Failed to save mobile step cache entries, continuing...")}}async resolveEntries(e){if(!this.readCaches){e.logger.debug("Skipping cache resolution because of regenerate flag");return}let{steps:t}=e.stepLists,n=await this.client.getMobileStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.info("Skipping mobile cache last used at update because branch is protected");return}for(let i of[t])i&&kp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Ln({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Nu from"path";function tG(r){let e=new Ux,t=Nu.join(r,"metadata.json"),n=Il.parse(JSON.parse(oh.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of oh.readdirSync(Nu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new Ux(Nu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Nu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Du(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!oh.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Ou(e);try{let{runGroupId:i,buffer:a}=tG(n),s=await o.uploadResultsArchive(i,a),c=`${e.getAppUrl()}/run-groups/${s}`;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 rG from"adm-zip";import Tt from"fs";import qt from"path";var As=class r{constructor(e){this.filePath=e;Tt.rmSync(this.filePath,{recursive:!0,force:!0}),Tt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(qt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){Tt.mkdirSync(qt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=qt.join(this.filePath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.filePath,t);try{Tt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=qt.join(this.filePath,e);return Tt.createWriteStream(t)}createRunArchive(e){return new ih(qt.join(this.filePath,"runs"),e)}},ih=class{constructor(e,t){this.filePath=e;this.tempPath=qt.join(e,`.${t}`),this.finalPath=qt.join(e,`${t}.zip`),Tt.rmSync(this.tempPath,{recursive:!0,force:!0}),Tt.rmSync(this.finalPath,{recursive:!0,force:!0}),Tt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=qt.join(this.tempPath,e);if(Tt.existsSync(t))return Tt.readFileSync(t)}mkdir(e){Tt.mkdirSync(qt.join(this.tempPath,e),{recursive:!0})}cd(e){return new As(qt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=qt.join(this.tempPath,t);Tt.writeFileSync(o,n)}createFileStream(e){let t=qt.join(this.tempPath,e);return Tt.createWriteStream(t)}close(){let e=new rG;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();Tt.writeFileSync(this.finalPath,t),Tt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import Wu from"fs";import Zx from"body-parser";import AG from"cors";import wG from"dedent";import{Router as aG}from"express";import Ft from"fs";import{globSync as sG}from"glob";import ht from"path";import ku from"fs";import nG from"path";var oG=new $c(30,60*1e3),ch="https://api.momentic.ai",sh,Bx=r=>{ch=r},uh=()=>ch,ws=()=>sh;var Wi,lh,Fx,zx=async r=>{if(sh&&Wi&&Fx)return Wi;let e=new Rr({baseUrl:ch,apiKey:r,logger:C});sh=e;try{let t=await e.getAuthInfo();return Wi=t.orgId,lh=t.userId,Fx=r,Wi}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},ji=()=>{if(!Wi)throw new Error("Your organization ID is invalid.");return Wi},Uu=()=>{if(!lh)throw new Error("Your user ID is invalid.");return lh};var dh,ah,Hx=(r,e)=>{dh=r,ah?.abort(),ah=new AbortController;let t=ah.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=nG.resolve(r.rootDir,o.envFile);try{if(ku.lstatSync(i).isSymbolicLink())return;ku.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{iG({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ve=()=>dh;function iG({filesToWatch:r,revalidator:e,signal:t,project:n}){C.debug("Starting watch on the following files:"),r.forEach(o=>{C.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(oG.increment("setLocalProject")&&C.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.`),dh=await Promise.resolve(e(n.configFilePath)))};ku.watchFile(o,{persistent:!1},i);let a=()=>{ku.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function $e(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Rs=aG();function Cs(r){let e=Ve(),t=ht.dirname(e.configFilePath);return ht.join(t,...r)}function lG(r){let e=Ve(),t=ht.dirname(e.configFilePath),n=ht.relative(t,r);return n?n.split(ht.sep):[]}function cG(r,e){let t=Ft.statSync(r),n=lG(r);return um.parse({name:e,absolutePath:r,relativePath:n.join(ht.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Rs.post("/",$e(async(r,e,t)=>{let n;try{n=qy.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Cs(n);if(!Ft.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(ht.sep)}`});return}if(!Ft.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}let a=Ve(),s=Array.from(a.config.exclude??[]).concat(Al),l=sG("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=ht.join(o,d);return cG(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Rs.put("/",$e(async(r,e,t)=>{let n;try{n=Ky.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Cs(n);if(Ft.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(ht.sep)}`,pathSegments:n});return}Ft.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(ht.sep)}`,pathSegments:n};e.status(201).json(i)}));Rs.patch("/",$e(async(r,e,t)=>{let n,o;try{let l=Yy.parse(r.body);n=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let i=Cs(n),a=Cs(o);if(!Ft.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(ht.sep)}`});return}if(Ft.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(ht.sep)}`});return}let s=ht.dirname(a);Ft.existsSync(s)||Ft.mkdirSync(s,{recursive:!0}),Ft.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(ht.sep)} to ${o.join(ht.sep)}`,pathSegments:o};e.status(200).json(c)}));Rs.delete("/",$e(async(r,e,t)=>{let n,o=!0;try{let c=Xy.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=Cs(n);if(!Ft.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(ht.sep)}`,pathSegments:n});return}if(!Ft.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(ht.sep)}`});return}if(o)Ft.rmSync(i,{recursive:!0,force:!0});else{if(Ft.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Ft.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var mh=Rs;import{Router as mG}from"express";import{hostname as uG}from"os";var dG="0.9.2",xs=ai({app:"desktop-server",hostname:uG(),disableConsoleLogs:!0}).child({cliVersion:dG});(async()=>{try{let r=await Es(xs);r.gitBranchName&&xs.addBinding("branch",r.gitBranchName)}catch{}})();var Gx=mG();Gx.get("/",async(r,e)=>{let t=Ve(),n=ws();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Ui(xs,n,t);e.status(200).json(o)});var ph=Gx;import CG from"events";import eM,{Router as RG}from"express";import xG from"http";import MG from"path";var Fu=class{sessions=new Map;registerSession(e,t){this.sessions.set(e,t)}getSession(e){return this.sessions.get(e)}async removeSession(e,t){let n=this.sessions.get(e);if(n)try{await n.cleanup?.(),t.info({sessionId:e,emulatorName:n.emulatorName},"Android emulator cleaned up")}catch(o){t.error({err:o},"Error during Android session cleanup")}finally{this.sessions.delete(e)}}async removeAllSessions(e){let t=Array.from(this.sessions.keys());await Promise.all(t.map(n=>this.removeSession(n,e)))}};var Vx=new Fu;import{Router as gG}from"express";import{existsSync as hG}from"fs";import fG from"path";import{hostname as pG}from"os";var gh="0.9.2",vt=ai({app:"mobile-desktop-server",hostname:pG(),disableConsoleLogs:!0}).child({cliVersion:gh});(async()=>{try{let r=await Es(vt);r.gitBranchName&&vt.addBinding("branch",r.gitBranchName)}catch{}})();var hh=gG();hh.get("/",$e(async(r,e)=>{let t=ws();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));hh.post("/upload-url",$e(async(r,e)=>{let t;try{t=rb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ws();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=fG.resolve(t.filePath);if(!hG(o)){e.status(400).json({error:`File not found: ${o}`});return}await Pc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:vt}),e.sendStatus(204)}));var Wx=hh;import{Router as bG}from"express";import{Router as SG}from"express";import jx from"fs";import yG from"path";var Ms=SG();async function fh(r){return(await _x(r,vt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){C.warn(`Found a dangling mobile module with ID ${n.moduleId} that could not be found on disk.`);return}return{...o,content:n}}).filter(n=>n!==void 0)}Ms.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(n);e.status(200).json(o)}));Ms.get("/:moduleId",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await hr(Ve()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Yg(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));Ms.patch("/:moduleId/metadata",$e(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=nb.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ve(),o=await hr(n);xx({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));Ms.post("/",$e(async(r,e)=>{let t;try{t=ob.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{la(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ve(),i=(await hr(n)).mobileModules;if(Object.values(i).find(c=>c.name===t.name)){e.status(400).json({error:`A mobile module with the name "${t.name}" already exists. Please choose a different name.`});return}let a=yG.join(n.rootDir,t.folderPath??"");if(!jx.existsSync(a)||!jx.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await Mx({...t,folder:a,project:n});e.status(201).json(s)}));var $x=Ms;var qx=bG();qx.get("/",$e(async(r,e)=>{let t=Ve(),n=await hr(t),o=await fh(n),i=new Set;n?.tests&&Object.values(n.tests).forEach(l=>{l.labels?.forEach(u=>i.add(u))});let a=Array.from(i).sort(),s=Object.values(n.mobileTests),c={labels:a,modules:o,tests:s};e.status(200).json(c)}));var Kx=qx;import{Router as EG}from"express";var Sh=EG();Sh.get("/",$e((r,e)=>{let t=fx(Ve(),vt);e.status(200).json(t)}));Sh.get("/names",$e((r,e)=>{let n=Ve().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var Yx=Sh;import{Router as TG}from"express";var Xx=TG();Xx.get("/",(r,e)=>{e.status(200).json({userId:Uu(),orgId:ji(),cliVersion:gh??"0.0.0"})});var Jx=Xx;import{Router as vG}from"express";import yh from"path";var Bu=vG();Bu.patch("/:testPath",$e(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=tb.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}if(n.steps===void 0&&n.settings===void 0){e.status(400).json({error:"At least one of steps or settings is required"});return}let o=Ve(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await hr(o);await Ix({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a,schemaVersion:Zn});let s={message:"ok"};e.status(200).json(s)}));Bu.post("/",$e((r,e)=>{let t;try{t=eb.parse(r.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}let{name:n,description:o,settings:i,pathSegments:a}=t;if(!n||typeof n!="string"){e.status(400).json({error:"Missing or invalid 'name' in body"});return}try{la(n)}catch(p){e.status(400).json({error:p.message});return}let s=Ve(),c=yh.join(s.rootDir,...a),{fullPath:l,testId:u}=Px({name:n,description:o,steps:[],settings:i,folder:c}),d=yh.basename(l),m=yh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(g)}));Bu.get("/:fileName",$e(async(r,e)=>{let t=r.params.fileName;if(!t){e.status(400).json({error:"Missing fileName in path"});return}let n=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,o=Ve(),i=await hr(o),s=await _u(n,vt,i);e.status(200).json(s)}));var Qx=Bu;var zu=class extends zi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ve();return Ss(t,o,C)}};var tM="10mb";async function rM(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&Bx(n),await zx(t);let u=ji(),d=Uu(),m=r.logger.child({orgId:u,userId:d});Hx(i,w=>bs({configFilePath:w}));let g=eM();g.use(AG()),g.use(Zx.json({limit:tM})),g.use(Zx.urlencoded({extended:!1,limit:tM}));let p=RG();if(p.use("/folders",mh),p.use("/entities",Kx),p.use("/identify",Jx),p.use("/mobile-tests",Qx),p.use("/mobile-modules",$x),p.use("/assets",Wx),p.use("/git",ph),p.use("/environments",Yx),g.use("/api",p),g.use((w,N,G)=>{C.debug({url:w.url,path:w.path,query:w.query,method:w.method,body:w.body,headers:w.rawHeaders,client:w.ip},"Incoming request on mobile-desktop-server"),N.on("close",()=>{N.statusCode>=400&&(C.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"),vt.error({url:w.url,method:w.method,statusCode:N.statusCode},"Request completed in error on mobile-desktop-server"))}),G()}),g.use((w,N,G,W)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){G.status(400).send("Client disconnected");return}C.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),vt.error({stack:w.stack,msg:w.message,err:w,url:N.url,method:N.method},"Unhandled exception leading to 500 on mobile-desktop-server"),G.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=eM.static(o,{setHeaders:N=>{N.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(w),g.use("*",(N,G)=>{G.sendFile(MG.join(o,"index.html"))})}let h=xG.createServer(g),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),w()})}catch(N){N.message.includes("EADDRINUSE")?_G(e):C.error(`An unexpected error occurred while starting the server: ${N.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:uh(),apiKey:t,logger:m},x=new Rr(b),v=Ve(),A={...b,mode:"interactive"},{dispose:_}=gx({baseServer:h,logger:m,authorization:b,globalStateManager:Vx,getOrgId:()=>ji(),androidDriverFactory:async({socket:w,logger:N,creationOpts:G})=>{let W=Math.floor(Math.random()*1e4)+4e4,ye=await Dl(W,"appium");return _c({logger:N,driverLogLevel:a,apiClient:x,creationOpts:G,socket:w,appiumPort:ye,sessionId:w.id,orgId:ji(),onStatusUpdate:Se=>{w.emit("connectionStatusUpdate",{message:Se})}})},mobileGeneratorFactory:async w=>new Vi({baseUrl:uh(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async w=>new Io(v.config.ai?.agentConfig,A),browserEnricherFactory:async w=>new Bi(A,new Io(v.config.ai?.agentConfig,A)),storageFactory:async w=>new zu(x,w),cacheStorageFactory:async w=>{let N=await Ui(m,x,v);return Lu({orgId:w,client:x,gitMetadata:N,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Gi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:v.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await Et.flush()}catch(w){C.error({err:w},"Error during session dispose on SIGUSR2")}try{h.close(()=>{process.kill(process.pid,"SIGUSR2")})}catch{process.kill(process.pid,"SIGUSR2")}}),process.once("SIGTERM",async()=>{C.info("SIGTERM in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{C.info("SIGINT in Momentic mobile app received");try{await _(),await Et.flush()}finally{h.close(()=>process.exit(0))}})}CG.setMaxListeners(25);process.on("warning",r=>{vt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{vt.error({err:r},"Uncaught exception on mobile-desktop-server"),C.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{vt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),C.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function _G(r){C.error(wG`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4282
4282
|
Using Bash on MacOS or Linux:
|
|
4283
4283
|
lsof -t -i :58888 | xargs kill -9
|
|
4284
4284
|
|
|
4285
4285
|
Using Command Prompt on Windows:
|
|
4286
4286
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
4287
|
-
`)}import
|
|
4287
|
+
`)}import KG from"open";import ju from"path";import{fileURLToPath as YG}from"url";import{InvalidArgumentError as bh,Option as ut}from"@commander-js/extra-typings";import{z as PG}from"zod";var nM=58890;function oM(r){let e=parseInt(r,10);if(isNaN(e))throw new bh("Not a number.");return e}var _s=new ut("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new bh("API key is required.");return r}).makeOptionMandatory(),Eh=new ut("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Ps=new ut("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return PG.string().url().parse(r),r}catch{throw new bh("Not a valid URL.")}}),Th=new ut("-y, --yes","Skip all confirmation prompts.").env("CI"),vh=new ut("--regenerate-cache","Regenerate all caches by starting from an empty cache state. This flag is useful for completely regenerating caches after changing configuration options. Warning: using this option will cause all steps to run without any cached data, resulting in significantly longer execution times.").implies({disableCache:!1,saveCache:!0}),Ah=new ut("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI").implies({disableCache:!1}),wh=new ut("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes.").implies({saveCache:!1,regenerateCache:!1}),Ch=new ut("--tag <tag>","Tag identifier for the asset."),iM=new ut("--channel <channel>","Channel name for the asset."),aM=new ut("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),sM=new ut("--env <env>","Environment to run all tests in (overrides test-level configuration)."),lM=new ut("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),cM=new ut("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),uM=new ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(oM),Rh=new ut("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),dM=new ut("--upload-results","Upload test results to Momentic Cloud.").default(!1),xh=new ut("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),mM=new ut("--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}),pM=new ut("--timeout-minutes <timeoutMinutes>","Maximum number of minutes to run tests before stopping. When the timeout is reached, tests will stop and current results will be printed.").argParser(oM);import{randomUUID as GG}from"crypto";import{existsSync as VG}from"fs";import Mh from"fs";import Hu from"path";import{cwd as OG}from"process";async function gM({tests:r,momenticFiles:e,project:t,yes:n,include:o,exclude:i,logger:a,quarantinedTestReasons:s}){let c=new Set;if(r&&r.length>0){let u=r.some(m=>Mh.existsSync(m)),d=OG();u?(d!==t.rootDir&&a.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.`),a.info(`Reading tests from the following local file paths:
|
|
4288
4288
|
- ${r.join(`
|
|
4289
4289
|
- `)}
|
|
4290
|
-
`),r.forEach(m=>{if(!Mh.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let g,p;try{g=Mh.statSync(m),p=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=Hu.resolve(m);Object.values(e.mobileTests).filter(f=>p?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(m=>{r.some(g=>m.relativePath.includes(g))&&c.add(m.fullFilePath)}))}else{!n&&!await Ol("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1));let u=Object.values(e.mobileTests);a.info(`Reading all ${u.length} mobile tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of Array.from(c)){let d=Hu.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Hu.relative(t.rootDir,u),m=await _u(u,a,e),g=Hu.basename(u,".test.yaml");return{id:m.id,name:g,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as
|
|
4290
|
+
`),r.forEach(m=>{if(!Mh.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let g,p;try{g=Mh.statSync(m),p=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=Hu.resolve(m);Object.values(e.mobileTests).filter(f=>p?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(a.info("The arguments provided don't appear to be valid paths. Treating them as substrings instead... "),Object.values(e.mobileTests).forEach(m=>{r.some(g=>m.relativePath.includes(g))&&c.add(m.fullFilePath)}))}else{!n&&!await Ol("No test paths or substrings were provided. Do you want to run all tests?")&&(a.error("Cancelled by user."),process.exit(1));let u=Object.values(e.mobileTests);a.info(`Reading all ${u.length} mobile tests in the project from local disk.`),u.forEach(d=>{c.add(d.fullFilePath)})}for(let u of Array.from(c)){let d=Hu.relative(t.rootDir,u);o&&!o.some(m=>new RegExp(m).test(d))&&c.delete(u),i&&i.some(m=>new RegExp(m).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=Hu.relative(t.rootDir,u),m=await _u(u,a,e),g=Hu.basename(u,".test.yaml");return{id:m.id,name:g,description:m.description,schemaVersion:m.schemaVersion,settings:m.settings,steps:m.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[m.id],quarantinedReason:s[m.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as LG}from"crypto";import{existsSync as NG,statSync as DG}from"fs";import{cloneDeep as kG}from"lodash-es";import UG from"path";async function hM(r){let{inputs:e,fixtures:t,metadata:n,options:o}=r,{tracer:i,logger:a}=t,{runId:s}=n,{testDefinition:c,runSigIntHandlers:l,project:u}=e,d=new Date,m=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:kG(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(m.loggerBindings||{}),p=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<p;h++){let f=new Date,E=await FG({runTracer:m,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:p},fixtures:{...t,logger:g},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason};if(h!==p-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await m.finish({logger:a,...E,finishedAt:b}),{...E,startedAt:d,lastAttemptStartedAt:f,finishedAt:b,runId:s,attempts:h+1,testMetadata:c,steps:c.steps,filePath:c.relativeFilePath,quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}}throw new Error("This code should not be reachable")}finally{l?.pop()}}async function FG(r){let{runTracer:e,testDefinition:t,metadata:n,constants:o,fixtures:i,inputs:a,options:s}=r,{attemptNumber:c,totalAttempts:l}=o,{orgId:u,gitMetadata:d}=n,{apiClient:m,logger:g,usageTracker:p}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:x}=a,{regenerateCache:v,alwaysSaveCache:A,noCache:_,logLevel:w,localAvdId:N,localApkPath:G}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let W={...a.project.config.emulator,...t.settings?.emulator},ye=G?UG.resolve(G):void 0;if(ye&&(!NG(ye)||!DG(ye).isFile()))throw new Error(`Local APK path "${ye}" does not exist. Provide a valid file path via --local-apk-path.`);let Se=Lu({orgId:u,client:m,gitMetadata:d,regenerateCache:v??!1,alwaysSaveCache:A??!1,noCache:_??!1}),Ae=new zi(m,u),K={type:"API_KEY",baseUrl:m.baseUrl,apiKey:m.apiKey,logger:g,mode:"runner"},j=new Vi(K),le=new Io(b.config.ai?.agentConfig,K),Q=new Bi(K,le),Xe=new Gi({httpClient:m,fakerSeed:void 0}),De=Math.floor(Math.random()*1e4)+4e4,Bt=await Dl(De,"appium"),Wt=W.region==="local"?ye??t.settings?.defaultApkFilePath?.trim():void 0,ke=f&&!Wt?{channel:f,tag:E}:void 0,Pe;if(N||W.region==="local"){if(!W.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is set to local. Provide --local-avd-id or configure a default local emulator AVD.");Pe={avdId:N??W.localEmulatorSettings?.avdId,apkToInstall:ke,apkFilePath:Wt}}else Pe={region:W.region,apkToInstall:ke,osVersion:W.remoteEmulatorSettings?.androidVersion??Iy};let _t=LG(),dt=await _c({apiClient:m,logger:g,driverLogLevel:w,creationOpts:Pe,onStatusUpdate:Os=>{g.debug({status:Os},"Limbar emulator status update")},appiumPort:Bt,orgId:u,sessionId:_t}),qr=await e.startAttempt({emulatorName:dt.emulatorName,runAttemptId:_t}),Oo=g.child(qr.loggerBindings||{}),$u=await Ic({driver:dt.driver,onLogs:Os=>{qr.appendLogs(Os)}}),cn=x||t.settings?.defaultEnv,Nh;cn&&(Nh=Ss(cn,b,Oo).variables);let bM=new ei({variablesFromEnvironment:Nh??{},envName:cn,testName:t.name}),Dh=await Ni.init({driver:dt.driver,generator:j,logger:Oo,limbarClient:dt.limbarClient,playwrightDevice:dt.playwrightDevice,orgId:u,adbPort:dt.adbPort,options:{emulator:W},fixtures:{storage:Ae,browserEnricher:Q,browserGenerator:le,localCodeEvalTools:Xe,testContext:bM}}),$;try{$=await wu({containerName:`mobile test ${t.name}`,fixtures:{controller:Dh,logger:Oo,cacheStorage:Se,usageTracker:p},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:qr,callbacks:{}})}finally{await $u(),await dt.cleanup(),await Dh.cleanup()}return await qr.finish({logger:Oo,results:$.results,status:$.status}),$}import{debounce as BG}from"ts-debounce";var Is="0.9.2";var Gu="assets";function zG(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 _h=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new Co,an.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Gu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Gu}/${t}.jpeg`,contents:n})}async finishInternal(e){this.finished||(this.finished=!0,this.interactionTracer.finish(),await Promise.all(this.children.map(t=>t.finish({status:HG(e.status),finishedAt:e.finishedAt}))))}async finish(e){return await this.finishInternal({status:e.result.status,finishedAt:new Date(e.result.endTime)}),{trace:this.interactionTracer.getRootSpan()}}async startSubSteps(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},$i=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o}children=[];finished=!1;async getScreenshot(e,t){return this.diskStorage.readFile(`${Gu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new _h(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(t),t}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(t=>t.finishInternal({status:zG(e.status),finishedAt:e.finishedAt}))))}},Ph=class{constructor(e,t,n,o,i,a){this.keepalive=e;this.testId=t;this.testName=n;this.runAttemptId=o;this.metadata=i;this.diskStorage=a;this.diskStorage.mkdir("assets"),this.logStream=this.diskStorage.createFileStream("assets/logs.logcat")}finished=!1;children=[];logStream;get loggerBindings(){return{runAttemptId:this.runAttemptId}}appendLogs(e){let t=e.join(`
|
|
4291
4291
|
`);this.logStream.write(t+`
|
|
4292
|
-
`)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,finishedAt:new Date,results:uu(o,t),beforeResults:i?uu(i,t):void 0,afterResults:a?uu(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Gu}/${t}.jpeg`)}},Ih=class{constructor(e,t,n,o,i,a){this.client=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}}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,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){let{runAttemptId:t}=e;this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let n=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),o={id:t,schemaVersion:yn,runAttemptSchemaVersion:tE,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=
|
|
4293
|
-
${Pe.stack}`;C.error(_t),Wt.error({err:Pe},`Encountered unexpected fatal error when running test ${Q.name}`)}finally{clearInterval(De),W[le].done=!0,delete W[le]}await ke.flush(s)})({testDefinition:j})}}await Promise.allSettled(Object.values(W).map(Ae=>Ae.promise)),G&&clearTimeout(G);let Se=b.some(Ae=>Ae.status==="FAILED"&&!Ae.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:Se}),process.off("SIGINT",N),A()}async function
|
|
4294
|
-
`),C.info("This wizard will help you bootstrap a new Momentic project."),Wu.existsSync(ki)&&(C.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 iE("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Gg};vx(t,ki),C.success(`Initialized Momentic project file at ${ju.resolve(ki)}`)});jn.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: ${Mm.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(C.error("No browsers specified"),process.exit(1)),await Nl({rawBrowsers:r,force:e.force,all:e.all})});async function
|
|
4292
|
+
`)}async finish(e){if(this.finished)return;this.finished=!0;let{logger:t,status:n,results:o,beforeResults:i,afterResults:a}=e,s={...this.metadata,status:n,finishedAt:new Date,results:uu(o,t),beforeResults:i?uu(i,t):void 0,afterResults:a?uu(a,t):void 0};await Promise.all(this.children.map(c=>c.finish({status:s.status,finishedAt:s.finishedAt})));try{this.logStream.end()}catch{}this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)})}async startBeforeStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new $i(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Gu}/${t}.jpeg`)}},Ih=class{constructor(e,t,n,o,i,a){this.client=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}}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,status:t.status,results:[],beforeResults:[],afterResults:[]}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(t,null,2)}),this.diskStorage.close()}async startAttempt(e){let{runAttemptId:t}=e;this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let n=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),o={id:t,schemaVersion:yn,runAttemptSchemaVersion:tE,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=BG(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new Ph(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},Vu=class r{constructor(e,t,n,o,i){this.orgId=e;this.runGroupId=t;this.metadata=n;this.client=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start({orgId:e,runGroupId:t,outputDir:n,client:o,gitMetadata:i,labels:a}){let s={...i,id:t,trigger:rr.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Is,labels:a??[]},c=new As(n);return c.storeFile({name:"metadata.json",contents:JSON.stringify(s,null,2)}),new r(e,t,s,o,c)}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",environmentName:e.environmentName,cliVersion:Is,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined,quarantinedReason:e.quarantinedReason,executionType:"ANDROID"};t.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)});let o=new Ih(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function fM(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 ln(){try{await k(Promise.all([uE(),Et.flush()]),{milliseconds:5e3})}catch{}}async function SM(r){let{options:e,fixtures:t,inputs:n,metadata:o}=r,{project:i,apiClient:a,logger:s}=t,{orgId:c,runGroupId:l,gitMetadata:u}=o,{outputDir:d,parallel:m}=e;VG(d)&&C.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await fM(s,a,e.ignoreQuarantine),p=await hr(i),h=await gM({tests:n.tests,yes:e.yes,project:i,momenticFiles:p,logger:C,quarantinedTestReasons:g}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await Vu.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],x=new Date,v=new Set,A=async()=>WG({runResults:b,startTime:x,ranTests:v,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),_=[],w=async Ae=>{C.warn(`${Ae} Stopping tests and printing latest results.`),await E.finish({logger:f,status:"CANCELLED"}),await A(),await Promise.allSettled(_.map(K=>K())),await ln(),process.exit(1)},N=async()=>{await w("SIGINT received.")};process.once("SIGINT",N);let G;if(e.timeoutMinutes!==void 0&&e.timeoutMinutes>0){let Ae=e.timeoutMinutes*60*1e3;G=setTimeout(()=>{w(`Timeout of ${e.timeoutMinutes} minute(s) reached.`)},Ae)}let W={};for(let Ae=0;Ae<h.length;Ae++){let K=Object.values(W);K.length===m&&await Promise.race(K.map(Q=>Q.promise));let j=h[Ae],le=`test-${Ae}`;W[le]={done:!1,promise:(async({testDefinition:Q})=>{v.add(le);let Xe=Q.relativeFilePath.includes("..")?Q.fullFilePath:Q.relativeFilePath;La({status:"START",testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length});let De=setInterval(()=>La({status:"RUN",testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length}),5*60*1e3),Bt=GG(),Wt=f.child({testId:Q.id,runId:Bt}),ke=new Gc({logger:Wt,reporter:new Iu(a),runType:"mobile-test-run",runId:Bt,testMetadata:Q,suiteMetadata:void 0});try{let Pe=await hM({metadata:{...o,runId:Bt},fixtures:{...t,tracer:E,logger:Wt,usageTracker:ke},inputs:{...n,project:i,testDefinition:Q,channel:n.channel??Q.settings?.defaultChannel,tag:n.tag??Q.settings?.defaultTag,logUpdate:(_t,dt)=>La({status:_t,testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length,additionalText:dt}),runSigIntHandlers:_},options:e});La({status:Pe.status,testLogRef:Xe,getRunningTestsCount:()=>v.size,getTotalTestsCount:()=>h.length}),b.push(Pe)}catch(Pe){let _t=`Encountered unexpected fatal error when running test '${Q.name}': ${Pe.message}
|
|
4293
|
+
${Pe.stack}`;C.error(_t),Wt.error({err:Pe},`Encountered unexpected fatal error when running test ${Q.name}`)}finally{clearInterval(De),W[le].done=!0,delete W[le]}await ke.flush(s)})({testDefinition:j})}}await Promise.allSettled(Object.values(W).map(Ae=>Ae.promise)),G&&clearTimeout(G);let Se=b.some(Ae=>Ae.status==="FAILED"&&!Ae.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:Se}),process.off("SIGINT",N),A()}async function WG({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=dE({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${Cm}- ${c.filePath}`;return c.runId&&(l+=` ( link when uploaded: ${a}/runs/${c.runId} )`),l},entity:"mobile test"});return C.log(""),o?(C.success(`Test results have been saved to the folder ${i}. Uploading to Momentic Cloud...`),await Du({client:n,consoleLogger:C,resultsPath:i})):C.success(`Test results have been saved to the folder ${i}. Upload them to Momentic Cloud by running 'npx momentic-mobile results upload ${i}'.`),s}async function Oh(){PA(),hE("Chromium")||(lo?(await Ol("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Nl({rawBrowsers:["chromium"],force:!1,all:!1})):(C.error("The Chromium browser is not installed but is required for automating webviews. Please install it using 'momentic-mobile install-browsers chromium'"),process.exit(1)))}vA({serviceName:"mobile-cli"});ar.setApp("mobile-cli");var jn=new jG;jn.name("momentic-mobile").description("Momentic Mobile CLI").version(Is);var XG=jn.command("assets").description("Manage mobile testing assets");XG.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(_s).addOption(Ps).addOption(Ch).addOption(aM).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=ju.resolve(r);Wu.existsSync(a)||(C.error(`File not found: ${a}`),process.exit(1));let s=new Rr({baseUrl:n,apiKey:t,logger:C});/\.apk$/i.test(a)||(C.error(`File is not an APK file: ${a}`),process.exit(1)),await Pc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:C})});jn.command("app").addOption(_s).addOption(Ps).addOption(Th).addOption(Eh).addOption(xh).addOption(vh).addOption(Ah).addOption(wh).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=xm(r.logLevel);ar.setApp("mobile-desktop-server");let c=new Rr({baseUrl:t,apiKey:e,logger:ar});await rh({client:c,skipPrompts:n}),C.debug("API key check complete");let l=YG(import.meta.url),u=ju.dirname(l),d=ju.resolve(u,"..","static");await Oh(),C.debug({appiumHome:os},"Resolved resource paths");let m=await bs({configFilePath:r.config}),g=nM;await rM({momenticServerUrl:t,serverPort:g,apiKey:e,staticDir:d,initialProject:m,driverLogLevel:s,logger:ar,regenerateCache:a,noCache:o,alwaysSaveCache:i});let p=`http://localhost:${g}`;C.info(`Local app started on: ${p}`),await KG(p)});var yM=jn.command("results").description("Merge and upload test results.");yM.command("merge").description("Merge test results files.").addOption(Rh).addArgument(new Lh("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired()).action(async(r,e)=>{let{outputDir:t}=e;t||(C.error("Output directory is required."),process.exit(1)),Wu.existsSync(r)||(C.warn("Results path does not exist, skipping merge."),process.exit(0)),Wu.existsSync(t)&&C.warn(`Output directory ${t} already exists, removing before merging...`),Dx(ar,t,r),await ln(),process.exit(0)});var JG=new Lh("<results>","Path to the results archive.").argRequired();yM.command("upload").description("Upload test results to Momentic cloud.").addOption(_s).addOption(Ps).addArgument(JG).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=ar,i=new Rr({baseUrl:n,apiKey:t,logger:o});await Du({consoleLogger:C,resultsPath:r,client:i}),await ln(),process.exit(0)});var QG=jn.command("run").alias("test").description("Run tests on the local machine");QG.addOption(_s).addOption(Ps).addOption(Eh).addOption(Th).addOption(uM).addOption(xh).addOption(vh).addOption(Ah).addOption(wh).addOption(Rh).addOption(dM).addOption(mM).addOption(pM).addOption(Ch).addOption(iM).addOption(sM).addOption(lM).addOption(cM).addArgument(new Lh("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional()).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i,outputDir:a}=e,s=xm(e.logLevel);await Oh(),C.debug({appiumHome:os},"Resolved resource paths");let c=await bs({configFilePath:e.config}),l=a??c.config.outputDir??Ax,u=e.parallel??c.config.parallel??1;C.debug("Checking API key and dependencies");let d=new Rr({baseUrl:n,apiKey:t,logger:C}),{orgId:m,userId:g}=await rh({client:d,skipPrompts:e.yes});C.debug("API key check and browser installation complete");let p=qG(),h=ar.child({runGroupId:p,orgId:m,userId:g}),f=await Ui(ar,d,c);h.debug(f,"Got local git metadata");try{let E=await SM({options:{...e,parallel:u,outputDir:l,alwaysSaveCache:e.saveCache,noCache:e.disableCache,logLevel:s,timeoutMinutes:e.timeoutMinutes},fixtures:{logger:h,project:c,apiClient:d},inputs:{envOverride:e.env,tag:o,channel:i,tests:r},metadata:{gitMetadata:f,runGroupId:p,orgId:m}});await ln(),E.failed>0?process.exit(1):process.exit(0)}catch(E){C.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),C.error(E),ar.error({err:E},"Failed to run tests locally"),await ln(),process.exit(1)}});jn.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new $G("--name <name>","Name of the project")).action(async r=>{C.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|
|
4294
|
+
`),C.info("This wizard will help you bootstrap a new Momentic project."),Wu.existsSync(ki)&&(C.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 iE("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Gg};vx(t,ki),C.success(`Initialized Momentic project file at ${ju.resolve(ki)}`)});jn.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: ${Mm.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(C.error("No browsers specified"),process.exit(1)),await Nl({rawBrowsers:r,force:e.force,all:e.all})});async function ZG(){try{await jn.parseAsync(process.argv),await ln()}catch(r){ar.error({err:r},"Uncaught error in CLI"),C.error(r),await ln(),process.exit(1)}}ZG();
|
|
4295
4295
|
//# sourceMappingURL=cli.js.map
|