momentic-mobile 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Cx=Object.defineProperty;var He=(r,e)=>()=>(r&&(e=r(r=0)),e);var xx=(r,e)=>{for(var t in e)Cx(r,t,{get:e[t],enumerable:!0})};var kb,Ub=He(()=>{"use strict";kb=typeof globalThis=="object"?globalThis:global});var Fb=He(()=>{"use strict";Ub()});var Bb=He(()=>{"use strict";Fb()});var Xr,ym=He(()=>{"use strict";Xr="1.9.0"});function ML(r){var e=new Set([r]),t=new Set,n=r.match(zb);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(zb);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 zb,Hb,Gb=He(()=>{"use strict";ym();zb=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Hb=ML(Xr)});function Xo(r,e,t,n){var o;n===void 0&&(n=!1);var i=Ma[xa]=(o=Ma[xa])!==null&&o!==void 0?o:{version:Xr};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!==Xr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Xr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Xr+"."),!0}function Jr(r){var e,t,n=(e=Ma[xa])===null||e===void 0?void 0:e.version;if(!(!n||!Hb(n)))return(t=Ma[xa])===null||t===void 0?void 0:t[r]}function Jo(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Xr+".");var t=Ma[xa];t&&delete t[r]}var _L,xa,Ma,_a=He(()=>{"use strict";Bb();ym();Gb();_L=Xr.split(".")[0],xa=Symbol.for("opentelemetry.js.api."+_L),Ma=kb});function Pa(r,e,t){var n=Jr("diag");if(n)return t.unshift(e),n[r].apply(n,IL([],PL(t),!1))}var PL,IL,Vb,Wb=He(()=>{"use strict";_a();PL=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},IL=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))},Vb=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 Pa("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("verbose",this._namespace,e)},r}()});var Ne,Il=He(()=>{"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"})(Ne||(Ne={}))});function jb(r,e){r<Ne.NONE?r=Ne.NONE:r>Ne.ALL&&(r=Ne.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",Ne.ERROR),warn:t("warn",Ne.WARN),info:t("info",Ne.INFO),debug:t("debug",Ne.DEBUG),verbose:t("verbose",Ne.VERBOSE)}}var $b=He(()=>{"use strict";Il()});var OL,LL,NL,Lr,Ia=He(()=>{"use strict";Wb();$b();Il();_a();OL=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},LL=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))},NL="diag",Lr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Jr("diag");if(s)return s[o].apply(s,LL([],OL(i),!1))}}var t=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:Ne.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=Jr("diag"),d=jb((s=i.logLevel)!==null&&s!==void 0?s:Ne.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 Xo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){Jo(NL,t)},t.createComponentLogger=function(o){return new Vb(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 qb,Kb=He(()=>{"use strict";qb=Symbol("BaggageEntryMetadata")});function bm(r){return typeof r!="string"&&(DL.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:qb,toString:function(){return r}}}var DL,Yb=He(()=>{"use strict";Ia();Kb();DL=Lr.instance()});function Em(r){return Symbol.for(r)}var kL,Tm,vm=He(()=>{"use strict";kL=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}(),Tm=new kL});function Rm(){return wm}var Qn,UL,Ol,FL,BL,zL,HL,Am,GL,VL,WL,wm,jL,$L,qL,KL,YL,XL,JL,Cm=He(()=>{"use strict";Qn=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)}}(),UL=function(){function r(){}return r.prototype.createGauge=function(e,t){return $L},r.prototype.createHistogram=function(e,t){return qL},r.prototype.createCounter=function(e,t){return jL},r.prototype.createUpDownCounter=function(e,t){return KL},r.prototype.createObservableGauge=function(e,t){return XL},r.prototype.createObservableCounter=function(e,t){return YL},r.prototype.createObservableUpDownCounter=function(e,t){return JL},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Ol=function(){function r(){}return r}(),FL=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ol),BL=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ol),zL=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ol),HL=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ol),Am=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),GL=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Am),VL=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Am),WL=function(r){Qn(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Am),wm=new UL,jL=new FL,$L=new zL,qL=new HL,KL=new BL,YL=new GL,XL=new VL,JL=new WL});var Gt,Xb=He(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Gt||(Gt={}))});var ZL,QL,Jb,Zb=He(()=>{"use strict";vm();ZL=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},QL=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))},Jb=function(){function r(){}return r.prototype.active=function(){return Tm},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,QL([n],ZL(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var eN,tN,xm,rN,Qb,eE=He(()=>{"use strict";Zb();_a();Ia();eN=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},tN=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))},xm="context",rN=new Jb,Qb=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Xo(xm,e,Lr.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,tN([e,t,n],eN(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Jr(xm)||rN},r.prototype.disable=function(){this._getContextManager().disable(),Jo(xm,Lr.instance())},r}()});var Zo,tE=He(()=>{"use strict";eE();Zo=Qb.getInstance()});var H,rE=He(()=>{"use strict";Ia();H=Lr.instance()});var nN,nE,oE=He(()=>{"use strict";Cm();nN=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return wm},r}(),nE=new nN});var Mm,iE,aE=He(()=>{"use strict";oE();_a();Ia();Mm="metrics",iE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Xo(Mm,e,Lr.instance())},r.prototype.getMeterProvider=function(){return Jr(Mm)||nE},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){Jo(Mm,Lr.instance())},r}()});var Ll,sE=He(()=>{"use strict";aE();Ll=iE.getInstance()});var _e=He(()=>{"use strict";Yb();vm();Il();Cm();Xb();tE();rE();sE()});import{Argument as gh,Command as KH,Option as YH}from"@commander-js/extra-typings";import Kk from"appium";import{execSync as Yk}from"child_process";import{z as Du}from"zod";var iG=Du.object({input:Du.string(),agentConfigVersion:Du.string().optional()});import{z as nt}from"zod";var lG=nt.object({srcs:nt.array(nt.string()),urls:nt.array(nt.string()),desiredSrc:nt.string().optional(),desiredUrl:nt.string().optional()}),Sh=nt.object({srcRegex:nt.string().optional(),urlRegex:nt.string().optional()}),yh=nt.object({x:nt.number(),y:nt.number(),correlation:nt.number()}),cG=nt.object({searchImageBase64String:nt.string(),pageImageBase64String:nt.string(),id:nt.string().uuid(),timeoutMs:nt.number().max(1e4).min(0).optional()});import{z as P}from"zod";import*as L from"zod";import{extendZodWithOpenApi as Mx}from"zod-openapi";Mx(L);var nn=(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))(nn||{}),_x=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(),Rs=L.object({type:L.literal("GCS_TRACES"),traces:ku}),rn=(o=>(o.Precise="precise",o.Narrow="narrow",o.Unspecific="broad",o.Irrelevant="irrelevant",o))(rn||{}),bh=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(rn)}).optional(),shape:L.object({width:L.number(),height:L.number(),tolerance:L.nativeEnum(rn)}).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),Px=L.object({selectors:L.string().array(),requirements:bh.optional()}),on=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:bh.optional(),additionalElements:Px.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:_x.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(nn).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:Rs.optional()}).openapi({ref:"ElementTargetCache"});function Cs(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var Ix=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),Ox=L.object({x:L.number(),y:L.number()}),Lx=L.object({type:L.literal("coordinates"),pixels:Ox}).openapi({ref:"CoordinatesTarget"});function an(r){return r.type==="description"}function Ar(r){return r.type==="coordinates"}var Et=L.discriminatedUnion("type",[Ix,Lx]).openapi({ref:"ElementTarget"});function Uu(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Eh(r){return Rs.safeParse(r).success}import{v4 as be}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as Hx}from"zod-openapi";import{z as te}from"zod";import{extendZodWithOpenApi as Nx}from"zod-openapi";import{z as Fi}from"zod";import Th from"zod";var Ui=Th.object({updatedAt:Th.coerce.date().optional()});var Fu=Fi.object({result:Fi.boolean(),traceId:Fi.string()}).array(),Bu=Fi.object({type:Fi.literal("GCS_TRACES"),traces:Fu}),zu=Ui.extend({memory:Bu.optional()});Nx(te);var vh=te.object({plan:te.string().optional(),evidence:te.string().optional(),thoughts:te.string(),result:te.boolean(),relevantElements:te.array(te.number()).optional(),updatedMemory:Fu.optional()}),Wr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Wr||{});var Dx=te.object({type:te.literal("ELEMENT_NAME"),negated:te.boolean().optional(),operation:te.nativeEnum(Wr),value:te.string()}).openapi({ref:"ElementNameAssertion"}),kx=te.object({type:te.literal("ELEMENT_STYLE"),negated:te.boolean().optional(),operation:te.nativeEnum(Wr),property:te.string(),value:te.string()}).openapi({ref:"ElementStyleAssertion"}),Ux=te.object({type:te.literal("ELEMENT_CONTENT"),negated:te.boolean().optional(),operation:te.nativeEnum(Wr),value:te.string()}).openapi({ref:"ElementContentAssertion"}),Fx=te.object({type:te.literal("ELEMENT_ATTRIBUTE"),negated:te.boolean().optional(),operation:te.nativeEnum(Wr),attr:te.string(),value:te.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Fn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Fn||{}),Bx=te.object({type:te.literal("ELEMENT_EXISTENCE"),negated:te.boolean().optional(),condition:te.nativeEnum(Fn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Ah=te.discriminatedUnion("type",[Ux,Fx,Bx,Dx,kx]).openapi({ref:"ManualElementAssertion"});var zx=te.object({type:te.literal("CONTENT"),negated:te.boolean().optional(),value:te.string()}).openapi({ref:"PageContentAssertion"}),wh=te.discriminatedUnion("type",[zx]).openapi({ref:"ManualPageAssertion"});import Mt from"zod";var Hu=Mt.discriminatedUnion("type",[Mt.object({type:Mt.literal("SUBSTRING"),url:Mt.string()}),Mt.object({type:Mt.literal("GLOB"),glob:Mt.string()}),Mt.object({type:Mt.literal("REGEX"),regex:Mt.string()}),Mt.object({type:Mt.literal("DOMAIN"),domain:Mt.string()})]),Bi=Mt.object({urlMatcher:Hu,method:Mt.string().optional()});import{z as ye}from"zod";var vo=ye.object({url:ye.string(),method:ye.union([ye.literal("GET"),ye.literal("POST"),ye.literal("PUT"),ye.literal("DELETE"),ye.literal("PATCH")]),headers:ye.record(ye.string(),ye.string()).optional(),params:ye.record(ye.string(),ye.string()).optional(),body:ye.string().optional(),timeout:ye.number().int().optional().describe("Max seconds to wait for the request to complete")}),Rh=ye.object({url:ye.string(),headers:ye.record(ye.string(),ye.string()).optional(),query:ye.string(),variables:ye.string().optional(),timeout:ye.number().int().optional().describe("Max seconds to wait for the request to complete")}),xs=ye.object({code:ye.string(),fragment:ye.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:ye.union([ye.literal("NODE"),ye.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:ye.number().int().max(60).optional().describe("Max seconds for the code to complete")});var ot=(W=>(W.AI_EXTRACT="AI_EXTRACT",W.AI_ASSERTION="AI_ASSERTION",W.AUTH_LOAD="AUTH_LOAD",W.AUTH_SAVE="AUTH_SAVE",W.BLUR="BLUR",W.CAPTCHA="CAPTCHA",W.CLICK="CLICK",W.COOKIE="COOKIE",W.COPY="COPY",W.DIALOG="DIALOG",W.DRAG="DRAG",W.ELEMENT_CHECK="ELEMENT_CHECK",W.FILE_UPLOAD="FILE_UPLOAD",W.FOCUS="FOCUS",W.GO_BACK="GO_BACK",W.GO_FORWARD="GO_FORWARD",W.HOVER="HOVER",W.JAVASCRIPT="JAVASCRIPT",W.LOCAL_STORAGE="LOCAL_STORAGE",W.MOUSE_DRAG="MOUSE_DRAG",W.NAVIGATE="NAVIGATE",W.NEW_TAB="NEW_TAB",W.PAGE_CHECK="PAGE_CHECK",W.PASTE="PASTE",W.PRESS="PRESS",W.KEY_DOWN="KEY_DOWN",W.KEY_UP="KEY_UP",W.REFRESH="REFRESH",W.REQUEST="REQUEST",W.GRAPHQL_REQUEST="GRAPHQL_REQUEST",W.SCROLL_DOWN="SCROLL_DOWN",W.SCROLL_UP="SCROLL_UP",W.SCROLL_LEFT="SCROLL_LEFT",W.SCROLL_RIGHT="SCROLL_RIGHT",W.SELECT_OPTION="SELECT_OPTION",W.SWITCH_TAB="TAB",W.TYPE="TYPE",W.VISUAL_DIFF="VISUAL_DIFF",W.WAIT="WAIT",W.WAIT_FOR_URL="WAIT_FOR_URL",W.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",W.AWAIT_LISTENER="AWAIT_LISTENER",W.RECORD_REQUESTS="RECORD_REQUESTS",W.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",W.SET_HEADER="SET_HEADER",W.MOCK_ROUTE="MOCK_ROUTE",W.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",W.OFFLINE_MODE="OFFLINE_MODE",W.SUCCESS="SUCCESS",W))(ot||{});Hx(y);var K=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),jt=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"}),$t=Ui.extend({target:on}).optional().openapi({ref:"SingleTargetCache"});function Ch(r){return $t.safeParse(r).success}var Ms=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),Gx=K.merge(Ms).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),_s=jt.merge(y.object({cache:$t})),Ao=K.merge(_s.merge(y.object({target:Et.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),wo=K.merge(_s.merge(y.object({target:Et.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Ro=K.merge(_s.merge(y.object({target:Et.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Co=K.merge(_s.merge(y.object({target:Et.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),HG=y.discriminatedUnion("type",[Ao,wo,Ro,Co]).openapi({ref:"AllScrollCommands"}),Vx=K.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Wx=K.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),jx=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")}),xh=K.extend({type:y.literal("WAIT_FOR_URL"),matcher:Hu}).merge(jx).openapi({ref:"WaitUrlCommand"}),Mh=K.merge(Ms).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),$x=K.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),_h=K.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),qx=K.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Kx=K.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"}),Vu=K.merge(jt).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Ph=K.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),Ih=K.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),Oh=K.merge(xs).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Hi=K.merge(jt).extend({type:y.literal("CLICK"),target:Et,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:$t,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),Lh=Ui.extend({fromTarget:on.optional(),toTarget:on.optional()}),xo=K.merge(jt).merge(y.object({type:y.literal("DRAG"),fromTarget:Et,toTarget:Et,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:Lh.optional()})).openapi({ref:"DragCommand"}),Mo=K.merge(jt).merge(y.object({type:y.literal("MOUSE_DRAG"),target:Et.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:$t})).openapi({ref:"MouseDragCommand"}),Gi=K.merge(jt).merge(y.object({type:y.literal("HOVER"),target:Et,cache:$t})).openapi({ref:"HoverCommand"}),Vi=K.merge(jt).merge(y.object({type:y.literal("FOCUS"),target:Et,cache:$t})).openapi({ref:"FocusCommand"}),Wi=K.merge(jt).extend({type:y.literal("BLUR"),target:Et.optional(),cache:$t}).openapi({ref:"BlurCommand"}),Yx=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Xx=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Jx=K.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[Yx,Xx]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),Nh=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()})]),ji=K.merge(jt).extend({type:y.literal("SELECT_OPTION"),target:Et,cache:$t,choice:Nh.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Wu=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),Ps=K.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:Wu.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:zu.optional()})).openapi({ref:"AIAssertionCommand"}),wr=5,$i=600,_o=K.merge(jt).extend({type:y.literal("ELEMENT_CHECK"),target:Et,assertion:Ah,cache:$t.or(zu).optional(),timeout:y.number().int().min(0).max($i).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Dh=K.extend({type:y.literal("PAGE_CHECK"),assertion:wh,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max($i).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),kh=K.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"}),Zx=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()}),Uh=25,qi=K.merge(jt).merge(Zx).extend({type:y.literal("TYPE"),target:Et.optional(),value:y.string(),cache:$t}).openapi({ref:"TypeCommand"}),Qx=K.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"}),eM=K.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),tM=K.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),rM=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),nM=y.object({type:y.literal("REGEX"),pattern:y.string()}),oM=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),iM=y.discriminatedUnion("type",[rM,nM,oM]),aM=K.merge(Ms).merge(y.object({type:y.literal("TAB"),action:iM})).openapi({ref:"TabCommand"}),Fh=K.merge(Ms).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),sM=K.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),Bh=K.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),zh=K.extend({type:y.literal("REQUEST")}).merge(vo).openapi({ref:"RequestCommand"}),lM=K.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Rh).openapi({ref:"GraphQLRequestCommand"}),cM=K.merge(y.object({type:y.literal("SUCCESS"),condition:Ps.optional()})).openapi({ref:"SuccessCommand"}),Hh=K.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),uM=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),Ki=K.merge(jt).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:Et.optional(),screenshot:uM.optional(),cache:$t})).openapi({ref:"VisualDiffCommand"}),dM=K.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Bi,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),mM=K.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),pM=K.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Bi,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),gM=K.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),hM=K.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Bi.optional()})).openapi({ref:"SetHeaderCommand"}),fM=K.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Bi,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"})),SM=K.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"})),yM=K.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),bM=y.discriminatedUnion("type",[Hi,qi,Qx,eM,tM,ji,Gx,wo,Ao,Ps,$x,Gi,Wx]),ju=y.discriminatedUnion("type",[...bM.options,cM]),$u=y.discriminatedUnion("type",[...ju.options,xo,Oh,_o,Dh,Fh,xh,kh,Ph,_h,Bh,Mo,Ih,Mh,zh]),EM=y.discriminatedUnion("type",[kh,Kx,qx,Vu,sM,Ph,Vx,xo,_o,Jx,_h,Oh,Bh,Mo,Fh,Dh,Ih,Mh,zh,lM,Ro,Co,aM,Ki,Vi,Wi,xh,dM,mM,pM,gM,hM,fM,SM,yM]),Po=y.discriminatedUnion("type",[...ju.options,...EM.options]).openapi({ref:"Command"}),Is=y.discriminatedUnion("type",[...ju.options,Hh]),GG=y.discriminatedUnion("type",[...$u.options,Hh]);function jr(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:be(),type:r};break;case"AUTH_LOAD":{e={id:be(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:be(),type:r,goal:""};break;case"DIALOG":e={id:be(),type:r,action:"DISMISS"};break;case"DRAG":e={id:be(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:be(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:be(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:be(),type:r,delay:1};break;case"BLUR":e={id:be(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:be(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:be(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:be(),type:r,value:""};break;case"SELECT_OPTION":e={id:be(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:be(),type:r,url:""};case"TAB":e={id:be(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:be(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:be(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:be(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:be(),type:r,code:""};break;case"AI_ASSERTION":e={id:be(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:be(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:be(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:be(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:be(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:be(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:be(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:be(),type:r,key:""};break}case"SET_HEADER":{e={id:be(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:be(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:be(),type:r};break}case"OFFLINE_MODE":{e={id:be(),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 Gh(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 TM}from"zod";var qG=TM.discriminatedUnion("type",[Wi,Vu,Hi,xo,Vi,Gi,Mo,Ao,wo,Ro,Co,ji,qi,Ki,_o]);import{z as vM}from"zod";import{z as sn}from"zod";function Yi(r){return sn.object({key:sn.string(),testId:sn.string().optional(),moduleId:sn.string().optional(),organizationId:sn.string(),value:r})}function Xi(r){return Yi(r).extend({uniqueKey:sn.string()})}function Os(r){return sn.record(sn.string(),Xi(r))}var _t={type:!0,cache:!0},Io=vM.discriminatedUnion("type",[Ps.pick(_t),Wi.pick(_t),Hi.pick(_t),xo.pick(_t),_o.pick(_t),Vi.pick(_t),Gi.pick(_t),Mo.pick(_t),Ao.pick(_t),wo.pick(_t),Ro.pick(_t),Co.pick(_t),ji.pick(_t),qi.pick(_t),Ki.pick(_t)]),qu=Object.values(ot).filter(r=>Io.options.some(e=>e.shape.type.safeParse(r).success));Po.options.forEach(r=>{if("target"in r.shape&&!qu.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Ku(r){return qu.includes(r.type)}var Vh=Yi(Io),Wh=Xi(Io),tV=Os(Io);import{v4 as t$}from"uuid";import{z as A}from"zod";var $h=Symbol("Let zodToJsonSchema decide on which parser to use");var jh={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"},qh=r=>typeof r=="string"?{...jh,name:r}:{...jh,...r};var Kh=r=>{let e=qh(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 Yu(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function me(r,e,t,n,o){r[e]=t,Yu(r,e,n,o)}var Ls=(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 de}from"zod";function De(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?Ls(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as AM}from"zod";function Yh(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==AM.ZodAny&&(t.items=Y(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&me(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&me(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(me(t,"minItems",r.exactLength.value,r.exactLength.message,e),me(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function Xh(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?me(t,"minimum",n.value,n.message,e):me(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),me(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?me(t,"maximum",n.value,n.message,e):me(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),me(t,"maximum",n.value,n.message,e));break;case"multipleOf":me(t,"multipleOf",n.value,n.message,e);break}return t}function Jh(){return{type:"boolean"}}function Ns(r,e){return Y(r.type._def,e)}var Zh=(r,e)=>Y(r.innerType._def,e);function Xu(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Xu(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 wM(r,e)}}var wM=(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":me(t,"minimum",n.value,n.message,e);break;case"max":me(t,"maximum",n.value,n.message,e);break}return t};function Qh(r,e){return{...Y(r.innerType._def,e),default:r.defaultValue()}}function ef(r,e){return e.effectStrategy==="input"?Y(r.schema._def,e):De(e)}function tf(r){return{type:"string",enum:Array.from(r.values)}}var RM=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function rf(r,e){let t=[Y(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(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(RM(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 nf(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 Ji}from"zod";var Ju,pr={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:()=>(Ju===void 0&&(Ju=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ju),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 Ds(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":me(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":me(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":gr(t,"email",n.message,e);break;case"format:idn-email":gr(t,"idn-email",n.message,e);break;case"pattern:zod":Pt(t,pr.email,n.message,e);break}break;case"url":gr(t,"uri",n.message,e);break;case"uuid":gr(t,"uuid",n.message,e);break;case"regex":Pt(t,n.regex,n.message,e);break;case"cuid":Pt(t,pr.cuid,n.message,e);break;case"cuid2":Pt(t,pr.cuid2,n.message,e);break;case"startsWith":Pt(t,RegExp(`^${Zu(n.value,e)}`),n.message,e);break;case"endsWith":Pt(t,RegExp(`${Zu(n.value,e)}$`),n.message,e);break;case"datetime":gr(t,"date-time",n.message,e);break;case"date":gr(t,"date",n.message,e);break;case"time":gr(t,"time",n.message,e);break;case"duration":gr(t,"duration",n.message,e);break;case"length":me(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),me(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Pt(t,RegExp(Zu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&gr(t,"ipv4",n.message,e),n.version!=="v4"&&gr(t,"ipv6",n.message,e);break}case"base64url":Pt(t,pr.base64url,n.message,e);break;case"jwt":Pt(t,pr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Pt(t,pr.ipv4Cidr,n.message,e),n.version!=="v4"&&Pt(t,pr.ipv6Cidr,n.message,e);break}case"emoji":Pt(t,pr.emoji(),n.message,e);break;case"ulid":{Pt(t,pr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{gr(t,"binary",n.message,e);break}case"contentEncoding:base64":{me(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Pt(t,pr.base64,n.message,e);break}}break}case"nanoid":Pt(t,pr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Zu(r,e){return e.patternStrategy==="escape"?xM(r):r}var CM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function xM(r){let e="";for(let t=0;t<r.length;t++)CM.has(r[t])||(e+="\\"),e+=r[t];return e}function gr(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}}})):me(r,"format",e,t,n)}function Pt(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}}})):me(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 Kx=Object.defineProperty;var Ve=(r,e)=>()=>(r&&(e=r(r=0)),e);var Yx=(r,e)=>{for(var t in e)Kx(r,t,{get:e[t],enumerable:!0})};var oE,iE=Ve(()=>{"use strict";oE=typeof globalThis=="object"?globalThis:global});var aE=Ve(()=>{"use strict";iE()});var sE=Ve(()=>{"use strict";aE()});var Xr,bp=Ve(()=>{"use strict";Xr="1.9.0"});function LL(r){var e=new Set([r]),t=new Set,n=r.match(lE);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(lE);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 lE,cE,uE=Ve(()=>{"use strict";bp();lE=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;cE=LL(Xr)});function Qo(r,e,t,n){var o;n===void 0&&(n=!1);var i=Ma[xa]=(o=Ma[xa])!==null&&o!==void 0?o:{version:Xr};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!==Xr){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Xr);return t.error(a.stack||a.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Xr+"."),!0}function Jr(r){var e,t,n=(e=Ma[xa])===null||e===void 0?void 0:e.version;if(!(!n||!cE(n)))return(t=Ma[xa])===null||t===void 0?void 0:t[r]}function ei(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Xr+".");var t=Ma[xa];t&&delete t[r]}var NL,xa,Ma,_a=Ve(()=>{"use strict";sE();bp();uE();NL=Xr.split(".")[0],xa=Symbol.for("opentelemetry.js.api."+NL),Ma=oE});function Pa(r,e,t){var n=Jr("diag");if(n)return t.unshift(e),n[r].apply(n,kL([],DL(t),!1))}var DL,kL,dE,pE=Ve(()=>{"use strict";_a();DL=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},kL=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))},dE=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 Pa("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Pa("verbose",this._namespace,e)},r}()});var ke,Il=Ve(()=>{"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"})(ke||(ke={}))});function mE(r,e){r<ke.NONE?r=ke.NONE:r>ke.ALL&&(r=ke.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",ke.ERROR),warn:t("warn",ke.WARN),info:t("info",ke.INFO),debug:t("debug",ke.DEBUG),verbose:t("verbose",ke.VERBOSE)}}var gE=Ve(()=>{"use strict";Il()});var UL,FL,BL,Lr,Ia=Ve(()=>{"use strict";pE();gE();Il();_a();UL=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},FL=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))},BL="diag",Lr=function(){function r(){function e(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Jr("diag");if(s)return s[o].apply(s,FL([],UL(i),!1))}}var t=this,n=function(o,i){var a,s,c;if(i===void 0&&(i={logLevel:ke.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=Jr("diag"),d=mE((s=i.logLevel)!==null&&s!==void 0?s:ke.INFO,o);if(u&&!i.suppressOverrideMessage){var p=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return Qo("diag",d,t,!0)};t.setLogger=n,t.disable=function(){ei(BL,t)},t.createComponentLogger=function(o){return new dE(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 hE,fE=Ve(()=>{"use strict";hE=Symbol("BaggageEntryMetadata")});function Ep(r){return typeof r!="string"&&(zL.error("Cannot create baggage metadata from unknown type: "+typeof r),r=""),{__TYPE__:hE,toString:function(){return r}}}var zL,SE=Ve(()=>{"use strict";Ia();fE();zL=Lr.instance()});function Tp(r){return Symbol.for(r)}var HL,vp,Ap=Ve(()=>{"use strict";HL=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}(),vp=new HL});function Cp(){return Rp}var eo,GL,Ol,VL,jL,WL,$L,wp,qL,KL,YL,Rp,XL,JL,ZL,QL,eN,tN,rN,xp=Ve(()=>{"use strict";eo=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)}}(),GL=function(){function r(){}return r.prototype.createGauge=function(e,t){return JL},r.prototype.createHistogram=function(e,t){return ZL},r.prototype.createCounter=function(e,t){return XL},r.prototype.createUpDownCounter=function(e,t){return QL},r.prototype.createObservableGauge=function(e,t){return tN},r.prototype.createObservableCounter=function(e,t){return eN},r.prototype.createObservableUpDownCounter=function(e,t){return rN},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r}(),Ol=function(){function r(){}return r}(),VL=function(r){eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ol),jL=function(r){eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e}(Ol),WL=function(r){eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ol),$L=function(r){eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e}(Ol),wp=function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r}(),qL=function(r){eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(wp),KL=function(r){eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(wp),YL=function(r){eo(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(wp),Rp=new GL,XL=new VL,JL=new WL,ZL=new $L,QL=new jL,eN=new qL,tN=new KL,rN=new YL});var Vt,yE=Ve(()=>{"use strict";(function(r){r[r.INT=0]="INT",r[r.DOUBLE=1]="DOUBLE"})(Vt||(Vt={}))});var nN,oN,bE,EE=Ve(()=>{"use strict";Ap();nN=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},oN=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))},bE=function(){function r(){}return r.prototype.active=function(){return vp},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,oN([n],nN(o),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}()});var iN,aN,Mp,sN,TE,vE=Ve(()=>{"use strict";EE();_a();Ia();iN=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},aN=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))},Mp="context",sN=new bE,TE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Qo(Mp,e,Lr.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,aN([e,t,n],iN(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Jr(Mp)||sN},r.prototype.disable=function(){this._getContextManager().disable(),ei(Mp,Lr.instance())},r}()});var ti,AE=Ve(()=>{"use strict";vE();ti=TE.getInstance()});var z,wE=Ve(()=>{"use strict";Ia();z=Lr.instance()});var lN,RE,CE=Ve(()=>{"use strict";xp();lN=function(){function r(){}return r.prototype.getMeter=function(e,t,n){return Rp},r}(),RE=new lN});var _p,xE,ME=Ve(()=>{"use strict";CE();_a();Ia();_p="metrics",xE=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Qo(_p,e,Lr.instance())},r.prototype.getMeterProvider=function(){return Jr(_p)||RE},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){ei(_p,Lr.instance())},r}()});var Ll,_E=Ve(()=>{"use strict";ME();Ll=xE.getInstance()});var _e=Ve(()=>{"use strict";SE();Ap();Il();xp();yE();AE();wE();_E()});import{Argument as Sh,Command as QH,Option as eG}from"@commander-js/extra-typings";import Qk from"appium";import{execSync as e0}from"child_process";import{z as ku}from"zod";var uG=ku.object({input:ku.string(),agentConfigVersion:ku.string().optional()});import{z as ot}from"zod";var mG=ot.object({srcs:ot.array(ot.string()),urls:ot.array(ot.string()),desiredSrc:ot.string().optional(),desiredUrl:ot.string().optional()}),Eh=ot.object({srcRegex:ot.string().optional(),urlRegex:ot.string().optional()}),Th=ot.object({x:ot.number(),y:ot.number(),correlation:ot.number()}),gG=ot.object({searchImageBase64String:ot.string(),pageImageBase64String:ot.string(),id:ot.string().uuid(),timeoutMs:ot.number().max(1e4).min(0).optional()});import{z as I}from"zod";import*as L from"zod";import{extendZodWithOpenApi as Xx}from"zod-openapi";Xx(L);var nn=(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))(nn||{}),Jx=L.object({mPathSelectorTokens:L.string().array(),frameSrcRegex:L.string().optional(),frameUrlRegex:L.string().optional(),indices:L.number().array()}),Uu=L.object({result:L.number(),traceId:L.string()}).array(),Cs=L.object({type:L.literal("GCS_TRACES"),traces:Uu}),rn=(o=>(o.Precise="precise",o.Narrow="narrow",o.Unspecific="broad",o.Irrelevant="irrelevant",o))(rn||{}),vh=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(rn)}).optional(),shape:L.object({width:L.number(),height:L.number(),tolerance:L.nativeEnum(rn)}).optional(),boundingBox:L.object({x:L.number(),y:L.number(),width:L.number(),height:L.number()}).optional()}),Zx=L.object({selectors:L.string().array(),requirements:vh.optional()}),on=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:vh.optional(),additionalElements:Zx.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:Jx.optional(),inputDescription:L.string().optional().describe("the description that generated this cache"),targetSource:L.nativeEnum(nn).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:Cs.optional()}).openapi({ref:"ElementTargetCache"});function xs(r){return!!(r.serializedHtml||r.screenshotUrl||r.generatedSelectors||r.hybridSelector)}var Qx=L.object({type:L.literal("description"),elementDescriptor:L.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),eM=L.object({x:L.number(),y:L.number()}),tM=L.object({type:L.literal("coordinates"),pixels:eM}).openapi({ref:"CoordinatesTarget"});function an(r){return r.type==="description"}function Ar(r){return r.type==="coordinates"}var Tt=L.discriminatedUnion("type",[Qx,tM]).openapi({ref:"ElementTarget"});function Fu(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor}return!0}function Ah(r){return Cs.safeParse(r).success}import{v4 as ye}from"uuid";import*as y from"zod";import{extendZodWithOpenApi as cM}from"zod-openapi";import{z as re}from"zod";import{extendZodWithOpenApi as rM}from"zod-openapi";import{z as Hi}from"zod";import wh from"zod";var zi=wh.object({updatedAt:wh.coerce.date().optional()});var Bu=Hi.object({result:Hi.boolean(),traceId:Hi.string()}).array(),zu=Hi.object({type:Hi.literal("GCS_TRACES"),traces:Bu}),Hu=zi.extend({memory:zu.optional()});rM(re);var Rh=re.object({plan:re.string().optional(),evidence:re.string().optional(),thoughts:re.string(),result:re.boolean(),relevantElements:re.array(re.number()).optional(),updatedMemory:Bu.optional()}),jr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(jr||{});var nM=re.object({type:re.literal("ELEMENT_NAME"),negated:re.boolean().optional(),operation:re.nativeEnum(jr),value:re.string()}).openapi({ref:"ElementNameAssertion"}),oM=re.object({type:re.literal("ELEMENT_STYLE"),negated:re.boolean().optional(),operation:re.nativeEnum(jr),property:re.string(),value:re.string()}).openapi({ref:"ElementStyleAssertion"}),iM=re.object({type:re.literal("ELEMENT_CONTENT"),negated:re.boolean().optional(),operation:re.nativeEnum(jr),value:re.string()}).openapi({ref:"ElementContentAssertion"}),aM=re.object({type:re.literal("ELEMENT_ATTRIBUTE"),negated:re.boolean().optional(),operation:re.nativeEnum(jr),attr:re.string(),value:re.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Fn=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Fn||{}),sM=re.object({type:re.literal("ELEMENT_EXISTENCE"),negated:re.boolean().optional(),condition:re.nativeEnum(Fn).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Ch=re.discriminatedUnion("type",[iM,aM,sM,nM,oM]).openapi({ref:"ManualElementAssertion"});var lM=re.object({type:re.literal("CONTENT"),negated:re.boolean().optional(),value:re.string()}).openapi({ref:"PageContentAssertion"}),xh=re.discriminatedUnion("type",[lM]).openapi({ref:"ManualPageAssertion"});import Mt from"zod";var Gu=Mt.discriminatedUnion("type",[Mt.object({type:Mt.literal("SUBSTRING"),url:Mt.string()}),Mt.object({type:Mt.literal("GLOB"),glob:Mt.string()}),Mt.object({type:Mt.literal("REGEX"),regex:Mt.string()}),Mt.object({type:Mt.literal("DOMAIN"),domain:Mt.string()})]),Gi=Mt.object({urlMatcher:Gu,method:Mt.string().optional()});import{z as Se}from"zod";var Ao=Se.object({url:Se.string(),method:Se.union([Se.literal("GET"),Se.literal("POST"),Se.literal("PUT"),Se.literal("DELETE"),Se.literal("PATCH")]),headers:Se.record(Se.string(),Se.string()).optional(),params:Se.record(Se.string(),Se.string()).optional(),body:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),Mh=Se.object({url:Se.string(),headers:Se.record(Se.string(),Se.string()).optional(),query:Se.string(),variables:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),Ms=Se.object({code:Se.string(),fragment:Se.boolean().optional().describe("Agents should not touch this unless explicitly told to"),environment:Se.union([Se.literal("NODE"),Se.literal("BROWSER")]).optional().describe("default NODE, Agents default to using node unless it is necessary to use browser"),timeout:Se.number().int().max(60).optional().describe("Max seconds for the code to complete")});var it=(W=>(W.AI_EXTRACT="AI_EXTRACT",W.AI_ASSERTION="AI_ASSERTION",W.AUTH_LOAD="AUTH_LOAD",W.AUTH_SAVE="AUTH_SAVE",W.BLUR="BLUR",W.CAPTCHA="CAPTCHA",W.CLICK="CLICK",W.COOKIE="COOKIE",W.COPY="COPY",W.DIALOG="DIALOG",W.DRAG="DRAG",W.ELEMENT_CHECK="ELEMENT_CHECK",W.FILE_UPLOAD="FILE_UPLOAD",W.FOCUS="FOCUS",W.GO_BACK="GO_BACK",W.GO_FORWARD="GO_FORWARD",W.HOVER="HOVER",W.JAVASCRIPT="JAVASCRIPT",W.LOCAL_STORAGE="LOCAL_STORAGE",W.MOUSE_DRAG="MOUSE_DRAG",W.NAVIGATE="NAVIGATE",W.NEW_TAB="NEW_TAB",W.PAGE_CHECK="PAGE_CHECK",W.PASTE="PASTE",W.PRESS="PRESS",W.KEY_DOWN="KEY_DOWN",W.KEY_UP="KEY_UP",W.REFRESH="REFRESH",W.REQUEST="REQUEST",W.GRAPHQL_REQUEST="GRAPHQL_REQUEST",W.SCROLL_DOWN="SCROLL_DOWN",W.SCROLL_UP="SCROLL_UP",W.SCROLL_LEFT="SCROLL_LEFT",W.SCROLL_RIGHT="SCROLL_RIGHT",W.SELECT_OPTION="SELECT_OPTION",W.SWITCH_TAB="TAB",W.TYPE="TYPE",W.VISUAL_DIFF="VISUAL_DIFF",W.WAIT="WAIT",W.WAIT_FOR_URL="WAIT_FOR_URL",W.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",W.AWAIT_LISTENER="AWAIT_LISTENER",W.RECORD_REQUESTS="RECORD_REQUESTS",W.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",W.SET_HEADER="SET_HEADER",W.MOCK_ROUTE="MOCK_ROUTE",W.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",W.OFFLINE_MODE="OFFLINE_MODE",W.SUCCESS="SUCCESS",W))(it||{});cM(y);var K=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),$t=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"}),qt=zi.extend({target:on}).optional().openapi({ref:"SingleTargetCache"});function _h(r){return qt.safeParse(r).success}var _s=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),Ph=K.merge(_s).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})).openapi({ref:"NavigateCommand"}),Ps=$t.merge(y.object({cache:qt})),Bn=K.merge(Ps.merge(y.object({target:Tt.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))).openapi({ref:"ScrollUpCommand"}),zn=K.merge(Ps.merge(y.object({target:Tt.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))).openapi({ref:"ScrollDownCommand"}),wo=K.merge(Ps.merge(y.object({target:Tt.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ro=K.merge(Ps.merge(y.object({target:Tt.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))).openapi({ref:"ScrollRightCommand"}),$G=y.discriminatedUnion("type",[Bn,zn,wo,Ro]).openapi({ref:"AllScrollCommands"}),uM=K.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Ih=K.merge(y.object({type:y.literal("WAIT"),delay:y.number()})).openapi({ref:"WaitCommand"}),dM=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")}),Oh=K.extend({type:y.literal("WAIT_FOR_URL"),matcher:Gu}).merge(dM).openapi({ref:"WaitUrlCommand"}),Lh=K.merge(_s).merge(y.object({type:y.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),Nh=K.merge(y.object({type:y.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Dh=K.merge(y.object({type:y.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),pM=K.extend({type:y.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),mM=K.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"}),ju=K.merge($t).extend({type:y.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),kh=K.extend({type:y.literal("COPY"),value:y.string()}).openapi({ref:"CopyCommand"}),Uh=K.extend({type:y.literal("PASTE")}).openapi({ref:"PasteCommand"}),Fh=K.merge(Ms).extend({type:y.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Co=K.merge($t).extend({type:y.literal("CLICK"),target:Tt,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:qt,relativePosition:y.object({x:y.number(),y:y.number()}).optional()}).openapi({ref:"ClickCommand"}),Bh=zi.extend({fromTarget:on.optional(),toTarget:on.optional()}),xo=K.merge($t).merge(y.object({type:y.literal("DRAG"),fromTarget:Tt,toTarget:Tt,steps:y.number().optional(),hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:Bh.optional()})).openapi({ref:"DragCommand"}),Mo=K.merge($t).merge(y.object({type:y.literal("MOUSE_DRAG"),target:Tt.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:qt})).openapi({ref:"MouseDragCommand"}),_o=K.merge($t).merge(y.object({type:y.literal("HOVER"),target:Tt,cache:qt})).openapi({ref:"HoverCommand"}),ji=K.merge($t).merge(y.object({type:y.literal("FOCUS"),target:Tt,cache:qt})).openapi({ref:"FocusCommand"}),Wi=K.merge($t).extend({type:y.literal("BLUR"),target:Tt.optional(),cache:qt}).openapi({ref:"BlurCommand"}),gM=y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),hM=y.object({type:y.literal("USER_FILE"),name:y.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),fM=K.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[gM,hM]),filename:y.string().optional()}).openapi({ref:"FileUploadCommand"}),zh=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()})]),Po=K.merge($t).extend({type:y.literal("SELECT_OPTION"),target:Tt,cache:qt,choice:zh.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Wu=y.union([y.literal("MULTIMODAL"),y.literal("VISION_ONLY")]),$i=K.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),contextChoice:Wu.optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Hu.optional()})).openapi({ref:"AIAssertionCommand"}),wr=5,qi=600,Io=K.merge($t).extend({type:y.literal("ELEMENT_CHECK"),target:Tt,assertion:Ch,cache:qt.or(Hu).optional(),timeout:y.number().int().min(0).max(qi).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Hh=K.extend({type:y.literal("PAGE_CHECK"),assertion:xh,iframeUrl:y.string().optional().describe("url or url regex for the iframe"),timeout:y.number().int().min(0).max(qi).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Gh=K.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"}),SM=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()}),Vh=25,Oo=K.merge($t).merge(SM).extend({type:y.literal("TYPE"),target:Tt.optional(),value:y.string(),cache:qt}).openapi({ref:"TypeCommand"}),jh=K.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"}),Wh=K.merge(y.object({type:y.literal("KEY_DOWN"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyDownCommand"}),$h=K.merge(y.object({type:y.literal("KEY_UP"),value:y.string(),convertMeta:y.boolean().optional()})).openapi({ref:"KeyUpCommand"}),yM=y.object({type:y.literal("SUBSTRING"),substring:y.string()}),bM=y.object({type:y.literal("REGEX"),pattern:y.string()}),EM=y.object({type:y.literal("INDEX"),index:y.coerce.string()}),TM=y.discriminatedUnion("type",[yM,bM,EM]),vM=K.merge(_s).merge(y.object({type:y.literal("TAB"),action:TM})).openapi({ref:"TabCommand"}),qh=K.merge(_s).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})).openapi({ref:"NewTabCommand"}),AM=K.merge(y.object({type:y.literal("COOKIE"),value:y.string()})).openapi({ref:"CookieCommand"}),Kh=K.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})).openapi({ref:"LocalStorageCommand"}),Yh=K.extend({type:y.literal("REQUEST")}).merge(Ao).openapi({ref:"RequestCommand"}),wM=K.extend({type:y.literal("GRAPHQL_REQUEST")}).merge(Mh).openapi({ref:"GraphQLRequestCommand"}),Xh=K.merge(y.object({type:y.literal("SUCCESS"),condition:$i.optional()})).openapi({ref:"SuccessCommand"}),Jh=K.merge(y.object({type:y.literal("FAILURE")})).openapi({ref:"FailureCommand"}),RM=y.object({data:y.string().describe("location at which to find a jpg"),width:y.number(),height:y.number()}),Ki=K.merge($t).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:Tt.optional(),screenshot:RM.optional(),cache:qt})).openapi({ref:"VisualDiffCommand"}),CM=K.merge(y.object({type:y.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Gi,key:y.string()})).openapi({ref:"RegisterRequestListenerCommand"}),xM=K.merge(y.object({type:y.literal("AWAIT_LISTENER"),key:y.string(),timeout:y.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),MM=K.merge(y.object({type:y.literal("RECORD_REQUESTS"),requestMatcher:Gi,key:y.string()})).openapi({ref:"RecordRequestsCommand"}),_M=K.merge(y.object({type:y.literal("GET_RECORDED_REQUESTS"),key:y.string()})).openapi({ref:"GetRecordedRequestsCommand"}),PM=K.merge(y.object({type:y.literal("SET_HEADER"),name:y.string(),value:y.string(),requestMatcher:Gi.optional()})).openapi({ref:"SetHeaderCommand"}),IM=K.merge(y.object({type:y.literal("MOCK_ROUTE"),requestMatcher:Gi,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"})),OM=K.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"})),LM=K.merge(y.object({type:y.literal("OFFLINE_MODE"),enable:y.boolean()})).openapi({ref:"OfflineModeCommand"}),NM=["CLICK","TYPE","PRESS","KEY_DOWN","KEY_UP","SELECT_OPTION","NAVIGATE","SCROLL_DOWN","SCROLL_UP","AI_ASSERTION","GO_BACK","HOVER","WAIT"],qG=[...NM,"DRAG"],DM=y.discriminatedUnion("type",[Co,Oo,jh,Wh,$h,Po,Ph,zn,Bn,$i,Nh,_o,Ih]),kM=y.discriminatedUnion("type",[...DM.options,xo]),UM=y.discriminatedUnion("type",[...kM.options]),Zh=y.discriminatedUnion("type",[...UM.options,Xh]),$u=y.discriminatedUnion("type",[Xh,Co,Oo,jh,Wh,$h,Po,Ph,zn,Bn,$i,Nh,_o,Ih,Fh,Io,Hh,qh,Oh,Gh,kh,Dh,Kh,xo,Mo,Uh,Lh,Yh]),FM=y.discriminatedUnion("type",[Gh,mM,pM,ju,AM,kh,uM,Io,fM,Dh,Fh,Kh,Mo,qh,Hh,Uh,Lh,Yh,wM,wo,Ro,vM,Ki,ji,Wi,Oh,CM,xM,MM,_M,PM,IM,OM,LM]),Lo=y.discriminatedUnion("type",[...Zh.options,...FM.options]).openapi({ref:"Command"}),Is=y.discriminatedUnion("type",[...Zh.options,Jh]),KG=y.discriminatedUnion("type",[...$u.options,Jh]);function Wr(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:ye(),type:r};break;case"AUTH_LOAD":{e={id:ye(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ye(),type:r,goal:""};break;case"DIALOG":e={id:ye(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ye(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ye(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:ye(),type:r,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:ye(),type:r,delay:1};break;case"BLUR":e={id:ye(),type:r};break;case"HOVER":case"FOCUS":case"CLICK":e={id:ye(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:ye(),type:r,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:ye(),type:r,value:""};break;case"SELECT_OPTION":e={id:ye(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:ye(),type:r,url:""};case"TAB":e={id:ye(),type:r,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:ye(),type:r,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:ye(),type:r,url:"",query:""};break;case"LOCAL_STORAGE":e={id:ye(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ye(),type:r,code:""};break;case"AI_ASSERTION":e={id:ye(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ye(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ye(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ye(),type:r,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:ye(),type:r,key:""};break}case"RECORD_REQUESTS":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:ye(),type:r,key:""};break}case"SET_HEADER":{e={id:ye(),type:r,name:"",value:""};break}case"MOCK_ROUTE":{e={id:ye(),type:r,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:ye(),type:r};break}case"OFFLINE_MODE":{e={id:ye(),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 Qh(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 BM}from"zod";var QG=BM.discriminatedUnion("type",[Wi,ju,Co,xo,ji,_o,Mo,Bn,zn,wo,Ro,Po,Oo,Ki,Io]);import{z as zM}from"zod";import{z as sn}from"zod";function Yi(r){return sn.object({key:sn.string(),testId:sn.string().optional(),moduleId:sn.string().optional(),organizationId:sn.string(),value:r})}function Xi(r){return Yi(r).extend({uniqueKey:sn.string()})}function Os(r){return sn.record(sn.string(),Xi(r))}var _t={type:!0,cache:!0},No=zM.discriminatedUnion("type",[$i.pick(_t),Wi.pick(_t),Co.pick(_t),xo.pick(_t),Io.pick(_t),ji.pick(_t),_o.pick(_t),Mo.pick(_t),Bn.pick(_t),zn.pick(_t),wo.pick(_t),Ro.pick(_t),Po.pick(_t),Oo.pick(_t),Ki.pick(_t)]),qu=Object.values(it).filter(r=>No.options.some(e=>e.shape.type.safeParse(r).success));Lo.options.forEach(r=>{if("target"in r.shape&&!qu.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});function Ku(r){return qu.includes(r.type)}var ef=Yi(No),tf=Xi(No),sV=Os(No);import{v4 as s$}from"uuid";import{z as v}from"zod";var nf=Symbol("Let zodToJsonSchema decide on which parser to use");var rf={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"},of=r=>typeof r=="string"?{...rf,name:r}:{...rf,...r};var af=r=>{let e=of(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 Yu(r,e,t,n){n?.errorMessages&&t&&(r.errorMessage={...r.errorMessage,[e]:t})}function de(r,e,t,n,o){r[e]=t,Yu(r,e,n,o)}var Ls=(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 ue}from"zod";function Ue(r){if(r.target!=="openAi")return{};let e=[...r.basePath,r.definitionPath,r.openAiAnyTypeName];return r.flags.hasReferencedOpenAiAnyType=!0,{$ref:r.$refStrategy==="relative"?Ls(e,r.currentPath):e.join("/")}}import{ZodFirstPartyTypeKind as HM}from"zod";function sf(r,e){let t={type:"array"};return r.type?._def&&r.type?._def?.typeName!==HM.ZodAny&&(t.items=Y(r.type._def,{...e,currentPath:[...e.currentPath,"items"]})),r.minLength&&de(t,"minItems",r.minLength.value,r.minLength.message,e),r.maxLength&&de(t,"maxItems",r.maxLength.value,r.maxLength.message,e),r.exactLength&&(de(t,"minItems",r.exactLength.value,r.exactLength.message,e),de(t,"maxItems",r.exactLength.value,r.exactLength.message,e)),t}function lf(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?de(t,"minimum",n.value,n.message,e):de(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),de(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(t,"maximum",n.value,n.message,e):de(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),de(t,"maximum",n.value,n.message,e));break;case"multipleOf":de(t,"multipleOf",n.value,n.message,e);break}return t}function cf(){return{type:"boolean"}}function Ns(r,e){return Y(r.type._def,e)}var uf=(r,e)=>Y(r.innerType._def,e);function Xu(r,e,t){let n=t??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>Xu(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 GM(r,e)}}var GM=(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":de(t,"minimum",n.value,n.message,e);break;case"max":de(t,"maximum",n.value,n.message,e);break}return t};function df(r,e){return{...Y(r.innerType._def,e),default:r.defaultValue()}}function pf(r,e){return e.effectStrategy==="input"?Y(r.schema._def,e):Ue(e)}function mf(r){return{type:"string",enum:Array.from(r.values)}}var VM=r=>"type"in r&&r.type==="string"?!1:"allOf"in r;function gf(r,e){let t=[Y(r.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(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(VM(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 hf(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 Ji}from"zod";var Ju,pr={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:()=>(Ju===void 0&&(Ju=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ju),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 Ds(r,e){let t={type:"string"};if(r.checks)for(let n of r.checks)switch(n.kind){case"min":de(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e);break;case"max":de(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":mr(t,"email",n.message,e);break;case"format:idn-email":mr(t,"idn-email",n.message,e);break;case"pattern:zod":Pt(t,pr.email,n.message,e);break}break;case"url":mr(t,"uri",n.message,e);break;case"uuid":mr(t,"uuid",n.message,e);break;case"regex":Pt(t,n.regex,n.message,e);break;case"cuid":Pt(t,pr.cuid,n.message,e);break;case"cuid2":Pt(t,pr.cuid2,n.message,e);break;case"startsWith":Pt(t,RegExp(`^${Zu(n.value,e)}`),n.message,e);break;case"endsWith":Pt(t,RegExp(`${Zu(n.value,e)}$`),n.message,e);break;case"datetime":mr(t,"date-time",n.message,e);break;case"date":mr(t,"date",n.message,e);break;case"time":mr(t,"time",n.message,e);break;case"duration":mr(t,"duration",n.message,e);break;case"length":de(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,n.value):n.value,n.message,e),de(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,n.value):n.value,n.message,e);break;case"includes":{Pt(t,RegExp(Zu(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&mr(t,"ipv4",n.message,e),n.version!=="v4"&&mr(t,"ipv6",n.message,e);break}case"base64url":Pt(t,pr.base64url,n.message,e);break;case"jwt":Pt(t,pr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Pt(t,pr.ipv4Cidr,n.message,e),n.version!=="v4"&&Pt(t,pr.ipv6Cidr,n.message,e);break}case"emoji":Pt(t,pr.emoji(),n.message,e);break;case"ulid":{Pt(t,pr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{mr(t,"binary",n.message,e);break}case"contentEncoding:base64":{de(t,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Pt(t,pr.base64,n.message,e);break}}break}case"nanoid":Pt(t,pr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return t}function Zu(r,e){return e.patternStrategy==="escape"?WM(r):r}var jM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function WM(r){let e="";for(let t=0;t<r.length;t++)jM.has(r[t])||(e+="\\"),e+=r[t];return e}function mr(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}}})):de(r,"format",e,t,n)}function Pt(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:ff(e,n),...t&&n.errorMessages&&{errorMessage:{pattern:t}}})):de(r,"pattern",ff(e,n),t,n)}function ff(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
|
-
]`;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 ks(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===Ji.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??De(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Ji.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=Ds(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===Ji.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===Ji.ZodBranded&&r.keyType._def.type._def.typeName===Ji.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=Ns(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function af(r,e){if(e.mapStrategy==="record")return ks(r,e);let t=Y(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||De(e),n=Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||De(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function sf(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 lf(r){return r.target==="openAi"?void 0:{not:De({...r,currentPath:[...r.currentPath,"not"]})}}function cf(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Zi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function df(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 Zi&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=Zi[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)=>Y(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 mf(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:Zi[r.innerType._def.typeName],nullable:!0}:{type:[Zi[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=Y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function pf(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",Yu(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?me(t,"minimum",n.value,n.message,e):me(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),me(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?me(t,"maximum",n.value,n.message,e):me(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),me(t,"maximum",n.value,n.message,e));break;case"multipleOf":me(t,"multipleOf",n.value,n.message,e);break}return t}function gf(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=_M(c);l&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=Y(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=MM(r,e);return a!==void 0&&(n.additionalProperties=a),n}function MM(r,e){if(r.catchall._def.typeName!=="ZodNever")return Y(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 _M(r){try{return r.isOptional()}catch{return!0}}var hf=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(r.innerType._def,e);let t=Y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:De(e)},t]}:De(e)};var ff=(r,e)=>{if(e.pipeStrategy==="input")return Y(r.in._def,e);if(e.pipeStrategy==="output")return Y(r.out._def,e);let t=Y(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function Sf(r,e){return Y(r.type._def,e)}function yf(r,e){let n={type:"array",uniqueItems:!0,items:Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&me(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&me(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function bf(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>Y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:Y(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>Y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function Ef(r){return{not:De(r)}}function Tf(r){return De(r)}var vf=(r,e)=>Y(r.innerType._def,e);var Af=(r,e,t)=>{switch(e){case de.ZodString:return Ds(r,t);case de.ZodNumber:return pf(r,t);case de.ZodObject:return gf(r,t);case de.ZodBigInt:return Xh(r,t);case de.ZodBoolean:return Jh();case de.ZodDate:return Xu(r,t);case de.ZodUndefined:return Ef(t);case de.ZodNull:return cf(t);case de.ZodArray:return Yh(r,t);case de.ZodUnion:case de.ZodDiscriminatedUnion:return df(r,t);case de.ZodIntersection:return rf(r,t);case de.ZodTuple:return bf(r,t);case de.ZodRecord:return ks(r,t);case de.ZodLiteral:return nf(r,t);case de.ZodEnum:return tf(r);case de.ZodNativeEnum:return sf(r);case de.ZodNullable:return mf(r,t);case de.ZodOptional:return hf(r,t);case de.ZodMap:return af(r,t);case de.ZodSet:return yf(r,t);case de.ZodLazy:return()=>r.getter()._def;case de.ZodPromise:return Sf(r,t);case de.ZodNaN:case de.ZodNever:return lf(t);case de.ZodEffects:return ef(r,t);case de.ZodAny:return De(t);case de.ZodUnknown:return Tf(t);case de.ZodDefault:return Qh(r,t);case de.ZodBranded:return Ns(r,t);case de.ZodReadonly:return vf(r,t);case de.ZodCatch:return Zh(r,t);case de.ZodPipeline:return ff(r,t);case de.ZodFunction:case de.ZodVoid:case de.ZodSymbol:return;default:return(n=>{})(e)}};function Y(r,e,t=!1){let n=e.seen.get(r);if(e.override){let s=e.override?.(r,e,n,t);if(s!==$h)return s}if(n&&!t){let s=PM(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=Af(r,r.typeName,e),a=typeof i=="function"?Y(i(),e):i;if(a&&IM(r,e,a),e.postProcess){let s=e.postProcess(a,r,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var PM=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:Ls(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`),De(e)):e.$refStrategy==="seen"?De(e):void 0}},IM=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var Bn=(r,e)=>{let t=Kh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:Y(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??De(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Y(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??De(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 Rr}from"zod";import{extendZodWithOpenApi as OM}from"zod-openapi";OM(Rr);var ve=(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))(ve||{});var Qu=Rr.object({reason:Rr.nativeEnum(ve),previousStepsDescription:Rr.array(Rr.string()).optional(),summary:Rr.string(),rootCause:Rr.string().optional()}).openapi({ref:"TestResultClassification"}),Us=Rr.object({errorMessage:Rr.string(),errorStack:Rr.string().optional(),classification:Qu.optional()}).openapi({ref:"TestFailureDetails"});var C=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(ve))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}}},Oo=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Cr=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}
|
|
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 ks(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===Ji.ZodEnum)return{type:"object",required:r.keyType._def.values,properties:r.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ue(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let t={type:"object",additionalProperties:Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(r.keyType?._def.typeName===Ji.ZodString&&r.keyType._def.checks?.length){let{type:n,...o}=Ds(r.keyType._def,e);return{...t,propertyNames:o}}else{if(r.keyType?._def.typeName===Ji.ZodEnum)return{...t,propertyNames:{enum:r.keyType._def.values}};if(r.keyType?._def.typeName===Ji.ZodBranded&&r.keyType._def.type._def.typeName===Ji.ZodString&&r.keyType._def.type._def.checks?.length){let{type:n,...o}=Ns(r.keyType._def,e);return{...t,propertyNames:o}}}return t}function Sf(r,e){if(e.mapStrategy==="record")return ks(r,e);let t=Y(r.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ue(e),n=Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ue(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,n],minItems:2,maxItems:2}}}function yf(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 bf(r){return r.target==="openAi"?void 0:{not:Ue({...r,currentPath:[...r.currentPath,"not"]})}}function Ef(r){return r.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Zi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vf(r,e){if(e.target==="openApi3")return Tf(r,e);let t=r.options instanceof Map?Array.from(r.options.values()):r.options;if(t.every(n=>n._def.typeName in Zi&&(!n._def.checks||!n._def.checks.length))){let n=t.reduce((o,i)=>{let a=Zi[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 Tf(r,e)}var Tf=(r,e)=>{let t=(r.options instanceof Map?Array.from(r.options.values()):r.options).map((n,o)=>Y(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 Af(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:Zi[r.innerType._def.typeName],nullable:!0}:{type:[Zi[r.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(r.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let t=Y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function wf(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",Yu(t,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?de(t,"minimum",n.value,n.message,e):de(t,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(t.exclusiveMinimum=!0),de(t,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?de(t,"maximum",n.value,n.message,e):de(t,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(t.exclusiveMaximum=!0),de(t,"maximum",n.value,n.message,e));break;case"multipleOf":de(t,"multipleOf",n.value,n.message,e);break}return t}function Rf(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=qM(c);l&&t&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=Y(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=$M(r,e);return a!==void 0&&(n.additionalProperties=a),n}function $M(r,e){if(r.catchall._def.typeName!=="ZodNever")return Y(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 qM(r){try{return r.isOptional()}catch{return!0}}var Cf=(r,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(r.innerType._def,e);let t=Y(r.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Ue(e)},t]}:Ue(e)};var xf=(r,e)=>{if(e.pipeStrategy==="input")return Y(r.in._def,e);if(e.pipeStrategy==="output")return Y(r.out._def,e);let t=Y(r.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(r.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,n].filter(o=>o!==void 0)}};function Mf(r,e){return Y(r.type._def,e)}function _f(r,e){let n={type:"array",uniqueItems:!0,items:Y(r.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return r.minSize&&de(n,"minItems",r.minSize.value,r.minSize.message,e),r.maxSize&&de(n,"maxItems",r.maxSize.value,r.maxSize.message,e),n}function Pf(r,e){return r.rest?{type:"array",minItems:r.items.length,items:r.items.map((t,n)=>Y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[]),additionalItems:Y(r.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:r.items.length,maxItems:r.items.length,items:r.items.map((t,n)=>Y(t._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((t,n)=>n===void 0?t:[...t,n],[])}}function If(r){return{not:Ue(r)}}function Of(r){return Ue(r)}var Lf=(r,e)=>Y(r.innerType._def,e);var Nf=(r,e,t)=>{switch(e){case ue.ZodString:return Ds(r,t);case ue.ZodNumber:return wf(r,t);case ue.ZodObject:return Rf(r,t);case ue.ZodBigInt:return lf(r,t);case ue.ZodBoolean:return cf();case ue.ZodDate:return Xu(r,t);case ue.ZodUndefined:return If(t);case ue.ZodNull:return Ef(t);case ue.ZodArray:return sf(r,t);case ue.ZodUnion:case ue.ZodDiscriminatedUnion:return vf(r,t);case ue.ZodIntersection:return gf(r,t);case ue.ZodTuple:return Pf(r,t);case ue.ZodRecord:return ks(r,t);case ue.ZodLiteral:return hf(r,t);case ue.ZodEnum:return mf(r);case ue.ZodNativeEnum:return yf(r);case ue.ZodNullable:return Af(r,t);case ue.ZodOptional:return Cf(r,t);case ue.ZodMap:return Sf(r,t);case ue.ZodSet:return _f(r,t);case ue.ZodLazy:return()=>r.getter()._def;case ue.ZodPromise:return Mf(r,t);case ue.ZodNaN:case ue.ZodNever:return bf(t);case ue.ZodEffects:return pf(r,t);case ue.ZodAny:return Ue(t);case ue.ZodUnknown:return Of(t);case ue.ZodDefault:return df(r,t);case ue.ZodBranded:return Ns(r,t);case ue.ZodReadonly:return Lf(r,t);case ue.ZodCatch:return uf(r,t);case ue.ZodPipeline:return xf(r,t);case ue.ZodFunction:case ue.ZodVoid:case ue.ZodSymbol:return;default:return(n=>{})(e)}};function Y(r,e,t=!1){let n=e.seen.get(r);if(e.override){let s=e.override?.(r,e,n,t);if(s!==nf)return s}if(n&&!t){let s=KM(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=Nf(r,r.typeName,e),a=typeof i=="function"?Y(i(),e):i;if(a&&YM(r,e,a),e.postProcess){let s=e.postProcess(a,r,e);return o.jsonSchema=a,s}return o.jsonSchema=a,a}var KM=(r,e)=>{switch(e.$refStrategy){case"root":return{$ref:r.path.join("/")};case"relative":return{$ref:Ls(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`),Ue(e)):e.$refStrategy==="seen"?Ue(e):void 0}},YM=(r,e,t)=>(r.description&&(t.description=r.description,e.markdownDescription&&(t.markdownDescription=r.description)),t);var Qi=(r,e)=>{let t=af(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:Y(u._def,{...t,currentPath:[...t.basePath,t.definitionPath,l]},!0)??Ue(t)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Y(r._def,o===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,o]},!1)??Ue(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 Rr}from"zod";import{extendZodWithOpenApi as XM}from"zod-openapi";XM(Rr);var Ae=(p=>(p.AI_PROVIDER="AIProviderError",p.USER_INFRA="UserInfrastructureError",p.ACTION_FAILURE="ActionFailureError",p.ASSERTION_FAILURE="AssertionFailureError",p.CONFIG_ERROR="UserConfigurationError",p.SETUP_FAILURE="SetupFailureError",p.TEARDOWN_FAILURE="TeardownFailureError",p.WEB_AGENT_PLATFORM="InternalWebAgentError",p.UNKNOWN_PLATFORM="InternalPlatformError",p.JOB_TIMEOUT="JobTimeoutError",p.CONCURRENCY_ERROR="ConcurrencyError",p.UNKNOWN="UnknownError",p))(Ae||{});var Qu=Rr.object({reason:Rr.nativeEnum(Ae),previousStepsDescription:Rr.array(Rr.string()).optional(),summary:Rr.string(),rootCause:Rr.string().optional()}).openapi({ref:"TestResultClassification"}),Us=Rr.object({errorMessage:Rr.string(),errorStack:Rr.string().optional(),classification:Qu.optional()}).openapi({ref:"TestFailureDetails"});var x=class extends Error{reason;constructor(e,t,n){let o=!1;for(let i of Object.values(Ae))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}}},Do=class extends Error{updatedLocatorMemory;constructor(e,t,n={}){super(e,n),this.updatedLocatorMemory=t,this.name="NoElementsFoundUsingAIError"}},Cr=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 wf(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function ed(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 xr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Fs=class extends xr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Bs=class extends xr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function td(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}var rd="Element to be clicked has no bounding box";function Rf(r){return r instanceof Error?r.message.startsWith(rd):!1}function nd(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 od(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 Qi=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var LM={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."},NM={...LM,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.",DRAG:"Drag an element from one location and drop it onto another element.",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."};$u.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!NM[e])throw new Error(`Command type ${e} is missing a description`)});var DM=A.object({type:A.literal("CLICK"),description:A.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:A.boolean().or(A.null()),rightClick:A.boolean().or(A.null())}),kM=A.object({type:A.literal("TYPE"),description:A.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:A.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:A.boolean().or(A.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:A.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),UM=A.object({type:A.literal("GO_BACK")}),FM=A.object({type:A.literal("GO_FORWARD")}),BM=A.object({type:A.literal("LOCAL_STORAGE"),key:A.string().describe("The localStorage key to set or get."),value:A.string().describe("The value to store in localStorage. If reading, this can be empty.")}),zM=A.object({type:A.literal("PRESS"),keys:A.array(A.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.')}),HM=A.object({type:A.literal("SELECT_OPTION"),description:A.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:A.discriminatedUnion("type",[A.object({type:A.literal("VALUE"),value:A.string()}),A.object({type:A.literal("LABEL"),label:A.string()}),A.object({type:A.literal("INDEX"),index:A.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.")}),GM=A.object({type:A.literal("NAVIGATE"),url:A.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),VM=A.object({type:A.literal("SCROLL"),y:A.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),WM=A.object({type:A.literal("WAIT"),timeout:A.number().describe("The number of seconds to wait.")}),jM=A.object({type:A.literal("AI_ASSERTION"),assertion:A.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:A.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.")}),$M=A.object({type:A.literal("HOVER"),description:A.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.")}),qM=A.object({type:A.literal("COPY"),value:A.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),KM=A.object({type:A.literal("PASTE")}),YM=A.object({type:A.literal("REFRESH")}),XM=A.object({type:A.literal("REQUEST"),url:A.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:A.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:A.record(A.string(),A.string()).or(A.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:A.record(A.string(),A.string()).or(A.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:A.string().or(A.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:A.number().int().or(A.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),JM=A.object({type:A.literal("DRAG"),fromDescription:A.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:A.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:A.number().int().positive().or(A.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:A.number().positive().or(A.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),ZM=A.object({type:A.literal("MOUSE_DRAG"),description:A.string().or(A.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:A.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:A.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:A.number().int().positive().or(A.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),QM=A.object({type:A.literal("JAVASCRIPT"),code:A.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:A.union([A.literal("NODE"),A.literal("BROWSER")]).or(A.null()).describe("Execution environment. Default is NODE."),timeout:A.number().or(A.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),e_=A.object({type:A.literal("AI_EXTRACT"),goal:A.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:A.string().or(A.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:A.string().or(A.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:A.string().or(A.null()).describe("URL or URL regex for the iframe to extract data from.")}),t_=A.object({type:A.literal("ELEMENT_CHECK"),description:A.string().describe("Description of the element to check."),assertionType:A.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:A.string().or(A.null()).describe("The value to check against (required for CONTENT assertions)."),negated:A.boolean().or(A.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:A.number().or(A.null()).describe("Max seconds to wait for the assertion to be true.")}),r_=A.object({type:A.literal("PAGE_CHECK"),value:A.string().describe("The text content to check for on the page."),negated:A.boolean().or(A.null()).describe("If true, checks that the content is NOT present."),timeout:A.number().or(A.null()).describe("Max seconds to wait for the assertion to be true.")}),n_=A.object({type:A.literal("NEW_TAB"),url:A.string().describe("The URL to open in the new tab.")}),o_=A.object({type:A.literal("WAIT_FOR_URL"),matcher:A.discriminatedUnion("type",[A.object({type:A.literal("SUBSTRING"),url:A.string()}),A.object({type:A.literal("GLOB"),glob:A.string()}),A.object({type:A.literal("REGEX"),regex:A.string()}),A.object({type:A.literal("DOMAIN"),domain:A.string()})]).describe("How to match the URL."),caseInsensitive:A.boolean().or(A.null()),negated:A.boolean().or(A.null()).describe("Wait for the URL to NOT match instead."),timeout:A.number().or(A.null()).describe("Max seconds to wait for the URL.")}),Cf=A.object({type:A.literal("SUCCESS")}),id=A.object({type:A.literal("FAILURE")}),ea=A.discriminatedUnion("type",[DM,kM,zM,HM,GM,VM,WM,jM,$M,UM]),c$=Bn(ea),zs=A.discriminatedUnion("type",[...ea.options,JM,QM,t_,r_,n_,o_,e_,qM,FM,BM,ZM,KM,YM,XM]),u$=Bn(zs),i_=A.discriminatedUnion("type",[...ea.options,id]).describe("The command that will be executed next. This should naturally follow from your reasoning and be consistent with the goal."),d$=Bn(i_),a_=A.discriminatedUnion("type",[...ea.options,Cf,id]),m$=Bn(a_),p$=A.discriminatedUnion("type",[...zs.options,Cf,id]),s_=A.object({command:ea,thoughts:A.string()}),g$=Bn(s_),h$=A.object({command:A.unknown(),thoughts:A.string()});import{z as ad}from"zod";import{extendZodWithOpenApi as u_}from"zod-openapi";import{z as xf}from"zod";import{extendZodWithOpenApi as l_}from"zod-openapi";import{z as zn}from"zod";var qt=zn.object({index:zn.number().optional().describe("global index within a test (in-order traversal)"),id:zn.string(),skipped:zn.boolean().optional(),envKey:zn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:zn.boolean().optional(),retries:zn.number().optional()});l_(xf);var c_=qt.extend({type:xf.literal("PRESET_ACTION")}),Kt=c_.extend({command:Po}).openapi({ref:"PresetAction"});u_(ad);var Hn=qt.extend({type:ad.literal("AI_ACTION"),text:ad.string(),steps:Kt.array().optional()}).openapi({ref:"AIAction"});import{z as It}from"zod";import{z as Hs}from"zod";import{extendZodWithOpenApi as d_}from"zod-openapi";d_(Hs);var Lo=qt.extend({type:Hs.literal("AI_ACTION_DYNAMIC"),text:Hs.string(),retries:Hs.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Mf}from"zod";var sd=qt.extend({type:Mf.literal("CONDITIONAL"),skipped:Mf.boolean().optional()});import{z as pe}from"zod";var m_=pe.object({cacheKey:pe.string(),cacheExpiryMs:pe.number()}),ld=qt.extend({id:pe.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:pe.record(pe.string()).optional(),cacheConfig:m_.optional()}),$r=ld.extend({type:pe.literal("MODULE"),moduleId:pe.string().uuid()}),p_=pe.union([$r.pick({type:!0,moduleId:!0}),pe.record(pe.unknown())]),g_=pe.object({type:pe.literal("URL_REGEX"),regex:pe.string()}),h_=pe.object({type:pe.literal("PAGE_CHECK"),substring:pe.string()}),cd=pe.object({cacheInvalidation:pe.discriminatedUnion("type",[h_,g_]).optional()}),Yt=pe.object({moduleId:pe.string().uuid(),name:pe.string(),description:pe.string().nullish(),enabled:pe.boolean().nullish(),parameters:pe.string().array().nullish(),defaultParameters:pe.record(pe.string(),pe.string()).nullish(),parameterEnums:pe.record(pe.string(),pe.string().array()).nullish(),defaultCacheKey:pe.string().nullish(),defaultCacheTtl:pe.number().nullish(),defaultCacheAllInvocations:pe.boolean().nullish(),autoAuth:pe.boolean().nullish(),advanced:cd.nullish()});import{z as Xt}from"zod";var _f=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(_f||{});var f_=Xt.discriminatedUnion("type",[Xt.object({type:Xt.literal("NAVIGATE_URL"),url:Xt.string().url()}),Xt.object({type:Xt.literal("GO_TO_SECTION_START")})]),S_=Xt.object({trigger:Xt.nativeEnum(_f).optional(),attempts:Xt.number().int().optional(),restartBehavior:f_}),ta=qt.extend({type:Xt.literal("SECTION"),description:Xt.string().describe("user provided goal of what the section should accomplish"),plan:Xt.string().array().optional(),autohealingConfig:S_.optional()});var Pf=Yt.merge(ld).extend({type:It.literal("RESOLVED_MODULE"),steps:It.lazy(()=>it.array())}),ud=Yt.extend({steps:It.lazy(()=>it.array())}),dd=ta.extend({steps:It.lazy(()=>Ot.array())}),y_=ta.extend({steps:It.lazy(()=>it.array())}),No=sd.extend({blocks:It.object({assertion:It.lazy(()=>Kt),steps:It.lazy(()=>Ot.array())}).array(),elseSteps:It.lazy(()=>Ot.array().optional())}),b_=sd.extend({blocks:It.object({assertion:It.lazy(()=>Kt),steps:It.lazy(()=>it.array())}).array(),elseSteps:It.lazy(()=>it.array().optional())}),Ot=It.discriminatedUnion("type",[Kt,Hn,Lo,$r,No,dd]),it=It.discriminatedUnion("type",[Kt,Hn,Lo,Pf,b_,y_]);import{z as Jt}from"zod";var E_=Jt.object({steps:Ot.array(),beforeSteps:Ot.array().nullish(),afterSteps:Ot.array().nullish()}),Gn=Jt.object({steps:it.array(),beforeSteps:it.array().nullish(),afterSteps:it.array().nullish()}),Vn=Jt.object({steps:Jt.record(Jt.string(),Jt.unknown()).array(),beforeSteps:Jt.record(Jt.string(),Jt.unknown()).array().nullish(),afterSteps:Jt.record(Jt.string(),Jt.unknown()).array().nullish()});var ln="1.0.21",md="0.0.1";import{z as Tt}from"zod";import{z as Wn}from"zod";var T_=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,qr=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 Do=Wn.string().min(1).max(255).superRefine((r,e)=>{try{ra(r)}catch(t){return e.addIssue({code:Wn.ZodIssueCode.custom,message:t.message,fatal:!0}),Wn.NEVER}});function ra(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(T_))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Gs=Wn.preprocess(r=>r===null?"":r,Wn.union([Wn.string().url(),Wn.literal("")])).optional();var v_=["AI_EXTRACT","JAVASCRIPT"],A_=Tt.object({id:Tt.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Do.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:Tt.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."),w_=Tt.object({selector:A_,inputs:Tt.record(Tt.string()).or(Tt.null())}),Pq=Tt.object({type:Tt.literal("PRESET_ACTION"),action:zs,envKey:Tt.string().or(Tt.null()).describe(`key in the environment to save the result of this step to. Only use this for ${v_.join(" or ")} steps.`)}),Iq=Tt.object({type:Tt.literal("MODULE"),module:w_}),Oq=Tt.object({type:Tt.literal("AI_ACTION_DYNAMIC"),text:Tt.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var If=P.object({phrase:P.string()}),pd=P.object({thoughts:P.string().optional(),result:P.union([P.literal("NOT_FOUND"),P.string(),P.number(),P.array(P.unknown()),P.record(P.unknown(),P.unknown()),P.unknown()])}),pK=P.object({text:P.string()}),R_=P.boolean().or(P.nativeEnum(rn)).transform(r=>!(!r||r==="irrelevant")),Of=P.object({attributes:P.array(P.string()).nullish(),text:R_.nullish(),position:P.nativeEnum(rn).nullish(),shape:P.nativeEnum(rn).nullish()}),C_=P.object({id:P.number().int(),requirements:Of}),x_=C_.array(),Lf=P.object({thoughts:P.string(),review:P.string().optional(),id:P.number().int(),updatedMemory:ku.optional(),requirements:Of.nullish().transform(r=>{if(r!==null)return r}),additionalElements:x_.nullish().transform(r=>{if(r!==null)return r})});var gd=(p=>(p.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",p.FEW_WORDS="FEW_WORDS",p.STYLE_TAG="STYLE_TAG",p.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",p.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",p.NONE="NONE",p.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",p.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",p.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",p.PREFER_ASSERTION="PREFER_ASSERTION",p.HTML_ELEMENTS="HTML_ELEMENTS",p.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",p.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",p))(gd||{}),Nf=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(Nf||{});var Df=P.object({thoughts:P.string(),category:P.nativeEnum(gd)}),kf=P.object({thoughts:P.string(),category:P.nativeEnum(Nf)}),M_=P.discriminatedUnion("op",[P.object({op:P.literal("replace"),path:P.string(),value:P.string()}),P.object({op:P.literal("add"),path:P.string(),value:P.string()}),P.object({op:P.literal("remove"),path:P.string()})]),gK=P.object({thoughts:P.string(),patches:M_.array()}),__=[P.literal("add"),P.literal("replace"),P.literal("remove")],P_=P.object({op:P.union(__),path:P.string(),value:it.optional()}),Uf=P.object({patches:P_.array(),thoughts:P.string()}),Ff=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(Ff||{}),Bf=P.object({thoughts:P.string(),scenario:P.nativeEnum(Ff),instructions:P.string().nullish()}),zf=P.object({reasoning:P.string(),scenario:P.string(),patch:P.null().optional()}),hK=P.object({thoughts:P.string(),evaluation:P.number().min(0).max(10)}),fK=P.object({observations:P.string(),reasoning:P.string(),command:Is});var hd=P.object({summary:P.string(),reasoning:P.string(),evaluation:P.discriminatedUnion("type",[P.object({type:P.literal("DONE")}),P.object({type:P.literal("RIGHT_TRACK")}),P.object({type:P.literal("WRONG_TRACK"),feedback:P.string()}),P.object({type:P.literal("IMPOSSIBLE")})])}),I_=P.object({startId:P.number().int(),endId:P.number().int()}),Hf=(n=>(n.SIMPLE_CONTENT_BASED_LOCATOR="SIMPLE_CONTENT_BASED_LOCATOR",n.SIMPLE_CONTENT_BASED_ASSERTION="SIMPLE_CONTENT_BASED_ASSERTION",n.OTHER="OTHER",n))(Hf||{}),Gf=P.object({categoryThoughts:P.string(),category:P.nativeEnum(Hf),relevantSections:I_.array()}),Kr=P.boolean().nullish().transform(r=>r??!1),Vf=P.object({thoughts:P.string().optional(),isPageReady:Kr,descriptionLabels:P.object({usesTextContent:Kr,usesAppearance:Kr,usesPosition:Kr,usesRelativeElements:Kr,usesSingleQuotes:Kr,isAmbiguous:Kr,targetDoesNotExist:Kr,usesIcon:Kr}).optional()});import{z as _}from"zod";import*as re from"zod";var vK=re.object({thoughts:re.string().optional().describe("only provided if a description was provided"),target:on.optional().describe("only provided if a description was provided"),pageState:re.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:re.object({label:re.string(),value:re.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:re.object({data:re.string(),height:re.number().int(),width:re.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Wf=re.union([re.literal("ELEMENT_CHECK"),re.literal("NEGATED_CHECK"),re.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),re.literal("SELECT_OPTION"),re.literal("TYPE")]);function na(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 oa=(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))(oa||{}),ko=re.object({matched:re.boolean(),reason:re.string().optional().describe("Human understandable description"),logs:re.string().array().optional().describe("Logs for debugging")}),O_=ko.extend({type:re.literal("USER_SELECTOR")}),L_=ko.extend({type:re.literal("CSS_SELECTOR"),selectors:re.string().array()}),N_=ko.extend({type:re.literal("HYBRID_SELECTOR")}),D_=ko.extend({type:re.literal("HTML_DISTANCE"),distance:re.number().optional(),closestElement:re.string().optional(),savedElement:re.string().optional()}),k_=ko.extend({type:re.literal("TEMPLATE_MATCHING"),elementImageUrl:re.string().url()}),U_=ko.extend({type:re.literal("AUTO_FRAME"),logs:re.string().array().optional()}),jf=re.discriminatedUnion("type",[O_,L_,N_,D_,k_,U_]);import{z as la}from"zod";import{z as K_}from"zod";import*as V from"zod";import{extendZodWithOpenApi as z_}from"zod-openapi";import{cloneDeep as LK}from"lodash-es";import DK from"truncate-json";import*as qn from"zod";import{extendZodWithOpenApi as B_}from"zod-openapi";import{z as vt}from"zod";import{z as se}from"zod";var fd=se.object({autoFollowNewTabs:se.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:se.union([se.boolean(),se.literal("inputs-only")]).optional(),ignoreHrefForCaching:se.boolean().optional(),disableSecondaryCacheResolution:se.boolean().optional(),hybridSelectorMode:se.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:se.union([se.boolean(),se.literal("always")]).optional(),visualActions:se.boolean().optional(),autoExpandIframes:se.boolean().optional(),disableHtmlSnapshots:se.boolean().optional(),importantAttributes:se.string().array().optional(),importantClasses:se.string().array().optional(),importantStyles:se.string().array().optional()});var $f=1e4,qf=6e4,F_=se.object({server:se.string(),username:se.string().optional(),password:se.string().optional()}),jn=fd.extend({pageLoadTimeoutMs:se.number().optional().refine(r=>r===void 0||r<=qf&&r>=-1,{message:`Page load timeout must be between 0 and ${qf/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:se.number().optional().refine(r=>r===void 0||r<=$f&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${$f/1e3} seconds`}),localChromeExtensionPaths:se.string().array().optional(),extraHeaders:se.record(se.string(),se.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:se.record(se.string(),se.record(se.string(),se.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:se.string().optional(),disableGpu:se.boolean().optional(),disableBrowserMonitoring:se.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),bustCacheOnBoundingBoxChange:se.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:se.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:se.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:F_.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency.")});var Sd="BASE_URL";var $n="ENV_NAME",Uo="TEST_NAME",MK={[Sd]:"https://www.google.com"},Kf=vt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Yf=vt.object({name:vt.string(),variables:vt.record(vt.string().describe("variable name"),vt.string().describe("variable value"))}),Xf=vt.object({name:vt.string(),variables:vt.record(vt.string().describe("variable name"),vt.unknown().describe("variable value")),browser:jn.optional()});var _K=vt.object({name:vt.string(),variables:vt.record(vt.string().describe("variable name"),vt.unknown().describe("variable value"))});B_(qn);var yd=qn.object({env:qn.record(qn.unknown())}).openapi({ref:"TestContextSnapshot"});var We=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(We||{}),bd=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(bd||{});z_(V);var Ed=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()}),H_=Ed.extend({viewport:V.object({height:V.number(),width:V.number()}).nullish(),status:V.nativeEnum(bd),message:V.string().optional(),elementInteracted:V.string().optional()}),Kn=Ed.extend({status:V.nativeEnum(We),message:V.string().optional(),data:V.unknown().optional(),beforeTestContext:yd.optional(),afterTestContext:yd.optional(),failureReason:V.nativeEnum(ve).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"}),Jf=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(Jf||{}),Vs=Kn.merge(Kt).extend({results:H_.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(()=>lt.array()).optional(),failureRecoveryStatus:V.object({type:V.nativeEnum(Jf),message:V.string()}).optional()}),G_=Kn.merge(Hn).extend({results:V.lazy(()=>Vs.array()),previousAttempts:V.lazy(()=>lt.array()).optional()}),V_=Kn.merge(Lo).extend({results:V.lazy(()=>Vs.array()),previousAttempts:V.lazy(()=>lt.array()).optional()}),W_=Kn.merge($r).extend({moduleName:V.string().optional(),results:V.lazy(()=>lt.array()),previousAttempts:V.lazy(()=>lt.array()).optional()}),j_=Kn.merge(No).extend({assertionResult:Vs.optional(),results:V.lazy(()=>lt.array()).describe("results for the block actually executed"),previousAttempts:V.lazy(()=>lt.array()).optional()}),$_=Kn.merge(ta).extend({results:V.lazy(()=>lt.array()),healingAttempts:V.lazy(()=>lt.array().array()).optional(),previousAttempts:V.lazy(()=>lt.array()).optional()}),lt=V.discriminatedUnion("type",[G_,V_,Vs,W_,j_,$_]),JK=Kn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),q_=Ed.extend({index:V.number().optional(),description:V.string(),pageState:V.string().optional(),elementInteracted:V.string().optional(),startedAt:V.coerce.date().or(V.string()).optional().catch(void 0),finishedAt:V.coerce.date().or(V.string()).optional().catch(void 0)}),Ws=q_.extend({beforeScreenshot:V.string().optional(),afterScreenshot:V.string().optional()});var Td=K_.object({results:lt.array().describe("main results"),beforeResults:lt.array().optional(),afterResults:lt.array().optional()}),ia=Td.partial();import{z as F}from"zod";import{extendZodWithOpenApi as tP}from"zod-openapi";var Fo=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Fo||{});import{isValidCron as Y_}from"cron-validator";import{z as ne}from"zod";import{z as vd}from"zod";var cn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(cn||{});var js=vd.object({width:vd.number().min(200).max(1e4),height:vd.number().min(200).max(1e4)}),Zf={"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}},o2=Object.keys(Zf);var un=Zf["Desktop Large"],Qf="en-us",eS="America/Los_Angeles";var $s={latitude:37.7749,longitude:-122.4194};var tS=["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 rS=1e4,X_=jn.extend({browserType:ne.nativeEnum(cn).optional(),slowMoMs:ne.number().optional().refine(r=>r===void 0||r<=rS&&r>=-1,{message:`Slow motion must be between 0 and ${rS} milliseconds`}),basicAuthorization:ne.object({username:ne.string().optional(),password:ne.string().optional()}).optional(),geolocation:ne.object({latitude:ne.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ne.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ne.boolean().optional(),locale:ne.string().optional(),timezone:ne.enum(tS).optional(),colorScheme:ne.enum(["light","dark"]).optional()});var Ad=ne.object({useMemory:ne.boolean().optional(),failureRecovery:ne.boolean().optional().describe("undefined means inherit org settings")}),J_=Ad.extend({disableAICaching:ne.boolean().optional(),failureRecoveryInstructions:ne.string().optional()}),Z_=ne.object({viewport:js.optional()}),aa=Z_.merge(J_).merge(X_),Bo=ne.object({cron:ne.string().refine(r=>Y_(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ne.boolean().default(!1),env:ne.string().optional(),timeZone:ne.string().default("America/Los_Angeles"),jobKey:ne.string().optional()}),zo=ne.object({onSuccess:ne.boolean().default(!1),failureMessage:ne.string().optional(),onFailure:ne.boolean().default(!0),successMessage:ne.string().optional()}),Q_=ne.object({name:ne.string(),required:ne.boolean().optional(),defaultValue:ne.string().describe("this is not optional because we need a value when the editor is first loaded")}),qs=Q_.array(),eP=ne.object({name:ne.string(),value:ne.string()}),nS=eP.array(),Ks=ne.object({name:ne.string(),default:ne.boolean().optional(),fixtures:Kf.array().optional()});tP(F);var Zt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},we=(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))(we||{}),Ys=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Ys||{});var Qe=F.string().pipe(F.coerce.date()).or(F.date()),sa=F.object({id:F.string(),runKey:F.string(),organizationId:F.string(),executionType:F.nativeEnum(Fo).optional().default("WEB"),createdAt:Qe,createdBy:F.string(),flake:F.boolean().nullish(),scheduledAt:Qe.or(F.null()),startedAt:Qe.or(F.null()),updatedAt:Qe.nullish(),finishedAt:Qe.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(Ys).nullish(),status:F.nativeEnum(we),trigger:F.nativeEnum(Zt),attempts:F.number(),runAttempts:F.array(F.object({id:F.string(),status:F.nativeEnum(we),startedAt:Qe.or(F.null()),finishedAt:Qe.or(F.null())})).optional(),videos:F.array(F.string()).optional(),failureReason:F.nativeEnum(ve).nullish(),failureDetails:Us.nullish(),failureRecoveryDetails:F.record(F.string(),F.unknown()).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"}),rP={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Xs=sa.pick({...rP,test:!0}),oS=sa.omit({failureReason:!0,failureDetails:!0,test:!0}),wd=sa.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:aa.nullish()}).nullish()}).merge(Td);var nP=la.object({id:la.string().uuid(),startedAt:Qe.or(la.null()),finishedAt:Qe.or(la.null()),status:la.nativeEnum(we)}).merge(ia),C2=nP.array();import{z as et}from"zod";var oP=et.object({id:et.string(),status:et.nativeEnum(we),trigger:et.nativeEnum(Zt),createdAt:Qe,startedAt:Qe.nullish(),finishedAt:Qe.nullish(),gitCommitSha:et.string().nullish(),gitCommitShaShort:et.string().nullish(),gitCommitTimestamp:Qe.nullish(),gitBranchName:et.string().nullish(),gitOriginUrl:et.string().nullish(),gitCommitMessage:et.string().nullish(),gitCommitAuthorName:et.string().nullish(),githubRepository:et.string().nullish(),gitlabProjectPath:et.string().nullish(),pipelineId:et.string().nullish(),cliVersion:et.string().nullish(),labels:et.string().array().optional(),suite:et.object({id:et.string(),name:et.string()}).nullish(),runs:et.object({status:et.nativeEnum(we)}).array()}).openapi({ref:"RunGroup"}),iS=oP.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Xs.array()});import{z as ct}from"zod";var iP=ct.object({type:ct.literal("TARGETING"),name:ct.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:jf.array(),pageState:ct.string().optional(),targetSource:ct.nativeEnum(nn).optional(),targetUpdateTime:ct.string().optional()}),aP=ct.object({type:ct.literal("AI_LOCATION"),matched:ct.boolean(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional(),thoughts:ct.string().optional()}),sP=ct.object({type:ct.literal("ASSERTION"),relevantElementsSerialized:ct.string().array().optional(),pageState:ct.string().optional(),ragUsed:ct.boolean().optional()}),lP=ct.discriminatedUnion("type",[iP,aP,sP]);import{z as Ye}from"zod";var cP=Ye.object({id:Ye.string(),name:Ye.string()}),z2=cP.merge(Ye.object({createdAt:Qe,createdBy:Ye.string(),schedule:Bo,notification:zo,environment:Ye.object({name:Ye.string()}).nullish(),beforeTests:Ye.object({id:Ye.string()}).array().nullish(),afterTests:Ye.object({id:Ye.string()}).array().nullish()})),aS=Ye.object({id:Ye.string().uuid(),orgId:Ye.string(),createdAt:Qe,startedAt:Qe.or(Ye.null()),finishedAt:Qe.or(Ye.null()),status:Ye.nativeEnum(we),trigger:Ye.nativeEnum(Zt),suite:Ye.object({id:Ye.string(),name:Ye.string()}).nullish(),runs:sa.array()}),H2=aS.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),sS=aS.extend({runs:Xs.array()});import{z as Qt}from"zod";import{cloneDeep as W2}from"lodash-es";import{z as Ee}from"zod";var X2=Ee.object({thoughts:Ee.string(),subGoals:Ee.object({instruction:Ee.string()}).array()}),J2=Ee.object({thoughts:Ee.string(),newPlanMarkdown:Ee.string()}),Z2=Ee.object({thoughts:Ee.string(),correct:Ee.boolean(),failedActionIndex:Ee.number().optional()}),uP=Ee.object({type:Ee.literal("PLANNING"),beforePlan:Ee.string(),goalDecision:Ee.string(),thoughts:Ee.string()}),dP=Ee.object({type:Ee.literal("RUNNING"),stepDisplayName:Ee.string(),status:Ee.nativeEnum(We),results:lt.array()}),mP=Ee.object({type:Ee.literal("REVISING"),beforePlan:Ee.string(),afterPlan:Ee.string(),errString:Ee.string(),diffs:Ee.string(),thoughts:Ee.string()}),pP=Ee.object({type:Ee.literal("SYSTEM"),message:Ee.string()}),gP=Ee.discriminatedUnion("type",[uP,dP,mP,pP]),lS=gP.array();var nY=Qt.object({id:Qt.string(),scheduledAt:Qt.coerce.date().nullable(),startedAt:Qt.coerce.date().nullable(),finishedAt:Qt.coerce.date().nullable(),status:Qt.nativeEnum(we),history:lS.nullable(),testPlan:Qt.object({id:Qt.string(),name:Qt.string()}).nullable(),test:Qt.object({id:Qt.string(),name:Qt.string()}).nullable()});import{z as Lt}from"zod";var Rd=Lt.object({content:Lt.string(),ids:Lt.string().array(),tokenLength:Lt.number()}),hP=Lt.object({chunks:Rd.array()}),EY=Lt.object({ids:Lt.string().array(),score:Lt.number(),tokenLength:Lt.number()}),TY=hP.extend({description:Lt.string().describe("Input to pass to RAG engine"),tokenLimit:Lt.number()}),cS=Lt.object({ids:Lt.number().array()}),uS=Lt.object({indices:Lt.number().array()});var pt=_.object({disableCache:_.boolean().optional(),useMemory:_.boolean().optional(),clientMode:_.enum(["interactive","runner"]).optional(),loggerTags:_.record(_.string(),_.string()).optional(),langfuseSessionId:_.string().optional(),agentConfigVersion:_.string().optional()}),_Y=pt.extend({chunks:Rd.array(),description:_.string().describe("Input to pass to AI"),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),softTokenLimit:_.number(),hardTokenLimit:_.number(),callId:_.string().optional()}),fP=_.object({screenshotBase64AfterCommand:_.string(),urlAfterCommand:_.string(),serializedCommand:_.string(),elementInteracted:_.string().optional(),thoughts:_.string().optional()}),dS=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),source:Wf.optional().catch(void 0),memory:_.discriminatedUnion("type",[Rs,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional()}),mS=_.object({target:_.string().or(_.number()),browserState:_.string().optional(),screenshot:_.string().optional(),boundingBox:_.object({x:_.number(),y:_.number(),height:_.number(),width:_.number()}).optional()}),pS=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string().optional(),returnSchema:_.string().optional()}),SP=_.literal("NEGATED_CHECK"),gS=_.object({goal:_.string(),browserState:_.string(),screenshot:_.string(),url:_.string(),contextChoice:Wu.optional(),memory:_.discriminatedUnion("type",[Bu,_.object({type:_.literal("RESOLVED_TRACES"),traces:_.unknown().array()})]).optional(),source:SP.optional()}),hS=_.object({command:Po}),fS=_.object({message:_.string()}),Cd=_.object({goal:_.string(),browserState:_.string(),startingScreenshot:_.string().optional(),screenshot:_.string(),url:_.string(),history:fP.array(),actionHint:_.string().optional(),lastError:_.string().optional()}),SS=_.object({results:Ws.array(),errorMessage:_.string(),errorStack:_.string().optional()}),yS=_.object({results:Ws.array(),goal:_.string(),errorMessage:_.string()}),bS=_.object({failedResults:Ws.array(),nextStepsSerialized:_.string().array(),currentUrl:_.string(),currentPageState:_.string(),currentScreenshot:_.string(),customInstructions:_.string().optional(),testDescription:_.string().optional()}),PY=_.object({description:_.string(),type:_.union([_.literal("locator"),_.literal("assertion"),_.literal("ai-action")]),excerpt:_.string()}),ES=_.object({type:_.string(),browserContext:_.string(),currentStep:_.string(),screenshot:_.string()}),TS=_.object({description:_.string(),browserState:_.string(),screenshot:_.string()});import{z as ca}from"zod";var LY=ca.object({goal:ca.string()}),vS=ca.object({keywords:ca.array(ca.string())});import{z as xd}from"zod";var Js=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Js||{}),kY=xd.nativeEnum(Js),yP=xd.enum(["v1","v2"]),UY=yP.or(xd.string().describe("for people with special configurations"));var AS={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v2"};import{z as ke}from"zod";var wS=ke.object({attributesRequired:ke.array(ke.string()).optional(),textRequired:ke.boolean().optional(),boundsRequired:ke.boolean().optional()}),RS=ke.object({id:ke.number(),thoughts:ke.string(),inWebview:ke.boolean().optional(),requirements:wS.optional(),additionalElements:ke.object({id:ke.number(),requirements:wS}).array().optional()}),CS=ke.object({description:ke.string(),screenXml:ke.string(),screenshot:ke.string()}),xS=ke.object({assertion:ke.string(),screenXml:ke.string(),screenshot:ke.string()}),MS=ke.object({thoughts:ke.string(),result:ke.boolean(),relevantElements:ke.array(ke.number()).optional()});import{z as Yn}from"zod";var _S=Yn.object({id:Yn.string().uuid(),skipped:Yn.boolean().optional(),envKey:Yn.string().optional().describe("key in the environment to save the result of this step to")}),Md=_S.merge(vo).extend({type:Yn.literal("REQUEST")}),_d=_S.merge(xs).extend({type:Yn.literal("JAVASCRIPT")}),Pd=Yn.discriminatedUnion("type",[_d,Md]);import{z as er}from"zod";var PS=er.object({id:er.string(),name:Do,description:er.string().optional().nullish(),baseUrl:Gs.nullish(),schemaVersion:er.string(),advanced:er.unknown().optional(),retries:er.number(),envs:er.array(Ks).nullish(),parameters:qs.nullish()}),bP=er.object({createdAt:er.coerce.date(),updatedAt:er.coerce.date(),schedule:Bo.nullish(),notification:zo.nullish(),createdBy:er.string(),organizationId:er.string()}),EP=PS.merge(bP),sX=EP.extend({steps:Pd.array()}),lX=PS.extend({steps:Pd.array()});import{z as kt}from"zod";var IS=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date(),status:kt.nativeEnum(We),message:kt.string().optional(),data:kt.unknown().optional()}),TP=IS.merge(_d).extend({type:kt.literal("JAVASCRIPT")}),vP=IS.merge(Md).extend({type:kt.literal("REQUEST")}),AP=kt.discriminatedUnion("type",[TP,vP]),OS=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date().nullish(),status:kt.nativeEnum(we),results:AP.array(),failureReason:kt.string().nullish(),failureDetails:Us.nullish()});import{z as Ut}from"zod";var wP=Ut.object({id:Ut.string(),organizationId:Ut.string(),createdAt:Ut.coerce.date(),updatedAt:Ut.coerce.date(),createdBy:Ut.string(),scheduledAt:Ut.coerce.date().nullish(),startedAt:Ut.coerce.date().nullish(),finishedAt:Ut.coerce.date().nullish(),status:Ut.nativeEnum(we),trigger:Ut.nativeEnum(Zt),results:OS.array().nullish(),apiTestName:Ut.string().nullish(),apiTestPath:Ut.string().nullish(),apiTestId:Ut.string().nullish()}),yX=wP.pick({status:!0,startedAt:!0,finishedAt:!0});var ua=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(ua||{}),LS=3;function RP(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Id(r){if(!RP(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 Od(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return LS;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 Zs=class{trackStepExecution(){}async flush(){}};import{parseString as CP,splitCookiesString as xP}from"set-cookie-parser";import{z as Ae}from"zod";var Ld=Ae.object({name:Ae.string(),value:Ae.string(),url:Ae.string().optional(),domain:Ae.string().optional(),path:Ae.string().optional(),expires:Ae.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Ae.boolean().optional(),secure:Ae.boolean().default(!0),sameSite:Ae.union([Ae.literal("Strict"),Ae.literal("Lax"),Ae.literal("None")]).default("None")});function Qs(r,e){let t=[],n=xP(r);for(let o of n){let i=CP(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=Ld.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 MP=Ae.object({origin:Ae.string(),localStorage:Ae.array(Ae.object({name:Ae.string(),value:Ae.string()}))}),_P=Ae.object({entries:Ae.record(Ae.string(),Ae.array(Ae.tuple([Ae.unknown(),Ae.unknown()]))),version:Ae.number().optional()}),NS=Ae.object({cookies:Ld.array().optional(),origins:MP.array().optional(),idb:Ae.record(Ae.string(),_P).optional().describe("key is db name")});function el(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Ld.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 nl}from"uuid";import Ue from"zod";import{v4 as HX}from"uuid";import{z}from"zod";import*as G from"zod";var DS=G.discriminatedUnion("type",[G.object({type:G.literal("SCREEN")}),G.object({type:G.literal("OPEN_APP")}),G.object({type:G.literal("OPEN_WEBVIEW")})]),da=G.object({type:G.literal("description"),description:G.string()}),kS=G.object({type:G.literal("CUSTOM_COORDINATES"),startX:G.number().describe("Starting X coordinate in pixels"),startY:G.number().describe("Starting Y coordinate in pixels"),deltaPixels:G.number().describe("Number of pixels to scroll in the specified direction")}),Nd=G.discriminatedUnion("type",[...DS.options,G.object({type:G.literal("CUSTOM"),target:da}),kS]);var PP=G.object({type:G.literal("coordinates"),xPercent:G.number(),yPercent:G.number()}),Dd=G.discriminatedUnion("type",[da,PP]),US=G.object({requiredText:G.string().optional(),requiredAttributes:G.record(G.string(),G.string()).optional(),requiredBounds:G.boolean().optional()}),IP=G.object({xPath:G.string(),requirements:US.optional()}),OP=G.object({type:G.literal("CUSTOM"),target:da,cache:G.lazy(()=>FS).optional()}),LP=G.object({pixelDelta:G.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:G.union([DS,OP,kS]),direction:G.enum(["up","down"])}),FS=G.object({type:G.literal("NATIVE"),bounds:G.number().array(),resolvedDescription:G.string(),xPath:G.string(),elementOnlySerializedXml:G.string(),scrollDetails:LP.optional(),requirements:US.optional(),requiredRelatedElements:IP.array().optional()}),NP=G.object({type:G.literal("WEBVIEW"),resolvedDescription:G.string(),xPath:G.string(),browserCache:on.optional()}),tl=G.union([FS,NP]);var dn=(b=>(b.AI_CHECK="AI_CHECK",b.TAP="TAP",b.TYPE="TYPE",b.PRESS="PRESS",b.PRESS_KEYBOARD="PRESS_KEYBOARD",b.OPEN_APP="OPEN_APP",b.KILL_APP="KILL_APP",b.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",b.SWIPE="SWIPE",b.SCROLL_TO="SCROLL_TO",b.SCREEN_CHECK="SCREEN_CHECK",b.JAVASCRIPT="JAVASCRIPT",b.REQUEST="REQUEST",b.WAIT="WAIT",b.ADD_FILE="ADD_FILE",b.INSTALL_APP="INSTALL_APP",b.ADB="ADB",b.STATE="STATE",b))(dn||{}),ma=(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))(ma||{}),kd=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(kd||{}),DP=z.object({updatedAt:z.coerce.date().optional()}),ut=z.object({id:z.string().uuid(),disableCache:z.boolean().optional()}),kP=ut.extend({type:z.literal("STATE")}),UP=ut.extend({type:z.literal("KILL_APP")}),rl=DP.extend({target:tl}),FP=ut.extend({type:z.literal("AI_CHECK"),assertion:z.string(),timeoutSecs:z.number().optional()}),Ud=ut.extend({type:z.literal("TAP"),target:Dd,cache:rl.optional(),longPress:z.boolean().optional(),longPressDurationMs:z.number().optional(),doubleTap:z.boolean().optional(),doubleTapDelayMs:z.number().optional(),relativePosition:z.object({x:z.number(),y:z.number()}).optional()}),Fd=ut.extend({type:z.literal("TYPE"),target:Dd.optional(),cache:rl.optional(),keyPressDelayMs:z.number().optional(),text:z.string(),clearContent:z.boolean().optional(),forceClearContent:z.boolean().optional()});var BP=ut.extend({type:z.literal("PRESS"),key:z.nativeEnum(ma),longPress:z.boolean().optional()}),zP=ut.extend({type:z.literal("PRESS_KEYBOARD"),key:z.nativeEnum(kd)}),HP=ut.extend({type:z.literal("OPEN_APP"),packageName:z.string(),activityName:z.string().optional(),intentExtras:z.string().optional()}),GP=ut.extend({type:z.literal("OPEN_NOTIFICATION_DRAWER")}),Bd=ut.extend({type:z.literal("SWIPE"),direction:z.enum(["up","down","left","right"]),scrollableElement:Nd,cache:rl.optional(),viewportPercent:z.number().optional(),durationMs:z.number().optional()}),zd=ut.extend({type:z.literal("SCROLL_TO"),target:da,direction:z.enum(["down","up"]),scrollableElement:Nd,scrollStepPercent:z.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:rl.optional()});var VP=z.object({type:z.literal("CONTENT"),negated:z.boolean().optional(),value:z.string()}),WP=ut.extend({type:z.literal("SCREEN_CHECK"),assertion:VP,timeout:z.number().int().min(0).max($i).optional().describe("max seconds to wait for the assertion to be true")}),jP=ut.extend({type:z.literal("JAVASCRIPT"),code:z.string(),timeout:z.number().int().max(60).optional().describe("Max seconds for the code to complete")}),$P=ut.extend({type:z.literal("REQUEST")}).merge(vo),qP=ut.extend({type:z.literal("WAIT"),timeoutSecs:z.number()}),KP=ut.extend({type:z.literal("ADB"),command:z.string(),jsonArgs:z.string().optional()}),YP=ut.extend({type:z.literal("ADD_FILE"),file:z.string(),storageLocation:z.string()}),XP=z.string().trim(),JP=ut.extend({type:z.literal("INSTALL_APP"),uri:XP}),zS=z.discriminatedUnion("type",[FP,Ud,Fd,BP,HP,GP,zP,Bd,zd,WP,jP,$P,qP,YP,JP,UP,KP,kP]);var Hd=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var ZP=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 Df(r){return r instanceof Error?r.message.includes("Timeout")&&r.message.includes("exceeded")&&r.message.includes("waiting for locator"):!1}function ed(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 xr=class extends Error{retryableWithAI;constructor(e,t,n={}){super(e,n),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=t}},Fs=class extends xr{constructor(e,t={}){super(e,!0,t),this.name="BoundingBoxMovedError"}},Bs=class extends xr{constructor(e,t={}){super(e,!1,t),this.name="ZeroOpacityError"}};function td(r){return r instanceof Error?r.message.includes("Could not find attribute data-momentic-id for object"):!1}var rd="Element to be clicked has no bounding box";function kf(r){return r instanceof Error?r.message.startsWith(rd):!1}function nd(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 od(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 ea=class extends Error{constructor(e,t={}){super(e,t),this.name="InsufficientCacheDataError"}};var JM={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."};$u.options.forEach(r=>{let e=r.shape.type.value;if(e!=="SUCCESS"&&!JM[e])throw new Error(`Command type ${e} is missing a description`)});var Uf=v.object({type:v.literal("CLICK"),description:v.string().describe("Description of the element to click in the Current Page. Never click on <select> elements, see SELECT_OPTION."),doubleClick:v.boolean().or(v.null()),rightClick:v.boolean().or(v.null())}),Ff=v.object({type:v.literal("TYPE"),description:v.string().describe("Description of the element to type into, which must be an <input>, <textarea>, or contenteditable element."),text:v.string().describe("The text to enter, truncated to 500 characters. If the PM provided text in the goals, use it exactly without modification."),pressEnter:v.boolean().or(v.null()).describe("Press enter after typing (useful for form submissions)."),clearContent:v.boolean().describe("Clear existing content before typing. Disable to append to the existing text.")}),Bf=v.object({type:v.literal("GO_BACK")}),ZM=v.object({type:v.literal("GO_FORWARD")}),QM=v.object({type:v.literal("LOCAL_STORAGE"),key:v.string().describe("The localStorage key to set or get."),value:v.string().describe("The value to store in localStorage. If reading, this can be empty.")}),zf=v.object({type:v.literal("PRESS"),keys:v.array(v.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.')}),Hf=v.object({type:v.literal("SELECT_OPTION"),description:v.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:v.discriminatedUnion("type",[v.object({type:v.literal("VALUE"),value:v.string()}),v.object({type:v.literal("LABEL"),label:v.string()}),v.object({type:v.literal("INDEX"),index:v.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.")}),Gf=v.object({type:v.literal("NAVIGATE"),url:v.string().describe("The URL to navigate to. Only navigate to URLs relevant to the user goal.")}),Vf=v.object({type:v.literal("SCROLL"),y:v.number().describe("Scroll up or down by the specified pixels. Positive values scroll down.")}),jf=v.object({type:v.literal("WAIT"),timeout:v.number().describe("The number of seconds to wait.")}),Wf=v.object({type:v.literal("AI_ASSERTION"),assertion:v.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:v.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.")}),$f=v.object({type:v.literal("HOVER"),description:v.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.")}),e_=v.object({type:v.literal("COPY"),value:v.string().describe("The text value to copy to the browser clipboard. This should be the exact text that needs to be copied.")}),t_=v.object({type:v.literal("PASTE")}),r_=v.object({type:v.literal("REFRESH")}),n_=v.object({type:v.literal("REQUEST"),url:v.string().describe("The URL to send the HTTP request to. Can be a full URL or relative path."),method:v.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:v.record(v.string(),v.string()).or(v.null()).describe("Optional HTTP headers as key-value pairs. Common headers include 'Content-Type', 'Authorization', 'Accept', etc."),params:v.record(v.string(),v.string()).or(v.null()).describe("Optional URL query parameters as key-value pairs. These will be appended to the URL as ?key1=value1&key2=value2."),body:v.string().or(v.null()).describe("Optional request body as a string. For JSON data, stringify the object. Typically used with POST, PUT, or PATCH requests."),timeout:v.number().int().or(v.null()).describe("Optional maximum number of seconds to wait for the request to complete. Defaults to 30 seconds if not specified.")}),qf=v.object({type:v.literal("DRAG"),fromDescription:v.string().describe("Description of the element to drag. Prefer precise identifiers or text that clearly distinguishes the element."),toDescription:v.string().describe("Description of the element to drop onto. Ensure the drop target is interactable and visible."),steps:v.number().int().positive().or(v.null()).describe("Optional number of intermediate mouse move steps during the drag. Do not use this unless the user tells you to."),hoverSeconds:v.number().positive().or(v.null()).describe("Optional seconds to hover over the destination before releasing the drag.")}),o_=v.object({type:v.literal("MOUSE_DRAG"),description:v.string().or(v.null()).describe("Optional description of the element to start the drag from. If not provided, starts from current mouse position."),deltaX:v.number().describe("Number of pixels to move horizontally (positive = right, negative = left)."),deltaY:v.number().describe("Number of pixels to move vertically (positive = down, negative = up)."),steps:v.number().int().positive().or(v.null()).describe("Optional number of intermediate mouse move steps during the drag.")}),i_=v.object({type:v.literal("JAVASCRIPT"),code:v.string().describe("JavaScript code to execute. Defaults to NODE environment unless BROWSER is specified."),environment:v.union([v.literal("NODE"),v.literal("BROWSER")]).or(v.null()).describe("Execution environment. Default is NODE."),timeout:v.number().or(v.null()).describe("Max seconds for the code to complete. Max 60 seconds.")}),a_=v.object({type:v.literal("AI_EXTRACT"),goal:v.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:v.string().or(v.null()).describe("JSON schema defining the expected structure of the extracted data."),envKey:v.string().or(v.null()).describe("Environment variable name to store the extracted result in. If provided, the result will be stored and can be referenced later."),iframeUrl:v.string().or(v.null()).describe("URL or URL regex for the iframe to extract data from.")}),s_=v.object({type:v.literal("ELEMENT_CHECK"),description:v.string().describe("Description of the element to check."),assertionType:v.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:v.string().or(v.null()).describe("The value to check against (required for CONTENT assertions)."),negated:v.boolean().or(v.null()).describe("If true, asserts the opposite (e.g., does NOT exist)."),timeout:v.number().or(v.null()).describe("Max seconds to wait for the assertion to be true.")}),l_=v.object({type:v.literal("PAGE_CHECK"),value:v.string().describe("The text content to check for on the page."),negated:v.boolean().or(v.null()).describe("If true, checks that the content is NOT present."),timeout:v.number().or(v.null()).describe("Max seconds to wait for the assertion to be true.")}),c_=v.object({type:v.literal("NEW_TAB"),url:v.string().describe("The URL to open in the new tab.")}),u_=v.object({type:v.literal("WAIT_FOR_URL"),matcher:v.discriminatedUnion("type",[v.object({type:v.literal("SUBSTRING"),url:v.string()}),v.object({type:v.literal("GLOB"),glob:v.string()}),v.object({type:v.literal("REGEX"),regex:v.string()}),v.object({type:v.literal("DOMAIN"),domain:v.string()})]).describe("How to match the URL."),caseInsensitive:v.boolean().or(v.null()),negated:v.boolean().or(v.null()).describe("Wait for the URL to NOT match instead."),timeout:v.number().or(v.null()).describe("Max seconds to wait for the URL.")}),id=v.object({type:v.literal("SUCCESS")}),ad=v.object({type:v.literal("FAILURE")}),Kf=v.discriminatedUnion("type",[Uf,Ff,zf,Hf,Gf,Vf,jf,Wf,$f,Bf]),d_=v.discriminatedUnion("type",[...Kf.options,qf]),zs=v.discriminatedUnion("type",[Uf,Ff,zf,Hf,Gf,Vf,jf,Wf,$f,Bf,qf,i_,s_,l_,c_,u_,a_,e_,ZM,QM,o_,t_,r_,n_]),h$=Qi(zs),f$=v.discriminatedUnion("type",[...zs.options,id,ad]),S$=Qi(v.discriminatedUnion("type",[...Kf.options,id,ad])),y$=Qi(v.discriminatedUnion("type",[...d_.options,id,ad])),b$=v.object({command:v.unknown(),thoughts:v.string()});import{z as sd}from"zod";import{extendZodWithOpenApi as g_}from"zod-openapi";import{z as Yf}from"zod";import{extendZodWithOpenApi as p_}from"zod-openapi";import{z as Hn}from"zod";var Kt=Hn.object({index:Hn.number().optional().describe("global index within a test (in-order traversal)"),id:Hn.string(),skipped:Hn.boolean().optional(),envKey:Hn.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Hn.boolean().optional(),retries:Hn.number().optional()});p_(Yf);var m_=Kt.extend({type:Yf.literal("PRESET_ACTION")}),Yt=m_.extend({command:Lo}).openapi({ref:"PresetAction"});g_(sd);var Gn=Kt.extend({type:sd.literal("AI_ACTION"),text:sd.string(),steps:Yt.array().optional()}).openapi({ref:"AIAction"});import{z as It}from"zod";import{z as Hs}from"zod";import{extendZodWithOpenApi as h_}from"zod-openapi";h_(Hs);var ko=Kt.extend({type:Hs.literal("AI_ACTION_DYNAMIC"),text:Hs.string(),retries:Hs.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Xf}from"zod";var ld=Kt.extend({type:Xf.literal("CONDITIONAL"),skipped:Xf.boolean().optional()});import{z as pe}from"zod";var f_=pe.object({cacheKey:pe.string(),cacheExpiryMs:pe.number()}),cd=Kt.extend({id:pe.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:pe.record(pe.string()).optional(),cacheConfig:f_.optional()}),$r=cd.extend({type:pe.literal("MODULE"),moduleId:pe.string().uuid()}),S_=pe.union([$r.pick({type:!0,moduleId:!0}),pe.record(pe.unknown())]),y_=pe.object({type:pe.literal("URL_REGEX"),regex:pe.string()}),b_=pe.object({type:pe.literal("PAGE_CHECK"),substring:pe.string()}),ud=pe.object({cacheInvalidation:pe.discriminatedUnion("type",[b_,y_]).optional()}),Xt=pe.object({moduleId:pe.string().uuid(),name:pe.string(),description:pe.string().nullish(),enabled:pe.boolean().nullish(),parameters:pe.string().array().nullish(),defaultParameters:pe.record(pe.string(),pe.string()).nullish(),parameterEnums:pe.record(pe.string(),pe.string().array()).nullish(),defaultCacheKey:pe.string().nullish(),defaultCacheTtl:pe.number().nullish(),defaultCacheAllInvocations:pe.boolean().nullish(),autoAuth:pe.boolean().nullish(),advanced:ud.nullish()});import{z as Jt}from"zod";var Jf=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Jf||{});var E_=Jt.discriminatedUnion("type",[Jt.object({type:Jt.literal("NAVIGATE_URL"),url:Jt.string().url()}),Jt.object({type:Jt.literal("GO_TO_SECTION_START")})]),T_=Jt.object({trigger:Jt.nativeEnum(Jf).optional(),attempts:Jt.number().int().optional(),restartBehavior:E_}),ta=Kt.extend({type:Jt.literal("SECTION"),description:Jt.string().describe("user provided goal of what the section should accomplish"),plan:Jt.string().array().optional(),autohealingConfig:T_.optional()});var Zf=Xt.merge(cd).extend({type:It.literal("RESOLVED_MODULE"),steps:It.lazy(()=>at.array())}),dd=Xt.extend({steps:It.lazy(()=>at.array())}),pd=ta.extend({steps:It.lazy(()=>Ot.array())}),v_=ta.extend({steps:It.lazy(()=>at.array())}),Uo=ld.extend({blocks:It.object({assertion:It.lazy(()=>Yt),steps:It.lazy(()=>Ot.array())}).array(),elseSteps:It.lazy(()=>Ot.array().optional())}),A_=ld.extend({blocks:It.object({assertion:It.lazy(()=>Yt),steps:It.lazy(()=>at.array())}).array(),elseSteps:It.lazy(()=>at.array().optional())}),Ot=It.discriminatedUnion("type",[Yt,Gn,ko,$r,Uo,pd]),at=It.discriminatedUnion("type",[Yt,Gn,ko,Zf,A_,v_]);import{z as Zt}from"zod";var w_=Zt.object({steps:Ot.array(),beforeSteps:Ot.array().nullish(),afterSteps:Ot.array().nullish()}),Vn=Zt.object({steps:at.array(),beforeSteps:at.array().nullish(),afterSteps:at.array().nullish()}),jn=Zt.object({steps:Zt.record(Zt.string(),Zt.unknown()).array(),beforeSteps:Zt.record(Zt.string(),Zt.unknown()).array().nullish(),afterSteps:Zt.record(Zt.string(),Zt.unknown()).array().nullish()});var ln="1.0.21",md="0.0.1";import{z as vt}from"zod";import{z as Wn}from"zod";var R_=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,qr=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 Fo=Wn.string().min(1).max(255).superRefine((r,e)=>{try{ra(r)}catch(t){return e.addIssue({code:Wn.ZodIssueCode.custom,message:t.message,fatal:!0}),Wn.NEVER}});function ra(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(R_))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Gs=Wn.preprocess(r=>r===null?"":r,Wn.union([Wn.string().url(),Wn.literal("")])).optional();var C_=["AI_EXTRACT","JAVASCRIPT"],x_=vt.object({id:vt.string().optional().describe("Recommended way of selecting an entity. The id of the entity to resolve."),name:Fo.optional().describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),path:vt.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."),M_=vt.object({selector:x_,inputs:vt.record(vt.string()).or(vt.null())}),Nq=vt.object({type:vt.literal("PRESET_ACTION"),action:zs,envKey:vt.string().or(vt.null()).describe(`key in the environment to save the result of this step to. Only use this for ${C_.join(" or ")} steps.`)}),Dq=vt.object({type:vt.literal("MODULE"),module:M_}),kq=vt.object({type:vt.literal("AI_ACTION_DYNAMIC"),text:vt.string().describe("The goal description for the AI action. Supports handlebars templates like {{env.VARIABLE_NAME}}.")});var Qf=I.object({phrase:I.string()}),gd=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()])}),SK=I.object({text:I.string()}),__=I.boolean().or(I.nativeEnum(rn)).transform(r=>!(!r||r==="irrelevant")),eS=I.object({attributes:I.array(I.string()).nullish(),text:__.nullish(),position:I.nativeEnum(rn).nullish(),shape:I.nativeEnum(rn).nullish()}),P_=I.object({id:I.number().int(),requirements:eS}),I_=P_.array(),tS=I.object({thoughts:I.string(),review:I.string().optional(),id:I.number().int(),updatedMemory:Uu.optional(),requirements:eS.nullish().transform(r=>{if(r!==null)return r}),additionalElements:I_.nullish().transform(r=>{if(r!==null)return r})});var hd=(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))(hd||{}),rS=(o=>(o.NONE="NONE",o.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",o.COPILOT_MISUSE="COPILOT_MISUSE",o.IRRELEVANT_MESSAGE="IRRELEVANT_MESSAGE",o))(rS||{});var nS=I.object({thoughts:I.string(),category:I.nativeEnum(hd)}),oS=I.object({thoughts:I.string(),category:I.nativeEnum(rS)}),O_=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()})]),yK=I.object({thoughts:I.string(),patches:O_.array()}),L_=[I.literal("add"),I.literal("replace"),I.literal("remove")],N_=I.object({op:I.union(L_),path:I.string(),value:at.optional()}),iS=I.object({patches:N_.array(),thoughts:I.string()}),aS=(n=>(n.LEGITIMATE="LEGITIMATE",n.RECOVERABLE="RECOVERABLE",n.INELIGIBLE="INELIGIBLE",n))(aS||{}),sS=I.object({thoughts:I.string(),scenario:I.nativeEnum(aS),instructions:I.string().nullish()}),lS=I.object({reasoning:I.string(),scenario:I.string(),patch:I.null().optional()}),bK=I.object({thoughts:I.string(),evaluation:I.number().min(0).max(10)}),EK=I.object({observations:I.string(),reasoning:I.string(),command:Is});var fd=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")})])}),D_=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||{}),uS=I.object({categoryThoughts:I.string(),category:I.nativeEnum(cS),relevantSections:D_.array()}),Kr=I.boolean().nullish().transform(r=>r??!1),dS=I.object({thoughts:I.string().optional(),isPageReady:Kr,descriptionLabels:I.object({usesTextContent:Kr,usesAppearance:Kr,usesPosition:Kr,usesRelativeElements:Kr,usesSingleQuotes:Kr,isAmbiguous:Kr,targetDoesNotExist:Kr,usesIcon:Kr}).optional()});import{z as P}from"zod";import*as ne from"zod";var CK=ne.object({thoughts:ne.string().optional().describe("only provided if a description was provided"),target:on.optional().describe("only provided if a description was provided"),pageState:ne.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ne.object({label:ne.string(),value:ne.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ne.object({data:ne.string(),height:ne.number().int(),width:ne.number().int()}).optional().describe("only provided if returnScreenshot is true")}),pS=ne.union([ne.literal("ELEMENT_CHECK"),ne.literal("NEGATED_CHECK"),ne.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ne.literal("SELECT_OPTION"),ne.literal("TYPE")]);function na(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 oa=(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))(oa||{}),Bo=ne.object({matched:ne.boolean(),reason:ne.string().optional().describe("Human understandable description"),logs:ne.string().array().optional().describe("Logs for debugging")}),k_=Bo.extend({type:ne.literal("USER_SELECTOR")}),U_=Bo.extend({type:ne.literal("CSS_SELECTOR"),selectors:ne.string().array()}),F_=Bo.extend({type:ne.literal("HYBRID_SELECTOR")}),B_=Bo.extend({type:ne.literal("HTML_DISTANCE"),distance:ne.number().optional(),closestElement:ne.string().optional(),savedElement:ne.string().optional()}),z_=Bo.extend({type:ne.literal("TEMPLATE_MATCHING"),elementImageUrl:ne.string().url()}),H_=Bo.extend({type:ne.literal("AUTO_FRAME"),logs:ne.string().array().optional()}),mS=ne.discriminatedUnion("type",[k_,U_,F_,B_,z_,H_]);import{z as la}from"zod";import{z as Z_}from"zod";import*as V from"zod";import{extendZodWithOpenApi as j_}from"zod-openapi";import{cloneDeep as UK}from"lodash-es";import BK from"truncate-json";import*as Kn from"zod";import{extendZodWithOpenApi as V_}from"zod-openapi";import{z as At}from"zod";import{z as oe}from"zod";var Sd=oe.object({autoFollowNewTabs:oe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:oe.union([oe.boolean(),oe.literal("inputs-only")]).optional(),ignoreHrefForCaching:oe.boolean().optional(),disableSecondaryCacheResolution:oe.boolean().optional(),hybridSelectorMode:oe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:oe.union([oe.boolean(),oe.literal("always")]).optional(),visualActions:oe.boolean().optional(),autoExpandIframes:oe.boolean().optional(),disableHtmlSnapshots:oe.boolean().optional(),importantAttributes:oe.string().array().optional(),importantClasses:oe.string().array().optional(),importantStyles:oe.string().array().optional()});var gS=1e4,hS=6e4,G_=oe.object({server:oe.string(),username:oe.string().optional(),password:oe.string().optional()}),$n=Sd.extend({pageLoadTimeoutMs:oe.number().optional().refine(r=>r===void 0||r<=hS&&r>=-1,{message:`Page load timeout must be between 0 and ${hS/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:oe.number().optional().refine(r=>r===void 0||r<=gS&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${gS/1e3} seconds`}),localChromeExtensionPaths:oe.string().array().optional(),extraHeaders:oe.record(oe.string(),oe.string()).optional().describe("HTTP headers to be sent on every request"),initialLocalStorage:oe.record(oe.string(),oe.record(oe.string(),oe.string())).optional().describe("Initial local storage key-value pairs to set per domain on browser startup"),userAgent:oe.string().optional(),disableGpu:oe.boolean().optional(),disableBrowserMonitoring:oe.boolean().optional().describe("Disable console logs and network request recording, which power the console and network tab in the run viewer"),bustCacheOnBoundingBoxChange:oe.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:oe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:oe.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:G_.optional().describe("HTTP proxy server to use for the entire browser. This can dramatically increase network latency."),disableFullStory:oe.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 yd="BASE_URL";var qn="ENV_NAME",zo="TEST_NAME",OK={[yd]:"https://www.google.com"},fS=At.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),SS=At.object({name:At.string(),variables:At.record(At.string().describe("variable name"),At.string().describe("variable value"))}),yS=At.object({name:At.string(),variables:At.record(At.string().describe("variable name"),At.unknown().describe("variable value")),browser:$n.optional()});var LK=At.object({name:At.string(),variables:At.record(At.string().describe("variable name"),At.unknown().describe("variable value"))});V_(Kn);var bd=Kn.object({env:Kn.record(Kn.unknown())}).openapi({ref:"TestContextSnapshot"});var $e=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))($e||{}),Ed=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(Ed||{});j_(V);var Td=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()}),W_=Td.extend({viewport:V.object({height:V.number(),width:V.number()}).nullish(),status:V.nativeEnum(Ed),message:V.string().optional(),elementInteracted:V.string().optional()}),Yn=Td.extend({status:V.nativeEnum($e),message:V.string().optional(),data:V.unknown().optional(),beforeTestContext:bd.optional(),afterTestContext:bd.optional(),failureReason:V.nativeEnum(Ae).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"}),bS=(t=>(t.NOT_ELIGIBLE="NOT_ELIGIBLE",t.ATTEMPTED="ATTEMPTED",t))(bS||{}),Vs=Yn.merge(Yt).extend({results:W_.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(()=>ut.array()).optional(),failureRecoveryStatus:V.object({type:V.nativeEnum(bS),message:V.string()}).optional()}),$_=Yn.merge(Gn).extend({results:V.lazy(()=>Vs.array()),previousAttempts:V.lazy(()=>ut.array()).optional()}),q_=Yn.merge(ko).extend({results:V.lazy(()=>Vs.array()),previousAttempts:V.lazy(()=>ut.array()).optional()}),K_=Yn.merge($r).extend({moduleName:V.string().optional(),results:V.lazy(()=>ut.array()),previousAttempts:V.lazy(()=>ut.array()).optional()}),Y_=Yn.merge(Uo).extend({assertionResult:Vs.optional(),results:V.lazy(()=>ut.array()).describe("results for the block actually executed"),previousAttempts:V.lazy(()=>ut.array()).optional()}),X_=Yn.merge(ta).extend({results:V.lazy(()=>ut.array()),healingAttempts:V.lazy(()=>ut.array().array()).optional(),previousAttempts:V.lazy(()=>ut.array()).optional()}),ut=V.discriminatedUnion("type",[$_,q_,Vs,K_,Y_,X_]),t2=Yn.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),J_=Td.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)}),js=J_.extend({beforeScreenshot:V.string().optional(),afterScreenshot:V.string().optional()});var vd=Z_.object({results:ut.array().describe("main results"),beforeResults:ut.array().optional(),afterResults:ut.array().optional()}),ia=vd.partial();import{z as F}from"zod";import{extendZodWithOpenApi as iP}from"zod-openapi";var Ho=(t=>(t.WEB="WEB",t.ANDROID="ANDROID",t))(Ho||{});import{isValidCron as Q_}from"cron-validator";import{z as ie}from"zod";import{z as Ad}from"zod";var cn=(n=>(n.CHROMIUM="Chromium",n.GOOGLE_CHROME="Google Chrome",n.CHROME_FOR_TESTING="Chrome for Testing",n))(cn||{});var Ws=Ad.object({width:Ad.number().min(200).max(1e4),height:Ad.number().min(200).max(1e4)}),ES={"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}},l2=Object.keys(ES);var un=ES["Desktop Large"],TS="en-us",vS="America/Los_Angeles";var $s={latitude:37.7749,longitude:-122.4194};var AS=["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 wS=1e4,eP=$n.extend({browserType:ie.nativeEnum(cn).optional(),slowMoMs:ie.number().optional().refine(r=>r===void 0||r<=wS&&r>=-1,{message:`Slow motion must be between 0 and ${wS} milliseconds`}),basicAuthorization:ie.object({username:ie.string().optional(),password:ie.string().optional()}).optional(),geolocation:ie.object({latitude:ie.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ie.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ie.boolean().optional(),locale:ie.string().optional(),timezone:ie.enum(AS).optional(),colorScheme:ie.enum(["light","dark"]).optional()});var wd=ie.object({useMemory:ie.boolean().optional(),failureRecovery:ie.boolean().optional().describe("undefined means inherit org settings")}),tP=wd.extend({disableAICaching:ie.boolean().optional(),failureRecoveryInstructions:ie.string().optional()}),rP=ie.object({viewport:Ws.optional()}),aa=rP.merge(tP).merge(eP),Go=ie.object({cron:ie.string().refine(r=>Q_(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ie.boolean().default(!1),env:ie.string().optional(),timeZone:ie.string().default("America/Los_Angeles"),jobKey:ie.string().optional()}),Vo=ie.object({onSuccess:ie.boolean().default(!1),failureMessage:ie.string().optional(),onFailure:ie.boolean().default(!0),successMessage:ie.string().optional()}),nP=ie.object({name:ie.string(),required:ie.boolean().optional(),defaultValue:ie.string().describe("this is not optional because we need a value when the editor is first loaded")}),qs=nP.array(),oP=ie.object({name:ie.string(),value:ie.string()}),RS=oP.array(),Ks=ie.object({name:ie.string(),default:ie.boolean().optional(),fixtures:fS.array().optional()});iP(F);var Qt={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||{}),Ys=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Ys||{});var et=F.string().pipe(F.coerce.date()).or(F.date()),sa=F.object({id:F.string(),runKey:F.string(),organizationId:F.string(),executionType:F.nativeEnum(Ho).optional().default("WEB"),createdAt:et,createdBy:F.string(),flake:F.boolean().nullish(),scheduledAt:et.or(F.null()),startedAt:et.or(F.null()),updatedAt:et.nullish(),finishedAt:et.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(Ys).nullish(),status:F.nativeEnum(Re),trigger:F.nativeEnum(Qt),attempts:F.number(),runAttempts:F.array(F.object({id:F.string(),status:F.nativeEnum(Re),startedAt:et.or(F.null()),finishedAt:et.or(F.null())})).optional(),videos:F.array(F.string()).optional(),failureReason:F.nativeEnum(Ae).nullish(),failureDetails:Us.nullish(),failureRecoveryDetails:F.record(F.string(),F.unknown()).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"}),aP={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Xs=sa.pick({...aP,test:!0}),CS=sa.omit({failureReason:!0,failureDetails:!0,test:!0}),Rd=sa.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:aa.nullish()}).nullish()}).merge(vd);var sP=la.object({id:la.string().uuid(),startedAt:et.or(la.null()),finishedAt:et.or(la.null()),status:la.nativeEnum(Re)}).merge(ia),P2=sP.array();import{z as tt}from"zod";var lP=tt.object({id:tt.string(),status:tt.nativeEnum(Re),trigger:tt.nativeEnum(Qt),createdAt:et,startedAt:et.nullish(),finishedAt:et.nullish(),gitCommitSha:tt.string().nullish(),gitCommitShaShort:tt.string().nullish(),gitCommitTimestamp:et.nullish(),gitBranchName:tt.string().nullish(),gitOriginUrl:tt.string().nullish(),gitCommitMessage:tt.string().nullish(),gitCommitAuthorName:tt.string().nullish(),githubRepository:tt.string().nullish(),gitlabProjectPath:tt.string().nullish(),pipelineId:tt.string().nullish(),cliVersion:tt.string().nullish(),labels:tt.string().array().optional(),suite:tt.object({id:tt.string(),name:tt.string()}).nullish(),runs:tt.object({status:tt.nativeEnum(Re)}).array()}).openapi({ref:"RunGroup"}),xS=lP.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Xs.array()});import{z as dt}from"zod";var cP=dt.object({type:dt.literal("TARGETING"),name:dt.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:mS.array(),pageState:dt.string().optional(),targetSource:dt.nativeEnum(nn).optional(),targetUpdateTime:dt.string().optional()}),uP=dt.object({type:dt.literal("AI_LOCATION"),matched:dt.boolean(),pageState:dt.string().optional(),ragUsed:dt.boolean().optional(),thoughts:dt.string().optional()}),dP=dt.object({type:dt.literal("ASSERTION"),relevantElementsSerialized:dt.string().array().optional(),pageState:dt.string().optional(),ragUsed:dt.boolean().optional()}),pP=dt.discriminatedUnion("type",[cP,uP,dP]);import{z as Je}from"zod";var mP=Je.object({id:Je.string(),name:Je.string()}),j2=mP.merge(Je.object({createdAt:et,createdBy:Je.string(),schedule:Go,notification:Vo,environment:Je.object({name:Je.string()}).nullish(),beforeTests:Je.object({id:Je.string()}).array().nullish(),afterTests:Je.object({id:Je.string()}).array().nullish()})),MS=Je.object({id:Je.string().uuid(),orgId:Je.string(),createdAt:et,startedAt:et.or(Je.null()),finishedAt:et.or(Je.null()),status:Je.nativeEnum(Re),trigger:Je.nativeEnum(Qt),suite:Je.object({id:Je.string(),name:Je.string()}).nullish(),runs:sa.array()}),W2=MS.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),_S=MS.extend({runs:Xs.array()});import{z as er}from"zod";import{cloneDeep as K2}from"lodash-es";import{z as be}from"zod";var eY=be.object({thoughts:be.string(),subGoals:be.object({instruction:be.string()}).array()}),tY=be.object({thoughts:be.string(),newPlanMarkdown:be.string()}),rY=be.object({thoughts:be.string(),correct:be.boolean(),failedActionIndex:be.number().optional()}),gP=be.object({type:be.literal("PLANNING"),beforePlan:be.string(),goalDecision:be.string(),thoughts:be.string()}),hP=be.object({type:be.literal("RUNNING"),stepDisplayName:be.string(),status:be.nativeEnum($e),results:ut.array()}),fP=be.object({type:be.literal("REVISING"),beforePlan:be.string(),afterPlan:be.string(),errString:be.string(),diffs:be.string(),thoughts:be.string()}),SP=be.object({type:be.literal("SYSTEM"),message:be.string()}),yP=be.discriminatedUnion("type",[gP,hP,fP,SP]),PS=yP.array();var sY=er.object({id:er.string(),scheduledAt:er.coerce.date().nullable(),startedAt:er.coerce.date().nullable(),finishedAt:er.coerce.date().nullable(),status:er.nativeEnum(Re),history:PS.nullable(),testPlan:er.object({id:er.string(),name:er.string()}).nullable(),test:er.object({id:er.string(),name:er.string()}).nullable()});import{z as Lt}from"zod";var Cd=Lt.object({content:Lt.string(),ids:Lt.string().array(),tokenLength:Lt.number()}),bP=Lt.object({chunks:Cd.array()}),wY=Lt.object({ids:Lt.string().array(),score:Lt.number(),tokenLength:Lt.number()}),RY=bP.extend({description:Lt.string().describe("Input to pass to RAG engine"),tokenLimit:Lt.number()}),IS=Lt.object({ids:Lt.number().array()}),OS=Lt.object({indices:Lt.number().array()});var ht=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()}),LY=ht.extend({chunks:Cd.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()}),EP=P.object({screenshotBase64AfterCommand:P.string(),urlAfterCommand:P.string(),serializedCommand:P.string(),elementInteracted:P.string().optional(),thoughts:P.string().optional()}),LS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),source:pS.optional().catch(void 0),memory:P.discriminatedUnion("type",[Cs,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional()}),NS=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()}),DS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string().optional(),returnSchema:P.string().optional()}),TP=P.literal("NEGATED_CHECK"),kS=P.object({goal:P.string(),browserState:P.string(),screenshot:P.string(),url:P.string(),contextChoice:Wu.optional(),memory:P.discriminatedUnion("type",[zu,P.object({type:P.literal("RESOLVED_TRACES"),traces:P.unknown().array()})]).optional(),source:TP.optional()}),US=P.object({command:Lo}),FS=P.object({message:P.string()}),xd=P.object({goal:P.string(),browserState:P.string(),startingScreenshot:P.string().optional(),screenshot:P.string(),url:P.string(),history:EP.array(),actionHint:P.string().optional(),lastError:P.string().optional()}),BS=P.object({results:js.array(),errorMessage:P.string(),errorStack:P.string().optional()}),zS=P.object({results:js.array(),goal:P.string(),errorMessage:P.string()}),HS=P.object({failedResults:js.array(),nextStepsSerialized:P.string().array(),currentUrl:P.string(),currentPageState:P.string(),currentScreenshot:P.string(),customInstructions:P.string().optional(),testDescription:P.string().optional()}),NY=P.object({description:P.string(),type:P.union([P.literal("locator"),P.literal("assertion"),P.literal("ai-action")]),excerpt:P.string()}),GS=P.object({type:P.string(),browserContext:P.string(),currentStep:P.string(),screenshot:P.string()}),VS=P.object({description:P.string(),browserState:P.string(),screenshot:P.string()});import{z as ca}from"zod";var UY=ca.object({goal:ca.string()}),jS=ca.object({keywords:ca.array(ca.string())});import{z as Md}from"zod";var Js=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(Js||{}),zY=Md.nativeEnum(Js),vP=Md.enum(["v1","v2"]),HY=vP.or(Md.string().describe("for people with special configurations"));var WS={locator:"v3",assertion:"v3","visual-assertion":"v3","text-extraction":"v2"};import{z as Fe}from"zod";var $S=Fe.object({attributesRequired:Fe.array(Fe.string()).optional(),textRequired:Fe.boolean().optional(),boundsRequired:Fe.boolean().optional()}),qS=Fe.object({id:Fe.number(),thoughts:Fe.string(),inWebview:Fe.boolean().optional(),requirements:$S.optional(),additionalElements:Fe.object({id:Fe.number(),requirements:$S}).array().optional()}),KS=Fe.object({description:Fe.string(),screenXml:Fe.string(),screenshot:Fe.string()}),YS=Fe.object({assertion:Fe.string(),screenXml:Fe.string(),screenshot:Fe.string()}),XS=Fe.object({thoughts:Fe.string(),result:Fe.boolean(),relevantElements:Fe.array(Fe.number()).optional()});import{z as Xn}from"zod";var JS=Xn.object({id:Xn.string().uuid(),skipped:Xn.boolean().optional(),envKey:Xn.string().optional().describe("key in the environment to save the result of this step to")}),_d=JS.merge(Ao).extend({type:Xn.literal("REQUEST")}),Pd=JS.merge(Ms).extend({type:Xn.literal("JAVASCRIPT")}),Id=Xn.discriminatedUnion("type",[Pd,_d]);import{z as tr}from"zod";var ZS=tr.object({id:tr.string(),name:Fo,description:tr.string().optional().nullish(),baseUrl:Gs.nullish(),schemaVersion:tr.string(),advanced:tr.unknown().optional(),retries:tr.number(),envs:tr.array(Ks).nullish(),parameters:qs.nullish()}),AP=tr.object({createdAt:tr.coerce.date(),updatedAt:tr.coerce.date(),schedule:Go.nullish(),notification:Vo.nullish(),createdBy:tr.string(),organizationId:tr.string()}),wP=ZS.merge(AP),dX=wP.extend({steps:Id.array()}),pX=ZS.extend({steps:Id.array()});import{z as Ut}from"zod";var QS=Ut.object({startedAt:Ut.coerce.date(),finishedAt:Ut.coerce.date(),status:Ut.nativeEnum($e),message:Ut.string().optional(),data:Ut.unknown().optional()}),RP=QS.merge(Pd).extend({type:Ut.literal("JAVASCRIPT")}),CP=QS.merge(_d).extend({type:Ut.literal("REQUEST")}),xP=Ut.discriminatedUnion("type",[RP,CP]),ey=Ut.object({startedAt:Ut.coerce.date(),finishedAt:Ut.coerce.date().nullish(),status:Ut.nativeEnum(Re),results:xP.array(),failureReason:Ut.string().nullish(),failureDetails:Us.nullish()});import{z as Ft}from"zod";var MP=Ft.object({id:Ft.string(),organizationId:Ft.string(),createdAt:Ft.coerce.date(),updatedAt:Ft.coerce.date(),createdBy:Ft.string(),scheduledAt:Ft.coerce.date().nullish(),startedAt:Ft.coerce.date().nullish(),finishedAt:Ft.coerce.date().nullish(),status:Ft.nativeEnum(Re),trigger:Ft.nativeEnum(Qt),results:ey.array().nullish(),apiTestName:Ft.string().nullish(),apiTestPath:Ft.string().nullish(),apiTestId:Ft.string().nullish()}),vX=MP.pick({status:!0,startedAt:!0,finishedAt:!0});var ua=(o=>(o.TestRun="test-run",o.MobileTestRun="mobile-test-run",o.CreditsUsed="credits-used",o.CreditsUsedV2="credits-used-v2",o))(ua||{}),ty=3;function _P(r){return r==="MODULE"||r==="CONDITIONAL"||r==="SECTION"||r==="RESOLVED_MODULE"}function Od(r){if(!_P(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 Ld(r){switch(r.type){case"AI_EXTRACT":case"AI_ASSERTION":return ty;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 Zs=class{trackStepExecution(){}async flush(){}};import{parseString as PP,splitCookiesString as IP}from"set-cookie-parser";import{z as we}from"zod";var Nd=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 Qs(r,e){let t=[],n=IP(r);for(let o of n){let i=PP(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=Nd.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,p]=u.split("=");if(!d||!p)throw new Error(`Invalid key-value pair in cookie: ${u}`);c.includes(d.toLowerCase())||t.push({...s,name:d,value:p})}}return t}var OP=we.object({origin:we.string(),localStorage:we.array(we.object({name:we.string(),value:we.string()}))}),LP=we.object({entries:we.record(we.string(),we.array(we.tuple([we.unknown(),we.unknown()]))),version:we.number().optional()}),ry=we.object({cookies:Nd.array().optional(),origins:OP.array().optional(),idb:we.record(we.string(),LP).optional().describe("key is db name")});function el(r,e){let t=[];return r.cloneSync()?.serializeSync()?.cookies.forEach(n=>{let o=Nd.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 nl}from"uuid";import Be from"zod";import{v4 as WX}from"uuid";import{z as B}from"zod";import*as H from"zod";var ny=H.discriminatedUnion("type",[H.object({type:H.literal("SCREEN")}),H.object({type:H.literal("OPEN_APP")}),H.object({type:H.literal("OPEN_WEBVIEW")})]),da=H.object({type:H.literal("description"),description:H.string()}),oy=H.object({type:H.literal("CUSTOM_COORDINATES"),startX:H.number().describe("Starting X coordinate in pixels"),startY:H.number().describe("Starting Y coordinate in pixels"),deltaPixels:H.number().describe("Number of pixels to scroll in the specified direction")}),Dd=H.discriminatedUnion("type",[...ny.options,H.object({type:H.literal("CUSTOM"),target:da}),oy]);var NP=H.object({type:H.literal("coordinates"),xPercent:H.number(),yPercent:H.number()}),kd=H.discriminatedUnion("type",[da,NP]),iy=H.object({requiredText:H.string().optional(),requiredAttributes:H.record(H.string(),H.string()).optional(),requiredBounds:H.boolean().optional()}),DP=H.object({xPath:H.string(),requirements:iy.optional()}),kP=H.object({type:H.literal("CUSTOM"),target:da,cache:H.lazy(()=>ay).optional()}),UP=H.object({pixelDelta:H.number().describe("Number of pixels to scroll in the specified direction"),scrollableElement:H.union([ny,kP,oy]),direction:H.enum(["up","down"])}),ay=H.object({type:H.literal("NATIVE"),bounds:H.number().array(),resolvedDescription:H.string(),xPath:H.string(),elementOnlySerializedXml:H.string(),scrollDetails:UP.optional(),requirements:iy.optional(),requiredRelatedElements:DP.array().optional()}),FP=H.object({type:H.literal("WEBVIEW"),resolvedDescription:H.string(),xPath:H.string(),browserCache:on.optional()}),tl=H.union([ay,FP]);var dn=(R=>(R.AI_CHECK="AI_CHECK",R.TAP="TAP",R.TYPE="TYPE",R.PRESS="PRESS",R.PRESS_KEYBOARD="PRESS_KEYBOARD",R.OPEN_APP="OPEN_APP",R.KILL_APP="KILL_APP",R.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",R.SWIPE="SWIPE",R.SCROLL_TO="SCROLL_TO",R.SCREEN_CHECK="SCREEN_CHECK",R.JAVASCRIPT="JAVASCRIPT",R.REQUEST="REQUEST",R.WAIT="WAIT",R.ADD_FILE="ADD_FILE",R.INSTALL_APP="INSTALL_APP",R.UNINSTALL_APP="UNINSTALL_APP",R.ADB="ADB",R.STATE="STATE",R))(dn||{}),pa=(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))(pa||{}),Ud=(n=>(n.CLOSE_KEYBOARD="CLOSE_KEYBOARD",n.ENTER="ENTER",n.BACKSPACE="BACKSPACE",n))(Ud||{}),BP=B.object({updatedAt:B.coerce.date().optional()}),st=B.object({id:B.string().uuid(),disableCache:B.boolean().optional()}),zP=st.extend({type:B.literal("STATE")}),HP=st.extend({type:B.literal("KILL_APP")}),rl=BP.extend({target:tl}),GP=st.extend({type:B.literal("AI_CHECK"),assertion:B.string(),timeoutSecs:B.number().optional()}),Fd=st.extend({type:B.literal("TAP"),target:kd,cache:rl.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()}),Bd=st.extend({type:B.literal("TYPE"),target:kd.optional(),cache:rl.optional(),keyPressDelayMs:B.number().optional(),text:B.string(),clearContent:B.boolean().optional(),forceClearContent:B.boolean().optional()});var VP=st.extend({type:B.literal("PRESS"),key:B.nativeEnum(pa),longPress:B.boolean().optional()}),jP=st.extend({type:B.literal("PRESS_KEYBOARD"),key:B.nativeEnum(Ud)}),WP=st.extend({type:B.literal("OPEN_APP"),packageName:B.string(),activityName:B.string().optional(),intentExtras:B.string().optional()}),$P=st.extend({type:B.literal("OPEN_NOTIFICATION_DRAWER")}),zd=st.extend({type:B.literal("SWIPE"),direction:B.enum(["up","down","left","right"]),scrollableElement:Dd,cache:rl.optional(),viewportPercent:B.number().optional(),durationMs:B.number().optional()}),Hd=st.extend({type:B.literal("SCROLL_TO"),target:da,direction:B.enum(["down","up"]),scrollableElement:Dd,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:rl.optional()});var qP=B.object({type:B.literal("CONTENT"),negated:B.boolean().optional(),value:B.string()}),KP=st.extend({type:B.literal("SCREEN_CHECK"),assertion:qP,timeout:B.number().int().min(0).max(qi).optional().describe("max seconds to wait for the assertion to be true")}),YP=st.extend({type:B.literal("JAVASCRIPT"),code:B.string(),timeout:B.number().int().max(60).optional().describe("Max seconds for the code to complete")}),XP=st.extend({type:B.literal("REQUEST")}).merge(Ao),JP=st.extend({type:B.literal("WAIT"),timeoutSecs:B.number()}),ZP=st.extend({type:B.literal("ADB"),command:B.string(),jsonArgs:B.string().optional()}),QP=st.extend({type:B.literal("ADD_FILE"),file:B.string(),storageLocation:B.string()}),eI=B.string().trim(),tI=st.extend({type:B.literal("INSTALL_APP"),uri:eI}),rI=st.extend({type:B.literal("UNINSTALL_APP"),packageName:B.string()}),ly=B.discriminatedUnion("type",[GP,Fd,Bd,VP,WP,$P,jP,zd,Hd,KP,YP,XP,JP,QP,tI,rI,HP,ZP,zP]);var Gd=r=>{switch(r.type){case"description":return r.description;case"coordinates":return`${r.xPercent}%, ${r.yPercent}%`}};var nI=Be.object({type:Be.literal("TAP"),description:Be.string().describe("Description of the element to tap."),longPress:Be.boolean().describe("Whether to hold the tap down before releasing. Useful for triggering context menus."),doubleTap:Be.boolean().describe("Whether to tap twice in quick succession."),relativePosition:Be.null().or(Be.object({x:Be.number(),y:Be.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
|
+
`),oI=Be.object({type:Be.literal("PRESS"),key:Be.nativeEnum(pa)}).describe(`
|
|
12
12
|
Press a button on the device. Some buttons are physical (volume) while others are virtual (Back/Home/App Switcher).
|
|
13
|
-
`),
|
|
13
|
+
`),iI=Be.object({type:Be.literal("AI_CHECK"),assertion:Be.string().describe("A natural language assertion to validate. On each attempt, Momentic's AI agents will evaluate the assertion by analyzing the current emulator XML and screenshot. Thus, the assertion must be verifiable based on a single point in time. The assertion will be automatically retried until it is true or the timeout is reached."),timeoutSecs:Be.number().describe("Maximum number of seconds to wait for the assertion to be true.")}).describe(`
|
|
14
14
|
Use AI to verify a statement about the current state of the emulator or wait until a statement is true.
|
|
15
|
-
`),tI=Ue.object({type:Ue.literal("TYPE"),text:Ue.string().describe("Exact type to text, which will be passed to appium's driver.keys() method."),keyPressDelayMs:Ue.number().or(Ue.null()).describe("Milliseconds to wait between each key press. Useful for triggering auto-complete and other event listeners."),clearContent:Ue.boolean().or(Ue.null()).describe("Clear the content of the input before typing. Do not set to true if the input is already empty.")}),Gd=Ue.discriminatedUnion("type",[ZP,QP,eI,tI]),HS=r=>{let e=Gd.parse(r);switch(e.type){case"TAP":return{id:nl(),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:nl(),...e};case"AI_CHECK":return{id:nl(),...e};case"TYPE":return{id:nl(),type:"TYPE",text:e.text,keyPressDelayMs:e.keyPressDelayMs??void 0,clearContent:e.clearContent??void 0};default:{let t=e;throw new Error("Unreachable")}}};import rI from"zod";var ol={type:!0,cache:!0},mn=rI.discriminatedUnion("type",[Ud.pick(ol),Fd.pick(ol),Bd.pick(ol),zd.pick(ol)]),nI=Object.values(dn).filter(r=>mn.options.some(e=>e.shape.type.safeParse(r).success));function il(r){return nI.includes(r.type)}var GS=Yi(mn),VS=Xi(mn),n5=Os(mn);import WS from"zod";var al=(t=>(t.US_WEST_1="us-west1",t.EU_NORTH_1="eu-north1",t))(al||{}),sl=(e=>(e.LOCAL="local",e))(sl||{}),jS=WS.nativeEnum(al).or(WS.nativeEnum(sl)),pa=(t=>(t.ANDROID_14="14",t.ANDROID_15="15",t))(pa||{});var $S="14";import{cloneDeep as ga}from"lodash-es";import qS from"truncate-json";var oI="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",iI=[$n,Uo],KS=[$n,Uo],Ho=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[$n],o=e.env[Uo],i={};for(let[s,c]of Object.entries(e.env))KS.includes(s)||(t??{})[s]===void 0&&(i[s]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=ga(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){iI.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[$n]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ga(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>KS.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,oI]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=qS(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=qS(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=ga(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable($n,e.envName),e.testName&&this.setMomenticSystemVariable(Uo,e.testName)}getDynamicVariablesCopy(){return ga(this.env)}getVariablesFromEnvironmentCopy(){return ga(this.varsFromMomenticEnvironment)}};import tt from"zod";import{z as fr}from"zod";import{z as Fe}from"zod";var hr=Fe.object({id:Fe.string(),name:Do,baseUrl:Gs,description:Fe.string().optional().nullish(),schemaVersion:Fe.string(),advanced:aa,retries:Fe.number(),envs:Fe.array(Ks).nullish(),parameters:qs.nullish(),disabled:Fe.boolean().optional(),labels:Fe.array(Fe.string()).optional().catch([])}),h5=Fe.enum(["INHERIT","ENABLED","DISABLED"]);var aI=aa.extend({failureRecovery:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED"),useMemory:Fe.boolean().or(Fe.string()).optional().transform(r=>typeof r=="string"?r:r===void 0?"INHERIT":r?"ENABLED":"DISABLED")});var f5=hr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:aI}),S5=hr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),sI=Fe.object({labels:Fe.array(Fe.string()).optional(),outputs:nS.nullish()}),Go=hr.merge(sI),lI=Fe.object({createdAt:Fe.coerce.date(),updatedAt:Fe.coerce.date(),updatedBy:Fe.string().nullable(),schedule:Bo,notification:zo,createdBy:Fe.string(),organizationId:Fe.string(),folderId:Fe.string().nullable().optional()}),cI=hr.merge(lI),y5=cI.merge(Gn),ll=hr.merge(Gn),b5=hr.merge(Vn);var uI="test",dI="module",mI="mobile-test",pI="mobile-module";var xe=(o=>(o.TEST=`momentic/${uI}`,o.MODULE=`momentic/${dI}`,o.MOBILE_TEST=`momentic/${mI}`,o.MOBILE_MODULE=`momentic/${pI}`,o))(xe||{}),C5=hr.merge(Vn),YS=Yt.extend({steps:fr.array(fr.record(fr.string(),fr.unknown())),schemaVersion:fr.string()}),x5=YS.extend({fileType:fr.literal(xe.MODULE)}),M5=fr.object({test:fr.string().describe("YAML for the test, including metadata and steps"),modules:fr.record(fr.string(),fr.string()).describe("Map of module name to YAML for the module")});var Vd=tt.object({parameterNames:tt.string().array(),defaultParameters:tt.record(tt.string(),tt.string()).optional(),parameterEnums:tt.record(tt.string(),tt.string().array()).optional()}),gI=tt.object({moduleId:tt.string().uuid(),name:tt.string(),description:tt.string().nullish(),parameters:Vd.optional(),enabled:tt.boolean().nullish(),schemaVersion:tt.string()}),ha=gI.omit({name:!0}),cl=ha.extend({steps:tt.array(tt.record(tt.string(),tt.unknown()))}),XS=tt.object({fileType:tt.literal(xe.MOBILE_MODULE)}).merge(cl);import At from"zod";var Ft=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(Ft||{}),fa=At.object({id:At.string().uuid(),envKey:At.string().optional(),skipped:At.boolean().optional()}),Sa=fa.extend({type:At.literal("MOBILE_PRESET_STEP"),command:zS,keyPressDelayMs:At.number().optional()}),Vo=At.object({moduleId:At.string(),inputs:At.record(At.string(),At.string()).optional()}),ya=fa.merge(Vo.extend({type:At.literal("MOBILE_MODULE_STEP")})),k5=Vo.extend({steps:At.lazy(()=>Sr.array())}),ba=fa.extend({type:At.literal("MOBILE_AI_ACTION_STEP"),text:At.string()}),Sr=At.discriminatedUnion("type",[Sa,ya,ba]);import Me from"zod";import Ea from"zod";var Yr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Yr||{}),Wd=Vo.extend({steps:Ea.lazy(()=>Wo.array()),description:Ea.string().optional(),name:Ea.string().describe("name of the module"),parameters:Vd.optional()}),hI=fa.merge(Wd).extend({type:Ea.literal("RESOLVED_MOBILE_MODULE")}),Wo=Ea.discriminatedUnion("type",[hI,Sa,ba]);function JS(r){return Object.values(Yr).includes(r)||Object.values(Ft).includes(r)}var fI=Me.object({disableMomenticAccessibilityTree:Me.boolean().optional(),autoGrantPermissions:Me.boolean().optional()}),jd=fI.extend({region:jS.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:Me.object({androidVersion:Me.nativeEnum(pa).optional()}).optional(),localEmulatorSettings:Me.object({avdId:Me.string()}).optional(),geolocation:Me.object({latitude:Me.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Me.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional()}),Ta=Me.object({retries:Me.number().optional().describe("number of retries to run"),defaultChannel:Me.string().optional().describe("default channel to use"),defaultTag:Me.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Me.string().optional(),defaultApkFilePath:Me.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:jd.optional()}),Mr=Me.object({id:Me.string().uuid(),description:Me.string(),schemaVersion:Me.string(),settings:Ta.optional()}),SI=Mr.merge(Me.object({steps:Me.array(Sr)})),ul=Me.object({fileType:Me.literal(xe.MOBILE_TEST)}).merge(SI),Q5=Me.object({name:Me.string(),steps:Me.array(Sr).optional(),settings:Ta.optional()}),yI=Mr.extend({steps:Wo.array()});import Te from"zod";var Xn=Te.object({startTime:Te.number(),endTime:Te.number().optional(),durationMs:Te.number().optional(),error:Te.string().optional(),result:Te.unknown().optional(),attributes:Te.record(Te.string(),Te.unknown())});var bI=Xn.extend({type:Te.literal("SECTION"),name:Te.string(),subSpans:Te.lazy(()=>$d.array())}),EI=Xn.extend({type:Te.literal("AI_LOCATOR_CALL"),result:Te.object({id:Te.number(),thoughts:Te.string()}).optional()}),TI=Xn.extend({type:Te.literal("AI_ASSERTION_CALL"),result:Te.object({thoughts:Te.string(),result:Te.boolean()}).optional()}),vI=Xn.extend({type:Te.literal("TARGET_RESOLUTION"),result:Te.object({serializedElement:Te.string()}).optional()}),AI=Xn.extend({type:Te.literal("EMULATOR_INTERACTION"),name:Te.string(),withinWebview:Te.boolean().optional()}),wI=Xn.extend({type:Te.literal("EMULATOR_READ_STATE"),name:Te.string()}),RI=Xn.extend({type:Te.literal("GENERIC"),name:Te.string()}),$d=Te.discriminatedUnion("type",[bI,EI,TI,vI,AI,wI,RI]);import Ht from"zod";var qd=Ht.object({message:Ht.string().optional(),startTime:Ht.number(),endTime:Ht.number(),status:Ht.nativeEnum(We),trace:Ht.unknown(),beforeSnapshot:Ht.string().optional(),afterSnapshot:Ht.string().optional(),data:Ht.unknown().optional().describe("output data from the step")}),CI=qd.merge(Sa),xI=qd.merge(ya).extend({steps:Ht.lazy(()=>tr.array()),name:Ht.string().optional()}),MI=qd.merge(ba).extend({steps:Ht.lazy(()=>tr.array())}),tr=Ht.discriminatedUnion("type",[CI,xI,MI]);import{parse as u4}from"date-fns";var L4=new Set(Object.values(ot));var _I={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"},N4={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:[]},D4={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."},k4={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",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",ADB:"ADB command",STATE:"Debug state"},U4={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.",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.",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 PI from"semver";import{z as II}from"zod";var H4=II.string().refine(r=>PI.valid(r),{message:"must be a valid semver string"});import{Faker as W4,en as j4}from"@faker-js/faker";import{z as N}from"zod";var q4=N.object({body:N.string(),to:N.string(),from:N.string()}),K4=N.object({from:N.string().optional(),to:N.string(),timeout:N.number().optional(),beforeDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional()}),Y4=N.object({to:N.string().email(),from:N.string(),subject:N.string(),body:N.string(),html:N.string().optional()}),X4=N.object({inbox:N.string().transform(r=>r.toLowerCase()),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),timeout:N.number().optional(),trimWhitespace:N.boolean().optional()}),J4=N.object({inbox:N.string(),limit:N.number().optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),trimWhitespace:N.boolean().optional()});var dl=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(dl||{}),ZS=N.object({body:N.string().nullish(),status:N.number().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}),OI=N.object({url:N.string(),options:N.object({method:N.string(),body:N.string().nullish(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),LI=N.object({body:N.string().nullish(),options:N.object({status:N.number(),statusText:N.string().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),QS=N.object({result:N.unknown(),variableUpdates:N.record(N.string(),N.unknown()).optional(),persistentVariableUpdates:N.record(N.string(),N.unknown()).optional(),error:N.string().optional(),success:N.boolean()}),Z4=N.object({id:N.string().optional(),orgId:N.string(),momenticLambdaAuthHash:N.string(),code:N.string(),fragment:N.boolean(),state:N.object({env:N.record(N.string(),N.unknown()),request:OI,response:LI,additionalBindings:N.record(N.string(),N.unknown()).optional()}),timeoutMs:N.number().optional(),disallowVariableUpdates:N.boolean().optional(),responseSerialization:N.nativeEnum(dl).optional()}),pn=15e3;import*as wt from"zod";import{extendZodWithOpenApi as NI}from"zod-openapi";NI(wt);var DI=wt.object({url:wt.string(),lineNumber:wt.number(),columnNumber:wt.number()}).openapi({ref:"CodeLocation"}),ml=wt.object({timestamp:wt.number(),text:wt.string(),type:wt.string(),tabIndex:wt.number(),args:wt.unknown().array().optional(),url:wt.string().optional(),location:DI.optional()}).openapi({ref:"ConsoleLog"}),ey=ml.array(),kI=ey.array();import*as Kd from"zod";import{extendZodWithOpenApi as UI}from"zod-openapi";UI(Kd);var FI=Kd.object({logsPerPage:ml.array().array()}).openapi({ref:"DebugData"});import{z as M}from"zod";var BI=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),zI=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),HI=M.object({onContentLoad:M.number().optional(),onLoad:M.number().optional(),comment:M.string().optional()}),Yd=M.object({startedDateTime:M.string(),id:M.string(),title:M.string().optional(),pageTimings:HI,comment:M.string().optional()}),GI=M.array(Yd),VI=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()}),ry=M.array(VI),WI=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),ny=M.array(WI),jI=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),$I=M.array(jI),qI=M.object({name:M.string(),value:M.string().optional(),fileName:M.string().optional(),contentType:M.string().optional(),comment:M.string().optional()}),KI=M.array(qI),YI=M.object({mimeType:M.string(),params:KI,text:M.string(),comment:M.string().optional(),_redactedReason:M.string().optional()}),XI=M.object({method:M.string(),url:M.string(),httpVersion:M.string().optional(),cookies:ry,headers:ny,queryString:$I,postData:YI.optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional()}),JI=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()}),ZI=M.object({status:M.number(),statusText:M.string(),httpVersion:M.string().optional(),cookies:ry,headers:ny,content:JI,redirectURL:M.string().optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional(),_mocked:M.boolean().optional()}),ty=M.object({expires:M.string().optional(),lastAccess:M.string(),eTag:M.string(),hitCount:M.number(),comment:M.string().optional()}),QI=M.object({beforeRequest:ty.optional(),afterRequest:ty.optional(),comment:M.string().optional()}),eO=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()}),Xd=M.object({pageref:M.string().optional(),startedDateTime:M.string(),time:M.number().optional(),request:XI,response:ZI.optional(),cache:QI.optional(),timings:eO,serverIPAddress:M.string().optional(),connection:M.string().optional(),comment:M.string().optional(),_resourceType:M.string().optional()}),tO=M.array(Xd),rO=M.object({version:M.string().default("1.1"),creator:BI.optional(),browser:zI.optional(),pages:GI.optional(),entries:tO,comment:M.string().optional()}),nO=M.object({log:rO}),d3=M.record(M.string(),Yd),m3=M.record(M.string(),Xd);import{cloneDeep as oO}from"lodash-es";import{z as _r}from"zod";var iy=(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))(iy||{});var oy=_r.union([_r.string(),_r.number(),_r.boolean(),_r.null(),_r.record(_r.string(),_r.lazy(()=>oy)),_r.array(_r.lazy(()=>oy))]),pl=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=oO(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(iy).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")}},w3=new pl({},{});var Jd={".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"},ay=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],C3=Object.keys(Jd);import*as sy from"zod";var M3=sy.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as gn}from"zod";var I3=gn.object({id:gn.string(),name:gn.string(),createdAt:gn.coerce.date(),createdBy:gn.string(),updatedAt:gn.coerce.date(),updatedBy:gn.string().nullable(),organizationId:gn.string()});import{z as I}from"zod";import hn from"zod";var jo=hn.object({platformSep:hn.string(),fullPathSegments:hn.string().array(),relativePathSegments:hn.string().array(),relativePath:hn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:hn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:hn.coerce.date(),createdAt:hn.coerce.date()});var iO=I.array(jo.extend({id:I.string(),name:I.string(),description:I.string().optional(),labels:I.string().array().optional()})),aO=jo.extend({id:I.string(),name:I.string(),description:I.string().optional(),content:ud}),sO=I.array(aO),W3=I.object({tests:iO,modules:sO,labels:I.string().array()}),j3=ll.merge(Go),$3=I.object({schemaVersion:I.string(),stepLists:Gn}),q3=Go.partial().merge(hr.pick({id:!0})),lO={name:I.string().min(1).max(255).describe("1-255 chars; Only letters/numbers/dashes. Cannot start/end with '-'. Not '.yaml', 'none', or UUID."),description:I.string().optional(),baseUrl:I.string().url().optional().describe("For LLM: Ask the user for the base URL if they don't provide it."),environment:I.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:I.nativeEnum(cn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:js.optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),pathSegments:I.string().array().optional().describe("For LLM: Only use if explicitly called for by the user. Used to create the test in the correct folder.")},K3=I.object(lO),Y3=ll.merge(I.object({relativeFilePath:I.string().describe("relative to project root")})),X3=I.object({name:I.string()}),J3=I.object({relativeFilePath:I.string()}),Z3=I.object({name:I.string()}),Q3=I.object({relativeFilePath:I.string()}),eJ=I.object({name:I.string(),description:I.string(),enabled:I.boolean(),steps:I.lazy(()=>it.array()),testFilePath:I.string().describe("relative to the project root"),folderPath:I.string().optional().describe("user selected folder path")}),tJ=I.object({name:I.string(),description:I.string(),enabled:I.boolean()}).partial();var rJ=I.array(Xf),nJ=I.object({defaultEnv:I.string().optional().describe("name of the default env, or undefined to unset")}),oJ=I.object({configFilePath:I.string().describe("full path on disk")}),iJ=I.string().array(),aJ=I.object({message:I.string(),newRelativeTestPath:I.string().optional()}),Zd=I.object({name:I.string(),absolutePath:I.string(),relativePath:I.string(),pathSegments:I.array(I.string()),isDirectory:I.boolean(),size:I.number(),createdAt:I.coerce.date(),modifiedAt:I.coerce.date(),accessedAt:I.coerce.date()}),ly=I.object({pathSegments:I.array(I.string())}),sJ=I.object({absolutePath:I.string(),pathSegments:I.array(I.string()),contents:I.array(Zd)}),cy=I.object({pathSegments:I.array(I.string())}),uy=I.object({pathSegments:I.array(I.string()),newPathSegments:I.array(I.string())}),dy=I.object({pathSegments:I.array(I.string()),recursive:I.boolean().optional()}),lJ=I.object({success:I.boolean(),message:I.string(),pathSegments:I.array(I.string()).optional()}),cJ=I.object({gitBranch:I.string(),fileMtime:I.coerce.date(),gitCommitSha:I.string()});var gl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],hl=gl.map(r=>`**/${r}/**`),my=!0,Pr=!1;import Ir from"chalk";import cO from"safe-stable-stringify";import uO from"truncate-json";import dO from"zod";var Jn=cO.configure({deterministic:!1});function py(r){let e=Jn(r),{jsonString:t}=uO(e,5e4);return t}var mO=["app","version","env","namespace","host"];function he(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!mO.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Sl=dO.enum(["debug","info","warn","error"]);var va={debug:20,info:30,warn:40,error:50},gy={20:"debug",30:"info",40:"warn",50:"error"},Qd=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=va[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(`
|
|
15
|
+
`),aI=Be.object({type:Be.literal("TYPE"),text:Be.string().describe("Exact type to text, which will be passed to appium's driver.keys() method."),keyPressDelayMs:Be.number().or(Be.null()).describe("Milliseconds to wait between each key press. Useful for triggering auto-complete and other event listeners."),clearContent:Be.boolean().or(Be.null()).describe("Clear the content of the input before typing. Do not set to true if the input is already empty.")}),Vd=Be.discriminatedUnion("type",[nI,oI,iI,aI]),cy=r=>{let e=Vd.parse(r);switch(e.type){case"TAP":return{id:nl(),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:nl(),...e};case"AI_CHECK":return{id:nl(),...e};case"TYPE":return{id:nl(),type:"TYPE",text:e.text,keyPressDelayMs:e.keyPressDelayMs??void 0,clearContent:e.clearContent??void 0};default:{let t=e;throw new Error("Unreachable")}}};import sI from"zod";var ol={type:!0,cache:!0},pn=sI.discriminatedUnion("type",[Fd.pick(ol),Bd.pick(ol),zd.pick(ol),Hd.pick(ol)]),lI=Object.values(dn).filter(r=>pn.options.some(e=>e.shape.type.safeParse(r).success));function il(r){return lI.includes(r.type)}var uy=Yi(pn),dy=Xi(pn),s5=Os(pn);import py from"zod";var al=(t=>(t.US_WEST_1="us-west1",t.EU_NORTH_1="eu-north1",t))(al||{}),sl=(e=>(e.LOCAL="local",e))(sl||{}),my=py.nativeEnum(al).or(py.nativeEnum(sl)),ma=(t=>(t.ANDROID_14="14",t.ANDROID_15="15",t))(ma||{});var gy="14";import{cloneDeep as ga}from"lodash-es";import hy from"truncate-json";var cI="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",uI=[qn,zo],fy=[qn,zo],jo=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[qn],o=e.env[zo],i={};for(let[s,c]of Object.entries(e.env))fy.includes(s)||(t??{})[s]===void 0&&(i[s]=c);return new r({dynamicVariables:i,envName:n,testName:o,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=ga(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){uI.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[qn]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ga(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>fy.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,cI]));for(let[n,o]of Object.entries(e.env)){if(!o){e.env[n]=o;continue}let{jsonString:i}=hy(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(i)}catch{e.env[n]=void 0}}let{jsonString:t}=hy(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=ga(e.variablesFromEnvironment),e.envName&&this.setMomenticSystemVariable(qn,e.envName),e.testName&&this.setMomenticSystemVariable(zo,e.testName)}getDynamicVariablesCopy(){return ga(this.env)}getVariablesFromEnvironmentCopy(){return ga(this.varsFromMomenticEnvironment)}};import rt from"zod";import{z as hr}from"zod";import{z as ze}from"zod";var gr=ze.object({id:ze.string(),name:Fo,baseUrl:Gs,description:ze.string().optional().nullish(),schemaVersion:ze.string(),advanced:aa,retries:ze.number(),envs:ze.array(Ks).nullish(),parameters:qs.nullish(),disabled:ze.boolean().optional(),labels:ze.array(ze.string()).optional().catch([])}),b5=ze.enum(["INHERIT","ENABLED","DISABLED"]);var dI=aa.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 E5=gr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:dI}),T5=gr.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),pI=ze.object({labels:ze.array(ze.string()).optional(),outputs:RS.nullish()}),Wo=gr.merge(pI),mI=ze.object({createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string().nullable(),schedule:Go,notification:Vo,createdBy:ze.string(),organizationId:ze.string(),folderId:ze.string().nullable().optional()}),gI=gr.merge(mI),v5=gI.merge(Vn),ll=gr.merge(Vn),A5=gr.merge(jn);var hI="test",fI="module",SI="mobile-test",yI="mobile-module";var xe=(o=>(o.TEST=`momentic/${hI}`,o.MODULE=`momentic/${fI}`,o.MOBILE_TEST=`momentic/${SI}`,o.MOBILE_MODULE=`momentic/${yI}`,o))(xe||{}),P5=gr.merge(jn),Sy=Xt.extend({steps:hr.array(hr.record(hr.string(),hr.unknown())),schemaVersion:hr.string()}),I5=Sy.extend({fileType:hr.literal(xe.MODULE)}),O5=hr.object({test:hr.string().describe("YAML for the test, including metadata and steps"),modules:hr.record(hr.string(),hr.string()).describe("Map of module name to YAML for the module")});var jd=rt.object({parameterNames:rt.string().array(),defaultParameters:rt.record(rt.string(),rt.string()).optional(),parameterEnums:rt.record(rt.string(),rt.string().array()).optional()}),bI=rt.object({moduleId:rt.string().uuid(),name:rt.string(),description:rt.string().nullish(),parameters:jd.optional(),enabled:rt.boolean().nullish(),schemaVersion:rt.string()}),ha=bI.omit({name:!0}),cl=ha.extend({steps:rt.array(rt.record(rt.string(),rt.unknown()))}),yy=rt.object({fileType:rt.literal(xe.MOBILE_MODULE)}).merge(cl);import wt from"zod";var Bt=(n=>(n.PRESET="MOBILE_PRESET_STEP",n.MODULE="MOBILE_MODULE_STEP",n.AI_ACTION="MOBILE_AI_ACTION_STEP",n))(Bt||{}),fa=wt.object({id:wt.string().uuid(),envKey:wt.string().optional(),skipped:wt.boolean().optional()}),Sa=fa.extend({type:wt.literal("MOBILE_PRESET_STEP"),command:ly,keyPressDelayMs:wt.number().optional()}),$o=wt.object({moduleId:wt.string(),inputs:wt.record(wt.string(),wt.string()).optional()}),ya=fa.merge($o.extend({type:wt.literal("MOBILE_MODULE_STEP")})),z5=$o.extend({steps:wt.lazy(()=>fr.array())}),ba=fa.extend({type:wt.literal("MOBILE_AI_ACTION_STEP"),text:wt.string()}),fr=wt.discriminatedUnion("type",[Sa,ya,ba]);import Me from"zod";import Ea from"zod";var Yr=(e=>(e.MODULE="RESOLVED_MOBILE_MODULE",e))(Yr||{}),Wd=$o.extend({steps:Ea.lazy(()=>qo.array()),description:Ea.string().optional(),name:Ea.string().describe("name of the module"),parameters:jd.optional()}),EI=fa.merge(Wd).extend({type:Ea.literal("RESOLVED_MOBILE_MODULE")}),qo=Ea.discriminatedUnion("type",[EI,Sa,ba]);function by(r){return Object.values(Yr).includes(r)||Object.values(Bt).includes(r)}var TI=Me.object({disableMomenticAccessibilityTree:Me.boolean().optional(),autoGrantPermissions:Me.boolean().optional()}),$d=TI.extend({region:my.optional().describe("Do you want local or Limbar?"),remoteEmulatorSettings:Me.object({androidVersion:Me.nativeEnum(ma).optional()}).optional(),localEmulatorSettings:Me.object({avdId:Me.string()}).optional(),geolocation:Me.object({latitude:Me.coerce.number().refine(r=>r>=-90&&r<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:Me.coerce.number().refine(r=>r>=-180&&r<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional()}),Ta=Me.object({retries:Me.number().optional().describe("number of retries to run"),defaultChannel:Me.string().optional().describe("default channel to use"),defaultTag:Me.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Me.string().optional(),defaultApkFilePath:Me.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:$d.optional()}),Mr=Me.object({id:Me.string().uuid(),description:Me.string(),schemaVersion:Me.string(),settings:Ta.optional()}),vI=Mr.merge(Me.object({steps:Me.array(fr)})),ul=Me.object({fileType:Me.literal(xe.MOBILE_TEST)}).merge(vI),n4=Me.object({name:Me.string(),steps:Me.array(fr).optional(),settings:Ta.optional()}),AI=Mr.extend({steps:qo.array()});import Ee from"zod";var Jn=Ee.object({startTime:Ee.number(),endTime:Ee.number().optional(),durationMs:Ee.number().optional(),error:Ee.string().optional(),result:Ee.unknown().optional(),attributes:Ee.record(Ee.string(),Ee.unknown())});var wI=Jn.extend({type:Ee.literal("SECTION"),name:Ee.string(),subSpans:Ee.lazy(()=>qd.array())}),RI=Jn.extend({type:Ee.literal("AI_LOCATOR_CALL"),result:Ee.object({id:Ee.number(),thoughts:Ee.string()}).optional()}),CI=Jn.extend({type:Ee.literal("AI_ASSERTION_CALL"),result:Ee.object({thoughts:Ee.string(),result:Ee.boolean()}).optional()}),xI=Jn.extend({type:Ee.literal("TARGET_RESOLUTION"),result:Ee.object({serializedElement:Ee.string()}).optional()}),MI=Jn.extend({type:Ee.literal("EMULATOR_INTERACTION"),name:Ee.string(),withinWebview:Ee.boolean().optional()}),_I=Jn.extend({type:Ee.literal("EMULATOR_READ_STATE"),name:Ee.string()}),PI=Jn.extend({type:Ee.literal("GENERIC"),name:Ee.string()}),qd=Ee.discriminatedUnion("type",[wI,RI,CI,xI,MI,_I,PI]);import Gt from"zod";var Kd=Gt.object({message:Gt.string().optional(),startTime:Gt.number(),endTime:Gt.number(),status:Gt.nativeEnum($e),trace:Gt.unknown(),beforeSnapshot:Gt.string().optional(),afterSnapshot:Gt.string().optional(),data:Gt.unknown().optional().describe("output data from the step")}),II=Kd.merge(Sa),OI=Kd.merge(ya).extend({steps:Gt.lazy(()=>rr.array()),name:Gt.string().optional()}),LI=Kd.merge(ba).extend({steps:Gt.lazy(()=>rr.array())}),rr=Gt.discriminatedUnion("type",[II,OI,LI]);import{parse as g4}from"date-fns";var U4=new Set(Object.values(it));var NI={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",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.",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 DI from"semver";import{z as kI}from"zod";var W4=kI.string().refine(r=>DI.valid(r),{message:"must be a valid semver string"});import{Faker as K4,en as Y4}from"@faker-js/faker";import{z as N}from"zod";var J4=N.object({body:N.string(),to:N.string(),from:N.string()}),Z4=N.object({from:N.string().optional(),to:N.string(),timeout:N.number().optional(),beforeDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional()}),Q4=N.object({to:N.string().email(),from:N.string(),subject:N.string(),body:N.string(),html:N.string().optional()}),e3=N.object({inbox:N.string().transform(r=>r.toLowerCase()),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),timeout:N.number().optional(),trimWhitespace:N.boolean().optional()}),t3=N.object({inbox:N.string(),limit:N.number().optional(),afterDate:N.string().pipe(N.coerce.date()).or(N.date()).optional(),trimWhitespace:N.boolean().optional()});var dl=(t=>(t.RAW="RAW",t.RESPONSE="RESPONSE",t))(dl||{}),Ey=N.object({body:N.string().nullish(),status:N.number().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}),UI=N.object({url:N.string(),options:N.object({method:N.string(),body:N.string().nullish(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),FI=N.object({body:N.string().nullish(),options:N.object({status:N.number(),statusText:N.string().optional(),headers:N.array(N.tuple([N.string(),N.string()])).optional()}).optional()}).optional(),Ty=N.object({result:N.unknown(),variableUpdates:N.record(N.string(),N.unknown()).optional(),persistentVariableUpdates:N.record(N.string(),N.unknown()).optional(),error:N.string().optional(),success:N.boolean()}),r3=N.object({id:N.string().optional(),orgId:N.string(),momenticLambdaAuthHash:N.string(),code:N.string(),fragment:N.boolean(),state:N.object({env:N.record(N.string(),N.unknown()),request:UI,response:FI,additionalBindings:N.record(N.string(),N.unknown()).optional()}),timeoutMs:N.number().optional(),disallowVariableUpdates:N.boolean().optional(),responseSerialization:N.nativeEnum(dl).optional()}),mn=15e3;import*as Rt from"zod";import{extendZodWithOpenApi as BI}from"zod-openapi";BI(Rt);var zI=Rt.object({url:Rt.string(),lineNumber:Rt.number(),columnNumber:Rt.number()}).openapi({ref:"CodeLocation"}),pl=Rt.object({timestamp:Rt.number(),text:Rt.string(),type:Rt.string(),tabIndex:Rt.number(),args:Rt.unknown().array().optional(),url:Rt.string().optional(),location:zI.optional()}).openapi({ref:"ConsoleLog"}),vy=pl.array(),HI=vy.array();import*as Yd from"zod";import{extendZodWithOpenApi as GI}from"zod-openapi";GI(Yd);var VI=Yd.object({logsPerPage:pl.array().array()}).openapi({ref:"DebugData"});import{z as M}from"zod";var jI=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),WI=M.object({name:M.string(),version:M.string(),comment:M.string().optional()}),$I=M.object({onContentLoad:M.number().optional(),onLoad:M.number().optional(),comment:M.string().optional()}),Xd=M.object({startedDateTime:M.string(),id:M.string(),title:M.string().optional(),pageTimings:$I,comment:M.string().optional()}),qI=M.array(Xd),KI=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()}),wy=M.array(KI),YI=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),Ry=M.array(YI),XI=M.object({name:M.string(),value:M.string(),comment:M.string().optional()}),JI=M.array(XI),ZI=M.object({name:M.string(),value:M.string().optional(),fileName:M.string().optional(),contentType:M.string().optional(),comment:M.string().optional()}),QI=M.array(ZI),eO=M.object({mimeType:M.string(),params:QI,text:M.string(),comment:M.string().optional(),_redactedReason:M.string().optional()}),tO=M.object({method:M.string(),url:M.string(),httpVersion:M.string().optional(),cookies:wy,headers:Ry,queryString:JI,postData:eO.optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional()}),rO=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()}),nO=M.object({status:M.number(),statusText:M.string(),httpVersion:M.string().optional(),cookies:wy,headers:Ry,content:rO,redirectURL:M.string().optional(),headersSize:M.number().optional(),bodySize:M.number().optional(),comment:M.string().optional(),_mocked:M.boolean().optional()}),Ay=M.object({expires:M.string().optional(),lastAccess:M.string(),eTag:M.string(),hitCount:M.number(),comment:M.string().optional()}),oO=M.object({beforeRequest:Ay.optional(),afterRequest:Ay.optional(),comment:M.string().optional()}),iO=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()}),Jd=M.object({pageref:M.string().optional(),startedDateTime:M.string(),time:M.number().optional(),request:tO,response:nO.optional(),cache:oO.optional(),timings:iO,serverIPAddress:M.string().optional(),connection:M.string().optional(),comment:M.string().optional(),_resourceType:M.string().optional()}),aO=M.array(Jd),sO=M.object({version:M.string().default("1.1"),creator:jI.optional(),browser:WI.optional(),pages:qI.optional(),entries:aO,comment:M.string().optional()}),lO=M.object({log:sO}),h3=M.record(M.string(),Xd),f3=M.record(M.string(),Jd);import{cloneDeep as cO}from"lodash-es";import{z as _r}from"zod";var xy=(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))(xy||{});var Cy=_r.union([_r.string(),_r.number(),_r.boolean(),_r.null(),_r.record(_r.string(),_r.lazy(()=>Cy)),_r.array(_r.lazy(()=>Cy))]),ml=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=cO(this.flags);return Object.entries(e).forEach(([t,n])=>{typeof n=="boolean"&&Object.values(xy).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")}},M3=new ml({},{});var Zd={".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"},My=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],P3=Object.keys(Zd);import*as _y from"zod";var O3=_y.custom().refine(r=>r&&r.length>0).refine(r=>r&&r[0]instanceof File,{message:"Please upload a valid file."});import{z as gn}from"zod";var D3=gn.object({id:gn.string(),name:gn.string(),createdAt:gn.coerce.date(),createdBy:gn.string(),updatedAt:gn.coerce.date(),updatedBy:gn.string().nullable(),organizationId:gn.string()});import{z as O}from"zod";import hn from"zod";var Ko=hn.object({platformSep:hn.string(),fullPathSegments:hn.string().array(),relativePathSegments:hn.string().array(),relativePath:hn.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:hn.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:hn.coerce.date(),createdAt:hn.coerce.date()});var uO=O.array(Ko.extend({id:O.string(),name:O.string(),description:O.string().optional(),labels:O.string().array().optional()})),dO=Ko.extend({id:O.string(),name:O.string(),description:O.string().optional(),content:dd}),pO=O.array(dO),K3=O.object({tests:uO,modules:pO,labels:O.string().array()}),Y3=ll.merge(Wo),X3=O.object({schemaVersion:O.string(),stepLists:Vn}),J3=Wo.partial().merge(gr.pick({id:!0})),mO={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(cn).optional().describe("For LLM: Never assign this variable unless the user explicitly asks for it."),viewport:Ws.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.")},Z3=O.object(mO),Q3=ll.merge(O.object({relativeFilePath:O.string().describe("relative to project root")})),eJ=O.object({name:O.string()}),tJ=O.object({relativeFilePath:O.string()}),rJ=O.object({name:O.string()}),nJ=O.object({relativeFilePath:O.string()}),oJ=O.object({name:O.string(),description:O.string(),enabled:O.boolean(),steps:O.lazy(()=>at.array()),testFilePath:O.string().describe("relative to the project root"),folderPath:O.string().optional().describe("user selected folder path")}),iJ=O.object({name:O.string(),description:O.string(),enabled:O.boolean()}).partial();var aJ=O.array(yS),sJ=O.object({defaultEnv:O.string().optional().describe("name of the default env, or undefined to unset")}),lJ=O.object({configFilePath:O.string().describe("full path on disk")}),cJ=O.string().array(),uJ=O.object({message:O.string(),newRelativeTestPath:O.string().optional()}),Qd=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()}),Py=O.object({pathSegments:O.array(O.string())}),dJ=O.object({absolutePath:O.string(),pathSegments:O.array(O.string()),contents:O.array(Qd)}),Iy=O.object({pathSegments:O.array(O.string())}),Oy=O.object({pathSegments:O.array(O.string()),newPathSegments:O.array(O.string())}),Ly=O.object({pathSegments:O.array(O.string()),recursive:O.boolean().optional()}),pJ=O.object({success:O.boolean(),message:O.string(),pathSegments:O.array(O.string()).optional()}),mJ=O.object({gitBranch:O.string(),fileMtime:O.coerce.date(),gitCommitSha:O.string()});var gl=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],hl=gl.map(r=>`**/${r}/**`),Ny=!0,Pr=!1;import Ir from"chalk";import gO from"safe-stable-stringify";import hO from"truncate-json";import fO from"zod";var Zn=gO.configure({deterministic:!1});function Dy(r){let e=Zn(r),{jsonString:t}=hO(e,5e4);return t}var SO=["app","version","env","namespace","host"];function ge(r){let e=r.bindings()??{},t={};for(let n of Object.keys(e)){let o=e[n];!SO.includes(n)&&typeof o=="string"&&(t[n]=o)}return t}var Sl=fO.enum(["debug","info","warn","error"]);var va={debug:20,info:30,warn:40,error:50},ky={20:"debug",30:"info",40:"warn",50:"error"},ep=class r{minLogLevel;logBindings;constructor(e,t){typeof e=="string"?this.minLogLevel=va[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(`
|
|
16
16
|
`).map((n,o)=>o>0?`${t}${n}`:n).join(`
|
|
17
|
-
`)}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(([
|
|
17
|
+
`)}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(([p])=>p!=="message"&&p!=="stack");for(let[p,g]of d){if(g instanceof Error){console.log(t(` ${s}.${p}:`,g.message)),g.stack&&console.log(t(` ${s}.${p}.stack:`,g.stack));continue}if(typeof g=="object"&&g!==null){let m=this.indentMultiline(Zn(g,void 0,2)," ");console.log(t(` ${s}.${p}:`,m));continue}console.log(t(` ${s}.${p}:`,g))}}else typeof c=="object"?(l=Zn(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=Zn(a,void 0,2),s=s.split(`
|
|
18
18
|
`).map((c,l)=>l>0?` ${c}`:c).join(`
|
|
19
|
-
`)),console.log(" ",t(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=va[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Ir.reset,...e)}info(...e){this.logWithLevel(30,Ir.white,...e)}debug(...e){this.logWithLevel(20,Ir.dim,...e)}warn(...e){this.logWithLevel(40,Ir.yellow,...e)}error(...e){this.logWithLevel(50,Ir.red,...e)}success(...e){this.logWithLevel(1/0,Ir.green,...e)}dimmed(...e){this.logWithLevel(30,Ir.dim,...e)}underline(...e){this.logWithLevel(40,Ir.underline,...e)}bold(...e){this.logWithLevel(40,Ir.bold,...e)}grey(...e){this.logWithLevel(20,Ir.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},em=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},SJ=new em,pO=typeof window>"u"&&typeof process<"u"&&Sl.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Sl.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,R=new Qd(pO,{}),fn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>fn,flush:async()=>{},bindings:()=>({})},fl={},yl=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=fl[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},fl[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=fl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete fl[e]},n)};import{z as le}from"zod";var gO=le.array(jo.extend({id:le.string(),name:le.string(),description:le.string().optional(),labels:le.string().array().optional()})),hO=le.array(jo.extend({id:le.string(),name:le.string(),description:le.string().optional(),content:Wd})),hy=le.object({name:le.string(),description:le.string().optional(),settings:Ta.optional(),pathSegments:le.string().array(),defaultEnv:le.string().optional()}),vJ=le.object({id:le.string(),fileName:le.string(),fullPath:le.string(),relativeFilePath:le.string().describe("relative to project root")});var fy=le.object({steps:Wo.array().optional(),settings:Ta.optional()}),AJ=le.object({message:le.literal("ok")}),Sy=le.object({tag:le.string(),channel:le.string(),filePath:le.string()}),wJ=le.object({tests:gO,modules:hO,labels:le.string().array()}),yy=le.object({name:le.string(),description:le.string(),enabled:le.boolean()}).partial(),by=le.object({name:le.string(),description:le.string(),enabled:le.boolean(),steps:Wo.array(),testFilePath:le.string().describe("relative to the project root"),folderPath:le.string().optional().describe("user selected folder path")});import{z as Xe}from"zod";var Ey=Xe.object({id:Xe.string(),createdAt:Xe.coerce.date(),createdBy:Xe.string(),organizationId:Xe.string(),name:Xe.string(),description:Xe.string().nullish(),enabled:Xe.boolean(),schemaVersion:Xe.string().describe("Schema version for steps"),parameters:Xe.string().array().nullish().describe("Parameter list"),parameterEnums:Xe.record(Xe.string(),Xe.string().array()).nullish(),defaultParameters:Xe.record(Xe.string(),Xe.string()).nullish(),defaultCacheKey:Xe.string().nullish(),defaultCacheTtl:Xe.number().nullish(),defaultCacheAllInvocations:Xe.boolean().nullish(),autoAuth:Xe.boolean().nullish(),advanced:cd.nullish()}),LJ=Ey.extend({steps:Xe.lazy(()=>Ot.array())}),NJ=5*60*1e3,fO=Yt.merge(Ey.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as UJ}from"date-fns-tz";import{z as Re}from"zod";var tm=Ad.extend({aiAction:Re.boolean().optional(),stepLintSuggestions:Re.boolean().optional(),agentConfig:Re.record(Re.string(),Re.string()).optional(),aiFailureAnalysis:Re.boolean().optional(),aiPageFiltering:Re.boolean().optional().describe("rag v2 feature flag")}),SO=Re.object({cliOnly:Re.boolean().optional()}),rm=Re.object({fakerConstantSeed:Re.boolean().optional()}),VJ=Re.object({ai:tm.optional(),githubAppInstallationId:Re.number().nullish(),githubAppSummaryMessageEnabled:Re.boolean().nullish(),githubReleaseAppInstallationId:Re.number().nullish(),gitlabAppAccessToken:Re.string().nullish(),gitlabAppBaseUrl:Re.string().nullish(),qaseAccessToken:Re.string().nullish(),testSuggestionsEnabled:Re.boolean().nullish(),browser:fd.optional(),internal:SO.optional(),advanced:rm.optional()}),WJ=Re.object({globalOverrides:Re.record(Re.string()).optional(),agentConfig:Re.record(Re.string(),Re.string()).optional()}),jJ=Re.record(Re.string(),Re.string()).nullish();import*as S from"zod";import{z as je}from"zod";var nm=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(nm||{});var yO=je.object({type:je.literal("DESCRIPTION_UPDATE"),thoughts:je.string()}),bl=je.discriminatedUnion("type",[yO]),bO=je.object({testId:je.string(),name:je.string(),orgId:je.string(),runId:je.string(),steps:it.array(),purpose:je.nativeEnum(nm),details:bl.or(bl.array()).optional()});var YJ=bO.pick({name:!0,orgId:!0}),EO=je.object({id:je.string(),name:je.string().nullish(),createdAt:je.string().pipe(je.coerce.date()).or(je.date()),organizationId:je.string(),schemaVersion:je.string(),runId:je.string().nullish(),purpose:je.nativeEnum(nm),details:bl.or(bl.array()).optional(),applied:je.boolean().nullish(),appliedAt:je.coerce.date().nullish()}),Ty=EO.extend({steps:it.array()});var El="x-momentic-cli-version",vy="x-momentic-client-mode",Ay="x-momentic-cli-type",wy="x-momentic-logger-tags",TO="x-momentic-main-branch-name",vO="x-momentic-branch-name",AO="x-momentic-commit-timestamp",wO="x-momentic-last-commit-on-main",RO="x-momentic-last-commit-on-main-timestamp",CO="x-momentic-merged-branch-name",Ry="x-momentic-session-id",m6=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),p6=pt.merge(Cd),Cy=Is,g6=pt.merge(Cd);var h6=pt.merge(gS).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),om=vh,f6=pt.merge(fS),xy=kf,S6=pt.merge(hS),My=Df,y6=pt.merge(dS),_y=Lf,b6=pt.merge(mS),Py=If,E6=pt.merge(pS);var T6=pt.merge(ES),v6=pt.merge(TS),A6=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()}),Iy=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var w6=S.string().array(),R6=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")})]),Oy=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"))}),xO=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),C6=xO.array(),x6=S.object({testId:S.string(),schemaVersion:S.string()}).merge(Vn);function im(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[TO]=encodeURIComponent(e)),t&&(a[vO]=encodeURIComponent(t)),n&&(a[AO]=n.toISOString()),o&&(a[wO]=encodeURIComponent(o)),i&&(a[RO]=i.toISOString()),r.mergedGitBranchName&&(a[CO]=encodeURIComponent(r.mergedGitBranchName)),a}var M6=S.object({entries:S.array(Vh),testId:S.string()}),_6=S.object({entries:S.array(GS),testId:S.string()}),P6=S.object({testId:S.string()});function Ly(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 Ny=Ly(Wh),Dy=Ly(VS),ky=S.object({trigger:S.nativeEnum(Zt),status:S.nativeEnum(we),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()}),I6=S.object({id:S.string()}),Uy=S.object({status:S.nativeEnum(we),updatedAt:S.coerce.date().optional(),finishedAt:S.coerce.date().optional()}),Fy=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(Zt),schemaVersion:S.string().optional(),section:S.nativeEnum(Ys).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),O6=S.object({id:S.string()}),MO=wd.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),By=MO.array(),zy=wd.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(),L6=S.object({id:S.string()}),Hy=S.object({status:S.nativeEnum(we),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()}),N6=S.object({screenshot:S.string()}),Gy=S.object({key:S.string()}),Vy=S.object({orgId:S.string(),userId:S.string()}),Wy=S.array(Yf),D6=S.record(S.string(),S.union([S.string(),S.boolean()])),k6=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),jy=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),U6=S.object({suiteRunIds:S.string().array()}),F6=sS.array(),B6=S.object({runGroupIds:S.string().array()}),_O=S.object({uploadUrl:S.string()}),z6=pt.merge(SS),H6=pt.merge(bS),G6=pt.merge(yS),PO=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()}),IO=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(ua),properties:PO}),V6=IO.array(),$y=Ty.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),W6=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),qy=oS.array(),j6=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),Ky=_O.extend({id:S.string()}),$6=S.object({runGroupId:S.string().uuid().optional()}),Yy=S.object({runGroupId:S.string().uuid()}),Xy=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),q6=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()}),K6=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Y6=pt.merge(CS),X6=pt.merge(xS),J6=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(al).optional(),osVersion:S.nativeEnum(pa).optional(),sessionId:S.string().optional()}),Jy=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()}),Z6=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),Zy=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),Qy=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 J}from"zod";var eb=7,OO=3,t8=J.object({localTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()}).or(J.object({cloudTestId:J.string(),quarantinedAt:J.date(),quarantinedBy:J.string().optional(),quarantinedReason:J.string(),quarantinedByGitEmail:J.string().optional(),quarantinedByGitName:J.string().optional(),quarantinedByGitUsername:J.string().optional()})),tb=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(tb||{});var am=J.object({name:J.string(),description:J.string().nullish(),effect:J.nativeEnum(tb),labels:J.array(J.string()).nullish(),githubRepository:J.string().nullish(),gitlabProjectPath:J.string().nullish(),gitBranchName:J.string().nullish(),slackNotificationChannel:J.string().nullish()}),LO=J.object({type:J.literal("LAST_N_RUNS"),lastN:J.number().min(OO)}),NO=J.object({type:J.literal("LAST_N_HOURS"),lastN:J.number().min(1).max(eb*24)}),DO=J.object({type:J.literal("LAST_N_DAYS"),lastN:J.number().min(1).max(eb)}),sm=J.discriminatedUnion("type",[LO,NO,DO]),kO=J.object({flakeRateThreshold:J.number().min(1).max(100),evaluationWindow:sm}),UO=am.extend({type:J.literal("FLAKE_RATE"),config:kO}),FO=J.object({passRateThreshold:J.number().min(1).max(100),evaluationWindow:sm}),BO=am.extend({type:J.literal("PASS_RATE"),config:FO}),zO=J.object({failureCountThreshold:J.number().min(0),evaluationWindow:sm}),HO=am.extend({type:J.literal("FAILURE_COUNT"),config:zO}),r8=J.discriminatedUnion("type",[UO,BO,HO]);import{z as Je}from"zod";var i8=Je.object({repositoriesIndexed:Je.boolean(),indexingInProgress:Je.boolean(),indexesOutdated:Je.boolean()}),rb=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(rb||{}),nb=(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))(nb||{}),a8=Je.object({name:Je.string(),status:Je.nativeEnum(rb),conclusion:Je.nativeEnum(nb).nullable()}),Aa=Je.object({sha:Je.string(),message:Je.string(),author:Je.object({name:Je.string().optional(),email:Je.string().optional(),date:Je.coerce.date().optional()}),committer:Je.object({name:Je.string().optional(),email:Je.string().optional(),date:Je.coerce.date().optional()})}),lm=Je.object({mergedBranch:Je.string().optional()});import{z as Be}from"zod";var ob=Be.object({orgId:Be.string(),cacheKeys:Be.string().array()}),c8=Be.object({keyParams:ob,clientMetadata:Be.string(),lockAcquisitionTimeoutMs:Be.number().optional()}),ib=Be.object({acquired:Be.boolean(),acquiredByMetadata:Be.string(),keyPrefix:Be.string()}),u8=Be.object({keyPrefix:Be.string(),result:Be.string(),ttlMs:Be.number()}),d8=Be.union([Be.object({keyPrefix:Be.string()}),ob]),GO=Be.object({remainingTtlMs:Be.number(),value:Be.string().nullish()}),m8=Be.object({results:Be.record(Be.string(),GO),activeLocks:Be.string().array()});var p8=5*60*1e3;var S8=90*24*60*60*1e3,y8=7*24*60*60*1e3;import{z as ab}from"zod";var T8=ab.object({quarantineNotifications:ab.string().nullish()});import{z as gt}from"zod";var VO=gt.object({version:gt.string(),json:gt.record(gt.unknown()),hash:gt.string()}),sb=gt.record(gt.unknown()),R8=gt.object({newSvgs:gt.array(VO),metadata:sb.optional()}),WO=gt.object({version:gt.string(),json:gt.record(gt.unknown()).nullish(),hash:gt.string(),description:gt.string().nullish(),metadata:sb.nullish()}),lb=gt.record(gt.string().describe("icon hash"),WO);import{z as Ge}from"zod";var cm=Ge.object({assertion:Ge.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),jO=Ge.object({instruction:Ge.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:cm.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.")}),cb=jO.extend({subSteps:Ge.lazy(()=>cb.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),ub=Ge.object({name:Ge.string().describe("Short name describing the test plan"),description:Ge.string().nullish().transform(r=>r??void 0).describe("Longer form description of the high level goal of the test plan")}),db=ub.extend({id:Ge.string(),createdAt:Ge.coerce.date(),updatedAt:Ge.coerce.date(),updatedBy:Ge.string(),createdBy:Ge.string(),test:Ge.object({id:Ge.string(),name:Ge.string()}).nullish().transform(r=>r??void 0)}),_8=db.extend({testGenRuns:Ge.tuple([]).or(Ge.tuple([Ge.object({id:Ge.string(),startedAt:Ge.coerce.date(),status:Ge.nativeEnum(we)})]))}),mb=Ge.object({preConditions:cm.array().nullish().transform(r=>r??[]),postConditions:cm.array().nullish().transform(r=>r??[]),steps:cb.array().nullish().transform(r=>r??[])}),P8=db.extend({plan:mb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),$O=ub.extend({plan:mb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),I8=$O.array().nullish().transform(r=>r??[]);import{validator as qO}from"@exodus/schemasafe";function pb(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{qO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var gb=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var Tl=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as K8}from"zod";var vl=class{async resolveEntries(){}async saveEntries(){}};import{z as um}from"zod";var hb=um.object({parentStepIdChain:um.array(um.string()),result:tr});import{z as q}from"zod";var KO=q.object({step:it,status:q.nativeEnum(We),startedAt:q.coerce.date(),finishedAt:q.coerce.date().optional(),healMetadata:q.object({healType:q.nativeEnum(oa).or(q.literal("AI")),healedAt:q.coerce.date()}).optional(),beforeSnapshotId:q.string().uuid().optional(),afterSnapshotId:q.string().uuid().optional(),message:q.string().optional()}),YO=KO.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),m9=YO.extend({step:q.unknown()}),fb="1.0.0",dm=Hy.extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),runAttemptSchemaVersion:q.string().optional(),schemaVersion:q.string().optional().default("1.0.19"),results:q.record(q.string(),q.unknown()).array().optional(),beforeResults:q.record(q.string(),q.unknown()).array().optional(),afterResults:q.record(q.string(),q.unknown()).array().optional(),activeVideos:q.array(q.object({videoName:q.string(),timestamp:q.coerce.date()})).optional()}),Sb=dm.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),p9=dm.merge(ia),g9=Sb.merge(ia),yb=q.object({results:q.array(tr),beforeResults:q.array(tr).optional(),afterResults:q.array(tr).optional()}),h9=dm.merge(yb),f9=Sb.merge(yb),XO=zy.merge(Fy).extend({executionType:q.nativeEnum(Fo).optional().default("WEB"),testId:q.string().uuid(),testDescription:q.string().optional(),runGroupId:q.string().uuid(),status:q.nativeEnum(we),startedAt:q.coerce.date(),attempts:q.number(),failureRecoveryDetails:q.record(q.unknown()).optional()}),S9=XO.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),JO=ky.merge(Uy).extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),cliVersion:q.string(),labels:q.string().array().optional().default([])}),Al=JO.extend({updatedAt:q.coerce.date().optional().transform(r=>r??new Date),finishedAt:q.coerce.date().optional().transform(r=>r??new Date)});import{confirm as ZO,input as QO}from"@inquirer/prompts";import{existsSync as jZ,mkdirSync as $Z,statSync as eL}from"fs";var Zn=!!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 tL=!1,bb=(()=>{try{return eL("/.dockerenv"),!0}catch{return!1}})();async function wl(r){return Zn||tL||bb?!0:(await R.flush(),await new Promise(t=>setTimeout(t,100)),await ZO({message:r}))}async function Eb(r,e){return Zn||bb?e:(await QO({message:r,default:e})).trim()||e}import Ko,{supportsColor as mL}from"chalk";import{Console as Tb}from"console";import{format as wa}from"util";var mm=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}},Rl=class r extends Tb{_buffer=[];_groupDepth=0;Console=Tb;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new mm(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
19
|
+
`)),console.log(" ",t(s))}}setMinLevel(e){typeof e=="string"?this.minLogLevel=va[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Ir.reset,...e)}info(...e){this.logWithLevel(30,Ir.white,...e)}debug(...e){this.logWithLevel(20,Ir.dim,...e)}warn(...e){this.logWithLevel(40,Ir.yellow,...e)}error(...e){this.logWithLevel(50,Ir.red,...e)}success(...e){this.logWithLevel(1/0,Ir.green,...e)}dimmed(...e){this.logWithLevel(30,Ir.dim,...e)}underline(...e){this.logWithLevel(40,Ir.underline,...e)}bold(...e){this.logWithLevel(40,Ir.bold,...e)}grey(...e){this.logWithLevel(20,Ir.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}async flush(){}bindings(){return this.logBindings}},tp=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}async flush(){}bindings(){return{}}},TJ=new tp,yO=typeof window>"u"&&typeof process<"u"&&Sl.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?Sl.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,C=new ep(yO,{}),fn={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>fn,flush:async()=>{},bindings:()=>({})},fl={},yl=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,i,...a)=>{let s=fl[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},fl[e]=s),s.totalCount++,s.count<t&&(s.count++,r.debug(o,i,...a)),s.timer=setTimeout(()=>{let c=fl[e];c?.totalCount!==c?.count&&r.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete fl[e]},n)};import{z as le}from"zod";var bO=le.array(Ko.extend({id:le.string(),name:le.string(),description:le.string().optional(),labels:le.string().array().optional()})),EO=le.array(Ko.extend({id:le.string(),name:le.string(),description:le.string().optional(),content:Wd})),Uy=le.object({name:le.string(),description:le.string().optional(),settings:Ta.optional(),pathSegments:le.string().array(),defaultEnv:le.string().optional()}),CJ=le.object({id:le.string(),fileName:le.string(),fullPath:le.string(),relativeFilePath:le.string().describe("relative to project root")});var Fy=le.object({steps:qo.array().optional(),settings:Ta.optional()}),xJ=le.object({message:le.literal("ok")}),By=le.object({tag:le.string(),channel:le.string(),filePath:le.string()}),MJ=le.object({tests:bO,modules:EO,labels:le.string().array()}),zy=le.object({name:le.string(),description:le.string(),enabled:le.boolean()}).partial(),Hy=le.object({name:le.string(),description:le.string(),enabled:le.boolean(),steps:qo.array(),testFilePath:le.string().describe("relative to the project root"),folderPath:le.string().optional().describe("user selected folder path")});import{z as Ze}from"zod";var Gy=Ze.object({id:Ze.string(),createdAt:Ze.coerce.date(),createdBy:Ze.string(),organizationId:Ze.string(),name:Ze.string(),description:Ze.string().nullish(),enabled:Ze.boolean(),schemaVersion:Ze.string().describe("Schema version for steps"),parameters:Ze.string().array().nullish().describe("Parameter list"),parameterEnums:Ze.record(Ze.string(),Ze.string().array()).nullish(),defaultParameters:Ze.record(Ze.string(),Ze.string()).nullish(),defaultCacheKey:Ze.string().nullish(),defaultCacheTtl:Ze.number().nullish(),defaultCacheAllInvocations:Ze.boolean().nullish(),autoAuth:Ze.boolean().nullish(),advanced:ud.nullish()}),UJ=Gy.extend({steps:Ze.lazy(()=>Ot.array())}),FJ=5*60*1e3,TO=Xt.merge(Gy.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as HJ}from"date-fns-tz";import{z as Ce}from"zod";var rp=wd.extend({aiAction:Ce.boolean().optional(),stepLintSuggestions:Ce.boolean().optional(),agentConfig:Ce.record(Ce.string(),Ce.string()).optional(),aiFailureAnalysis:Ce.boolean().optional(),aiPageFiltering:Ce.boolean().optional().describe("rag v2 feature flag")}),vO=Ce.object({cliOnly:Ce.boolean().optional()}),np=Ce.object({fakerConstantSeed:Ce.boolean().optional()}),qJ=Ce.object({ai:rp.optional(),githubAppInstallationId:Ce.number().nullish(),githubAppSummaryMessageEnabled:Ce.boolean().nullish(),githubReleaseAppInstallationId:Ce.number().nullish(),gitlabAppAccessToken:Ce.string().nullish(),gitlabAppBaseUrl:Ce.string().nullish(),qaseAccessToken:Ce.string().nullish(),testSuggestionsEnabled:Ce.boolean().nullish(),browser:Sd.optional(),internal:vO.optional(),advanced:np.optional()}),KJ=Ce.object({globalOverrides:Ce.record(Ce.string()).optional(),agentConfig:Ce.record(Ce.string(),Ce.string()).optional()}),YJ=Ce.record(Ce.string(),Ce.string()).nullish();import*as S from"zod";import{z as qe}from"zod";var op=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(op||{});var AO=qe.object({type:qe.literal("DESCRIPTION_UPDATE"),thoughts:qe.string()}),bl=qe.discriminatedUnion("type",[AO]),wO=qe.object({testId:qe.string(),name:qe.string(),orgId:qe.string(),runId:qe.string(),steps:at.array(),purpose:qe.nativeEnum(op),details:bl.or(bl.array()).optional()});var QJ=wO.pick({name:!0,orgId:!0}),RO=qe.object({id:qe.string(),name:qe.string().nullish(),createdAt:qe.string().pipe(qe.coerce.date()).or(qe.date()),organizationId:qe.string(),schemaVersion:qe.string(),runId:qe.string().nullish(),purpose:qe.nativeEnum(op),details:bl.or(bl.array()).optional(),applied:qe.boolean().nullish(),appliedAt:qe.coerce.date().nullish()}),Vy=RO.extend({steps:at.array()});var El="x-momentic-cli-version",jy="x-momentic-client-mode",Wy="x-momentic-cli-type",$y="x-momentic-logger-tags",CO="x-momentic-main-branch-name",xO="x-momentic-branch-name",MO="x-momentic-commit-timestamp",_O="x-momentic-last-commit-on-main",PO="x-momentic-last-commit-on-main-timestamp",IO="x-momentic-merged-branch-name",qy="x-momentic-session-id",f6=S.object({error:S.boolean(),reason:S.string(),message:S.string()}),S6=ht.merge(xd),Ky=Is,y6=ht.merge(xd);var b6=ht.merge(kS).extend({useConsensus:S.boolean().optional(),attemptNumber:S.number().optional()}),ip=Rh,E6=ht.merge(FS),Yy=oS,T6=ht.merge(US),Xy=nS,v6=ht.merge(LS),Jy=tS,A6=ht.merge(NS),Zy=Qf,w6=ht.merge(DS);var R6=ht.merge(GS),C6=ht.merge(VS),x6=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()}),Qy=S.object({queuedTests:S.unknown().array(),runIds:S.string().uuid().array(),runGroupId:S.string().optional()});var M6=S.string().array(),_6=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")})]),eb=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"))}),OO=S.object({test:S.string().describe("test YAML"),modules:S.record(S.string().describe("moduleId"),S.string().describe("module YAML"))}),P6=OO.array(),I6=S.object({testId:S.string(),schemaVersion:S.string()}).merge(jn);function ap(r){let{gitMainBranch:e,gitBranchName:t,gitCommitTimestamp:n,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=r,a={};return e&&(a[CO]=encodeURIComponent(e)),t&&(a[xO]=encodeURIComponent(t)),n&&(a[MO]=n.toISOString()),o&&(a[_O]=encodeURIComponent(o)),i&&(a[PO]=i.toISOString()),r.mergedGitBranchName&&(a[IO]=encodeURIComponent(r.mergedGitBranchName)),a}var O6=S.object({entries:S.array(ef),testId:S.string()}),L6=S.object({entries:S.array(uy),testId:S.string()}),N6=S.object({testId:S.string()});function tb(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 rb=tb(tf),nb=tb(dy),ob=S.object({trigger:S.nativeEnum(Qt),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()}),D6=S.object({id:S.string()}),ib=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(Qt),schemaVersion:S.string().optional(),section:S.nativeEnum(Ys).optional(),resolvedInputs:S.record(S.string(),S.string()).optional(),quarantined:S.boolean().optional().default(!1),quarantinedReason:S.string().optional()}),k6=S.object({id:S.string()}),LO=Rd.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),sb=LO.array(),lb=Rd.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(),U6=S.object({id:S.string()}),cb=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()}),F6=S.object({screenshot:S.string()}),ub=S.object({key:S.string()}),db=S.object({orgId:S.string(),userId:S.string()}),pb=S.array(SS),B6=S.record(S.string(),S.union([S.string(),S.boolean()])),z6=S.object({paths:S.string().array(),env:S.string().optional(),urlOverride:S.string().optional(),customHeaders:S.record(S.string(),S.string()).optional()}),mb=S.object({suiteRunIds:S.string().array(),runGroupIds:S.string().array()}),H6=S.object({suiteRunIds:S.string().array()}),G6=_S.array(),V6=S.object({runGroupIds:S.string().array()}),NO=S.object({uploadUrl:S.string()}),j6=ht.merge(BS),W6=ht.merge(HS),$6=ht.merge(zS),DO=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()}),kO=S.object({transactionId:S.string(),timestamp:S.string(),event:S.nativeEnum(ua),properties:DO}),q6=kO.array(),gb=Vy.omit({steps:!0}).extend({steps:S.array(S.record(S.string(),S.unknown())).describe("unparsed ResolvedStep[]")}),K6=S.object({limit:S.number().max(10).optional(),afterTime:S.number().optional()}),hb=CS.array(),Y6=S.object({applied:S.boolean().optional(),appliedAt:S.coerce.date().optional()}),fb=NO.extend({id:S.string()}),X6=S.object({runGroupId:S.string().uuid().optional()}),Sb=S.object({runGroupId:S.string().uuid()}),yb=S.object({quarantined:S.object({testId:S.string().uuid(),quarantinedAt:S.coerce.date(),quarantinedBy:S.string().optional(),quarantinedReason:S.string()}).array()}),J6=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()}),Z6=S.object({testName:S.string().optional(),reason:S.string().optional(),gitLocalUsername:S.string().optional(),gitLocalEmail:S.string().optional(),gitLocalName:S.string().optional()}),Q6=ht.merge(KS),e8=ht.merge(YS),t8=S.object({apkToInstall:S.object({channel:S.string(),tag:S.string().optional()}).optional(),hostname:S.string().optional(),region:S.nativeEnum(al).optional(),osVersion:S.nativeEnum(ma).optional(),sessionId:S.string().optional()}),bb=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()}),r8=S.object({channel:S.string(),tag:S.string(),md5:S.string()}),Eb=S.object({id:S.string(),uploadUrl:S.string().optional(),downloadUrl:S.string(),md5:S.string().optional()}),Tb=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 vb=7,UO=3,i8=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()})),Ab=(t=>(t.QUARANTINE="QUARANTINE",t.UNQUARANTINE="UNQUARANTINE",t))(Ab||{});var sp=Z.object({name:Z.string(),description:Z.string().nullish(),effect:Z.nativeEnum(Ab),labels:Z.array(Z.string()).nullish(),githubRepository:Z.string().nullish(),gitlabProjectPath:Z.string().nullish(),gitBranchName:Z.string().nullish(),slackNotificationChannel:Z.string().nullish()}),FO=Z.object({type:Z.literal("LAST_N_RUNS"),lastN:Z.number().min(UO)}),BO=Z.object({type:Z.literal("LAST_N_HOURS"),lastN:Z.number().min(1).max(vb*24)}),zO=Z.object({type:Z.literal("LAST_N_DAYS"),lastN:Z.number().min(1).max(vb)}),lp=Z.discriminatedUnion("type",[FO,BO,zO]),HO=Z.object({flakeRateThreshold:Z.number().min(1).max(100),evaluationWindow:lp}),GO=sp.extend({type:Z.literal("FLAKE_RATE"),config:HO}),VO=Z.object({passRateThreshold:Z.number().min(1).max(100),evaluationWindow:lp}),jO=sp.extend({type:Z.literal("PASS_RATE"),config:VO}),WO=Z.object({failureCountThreshold:Z.number().min(0),evaluationWindow:lp}),$O=sp.extend({type:Z.literal("FAILURE_COUNT"),config:WO}),a8=Z.discriminatedUnion("type",[GO,jO,$O]);import{z as Qe}from"zod";var c8=Qe.object({repositoriesIndexed:Qe.boolean(),indexingInProgress:Qe.boolean(),indexesOutdated:Qe.boolean()}),wb=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))(wb||{}),Rb=(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))(Rb||{}),u8=Qe.object({name:Qe.string(),status:Qe.nativeEnum(wb),conclusion:Qe.nativeEnum(Rb).nullable()}),Aa=Qe.object({sha:Qe.string(),message:Qe.string(),author:Qe.object({name:Qe.string().optional(),email:Qe.string().optional(),date:Qe.coerce.date().optional()}),committer:Qe.object({name:Qe.string().optional(),email:Qe.string().optional(),date:Qe.coerce.date().optional()})}),cp=Qe.object({mergedBranch:Qe.string().optional()});import{z as He}from"zod";var Cb=He.object({orgId:He.string(),cacheKeys:He.string().array()}),m8=He.object({keyParams:Cb,clientMetadata:He.string(),lockAcquisitionTimeoutMs:He.number().optional()}),xb=He.object({acquired:He.boolean(),acquiredByMetadata:He.string(),keyPrefix:He.string()}),g8=He.object({keyPrefix:He.string(),result:He.string(),ttlMs:He.number()}),h8=He.union([He.object({keyPrefix:He.string()}),Cb]),qO=He.object({remainingTtlMs:He.number(),value:He.string().nullish()}),f8=He.object({results:He.record(He.string(),qO),activeLocks:He.string().array()});var S8=5*60*1e3;var T8=90*24*60*60*1e3,v8=7*24*60*60*1e3;import{z as Mb}from"zod";var R8=Mb.object({quarantineNotifications:Mb.string().nullish()});import{z as ft}from"zod";var KO=ft.object({version:ft.string(),json:ft.record(ft.unknown()),hash:ft.string()}),_b=ft.record(ft.unknown()),_8=ft.object({newSvgs:ft.array(KO),metadata:_b.optional()}),YO=ft.object({version:ft.string(),json:ft.record(ft.unknown()).nullish(),hash:ft.string(),description:ft.string().nullish(),metadata:_b.nullish()}),Pb=ft.record(ft.string().describe("icon hash"),YO);import{z as je}from"zod";var up=je.object({assertion:je.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),XO=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:up.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.")}),Ib=XO.extend({subSteps:je.lazy(()=>Ib.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Ob=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")}),Lb=Ob.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)}),L8=Lb.extend({testGenRuns:je.tuple([]).or(je.tuple([je.object({id:je.string(),startedAt:je.coerce.date(),status:je.nativeEnum(Re)})]))}),Nb=je.object({preConditions:up.array().nullish().transform(r=>r??[]),postConditions:up.array().nullish().transform(r=>r??[]),steps:Ib.array().nullish().transform(r=>r??[])}),N8=Lb.extend({plan:Nb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),JO=Ob.extend({plan:Nb.nullish().transform(r=>r??{preConditions:[],postConditions:[],steps:[]})}),D8=JO.array().nullish().transform(r=>r??[]);import{validator as ZO}from"@exodus/schemasafe";function Db(r){let e;try{e=JSON.parse(r)}catch(t){return`The schema is not valid JSON. ${t}`}try{ZO(e)}catch(t){return`The schema is not a valid JSON schema. ${t}`}}var kb=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var Tl=class{async prepareGoldenScreenshotForComparison(e,t,n){return n}};import{z as Z8}from"zod";var vl=class{async resolveEntries(){}async saveEntries(){}};import{z as dp}from"zod";var Ub=dp.object({parentStepIdChain:dp.array(dp.string()),result:rr});import{z as q}from"zod";var QO=q.object({step:at,status:q.nativeEnum($e),startedAt:q.coerce.date(),finishedAt:q.coerce.date().optional(),healMetadata:q.object({healType:q.nativeEnum(oa).or(q.literal("AI")),healedAt:q.coerce.date()}).optional(),beforeSnapshotId:q.string().uuid().optional(),afterSnapshotId:q.string().uuid().optional(),message:q.string().optional()}),eL=QO.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),f9=eL.extend({step:q.unknown()}),Fb="1.0.0",pp=cb.extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),runAttemptSchemaVersion:q.string().optional(),schemaVersion:q.string().optional().default("1.0.19"),results:q.record(q.string(),q.unknown()).array().optional(),beforeResults:q.record(q.string(),q.unknown()).array().optional(),afterResults:q.record(q.string(),q.unknown()).array().optional(),activeVideos:q.array(q.object({videoName:q.string(),timestamp:q.coerce.date()})).optional()}),Bb=pp.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),S9=pp.merge(ia),y9=Bb.merge(ia),zb=q.object({results:q.array(rr),beforeResults:q.array(rr).optional(),afterResults:q.array(rr).optional()}),b9=pp.merge(zb),E9=Bb.merge(zb),tL=lb.merge(ab).extend({executionType:q.nativeEnum(Ho).optional().default("WEB"),testId:q.string().uuid(),testDescription:q.string().optional(),runGroupId:q.string().uuid(),status:q.nativeEnum(Re),startedAt:q.coerce.date(),attempts:q.number(),failureRecoveryDetails:q.record(q.unknown()).optional()}),T9=tL.extend({finishedAt:q.coerce.date().optional().transform(r=>r??new Date)}),rL=ob.merge(ib).extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),cliVersion:q.string(),labels:q.string().array().optional().default([])}),Al=rL.extend({updatedAt:q.coerce.date().optional().transform(r=>r??new Date),finishedAt:q.coerce.date().optional().transform(r=>r??new Date)});import{confirm as nL,input as oL}from"@inquirer/prompts";import{existsSync as YZ,mkdirSync as XZ,statSync as iL}from"fs";var Qn=!!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 aL=!1,Hb=(()=>{try{return iL("/.dockerenv"),!0}catch{return!1}})();async function wl(r){return Qn||aL||Hb?!0:(await C.flush(),await new Promise(t=>setTimeout(t,100)),await nL({message:r}))}async function Gb(r,e){return Qn||Hb?e:(await oL({message:r,default:e})).trim()||e}import Jo,{supportsColor as SL}from"chalk";import{Console as Vb}from"console";import{format as wa}from"util";var mp=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}},Rl=class r extends Vb{_buffer=[];_groupDepth=0;Console=Vb;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let i=new mp(void 0,r.write).stack;if(!i)return e;let a=i.split(`
|
|
20
20
|
`).slice(o).filter(Boolean).join(`
|
|
21
|
-
`);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",wa(e,...t))}error(e,...t){this._log("error",wa(e,...t))}info(e,...t){this._log("info",wa(e,...t))}log(e,...t){this._log("log",wa(e,...t))}warn(e,...t){this._log("warn",wa(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function
|
|
21
|
+
`);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",wa(e,...t))}error(e,...t){this._log("error",wa(e,...t))}info(e,...t){this._log("info",wa(e,...t))}log(e,...t){this._log("log",wa(e,...t))}warn(e,...t){this._log("warn",wa(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function jb(r){let e=globalThis.console,t=new Rl;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
22
22
|
`);process.stderr.write(`${o}
|
|
23
|
-
`),globalThis.console=e}}var pm=" ".repeat(6);import rL from"fetch-retry";import nL from"os";import Ab,{multistream as oL}from"pino";import iL from"pino-pretty";import aL from"pino-std-serializers";var $o=new Map,sL=!0,wb="Log throttle exceeded",lL=100,cL=5e3,uL=rL(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}}),gm=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??nL.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=sL?Ab(a):Ab(a,oL([{stream:iL({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 uL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Jn(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===wb)return!0;let t=Date.now();return t-this.lastWindowStart>cL&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,wb),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<lL?(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(va[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=aL.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:py({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,$o.set("app",this),$o.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=gy[e]):(this.minLevelValue=va[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},qo=({app:r,hostname:e,disableConsoleLogs:t})=>($o.has(r)||$o.set(r,new gm({bindings:{app:r},hostname:e,disableConsoleLogs:t})),$o.get(r));async function Rb(){await Promise.all([...$o.values()].map(r=>r.flush()))}import{hostname as dL}from"os";var rr=qo({app:"cli",hostname:dL(),disableConsoleLogs:!0}).child({cliVersion:"0.7.2"});function hm(r){if(!r)return;r=r.toLowerCase();let e=Sl.safeParse(r);if(e.success)return R.setMinLevel(e.data),e.data}function Cb({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 vb(()=>{if(c.forEach(u=>{R.log(""),o(u)}),c.length){R.log("");let u=c.length===1?"":"s";R.error(`${c.length} ${t}${u} failed:`),c.forEach(d=>{R.dimmed(n(d))})}if(l.length){R.log("");let u=l.length===1?"":"s";R.warn(`${l.length} ${t}${u} cancelled:`),l.forEach(d=>{R.dimmed(n(d))})}if(a.length){R.log("");let u=a.length===1?"":"s";R.success(`${a.length} ${t}${u} passed:`),a.forEach(d=>{R.dimmed(n(d))})}if(s.length){R.log("");let u=s.length===1?"":"s";R.warn(`${s.length} quarantined ${t}${u} failed:`),s.forEach(d=>{R.dimmed(n(d))})}if(i.length){R.log("");let u=i.length===1?"":"s";R.warn(`${i.length} quarantined ${t}${u} passed:`),i.forEach(d=>{R.dimmed(n(d))})}R.log(""),R.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 Ra=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Ko.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Ko.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Ko.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Ko.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Ko.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Ko.bgMagenta.white("RUNNING"),a=0):(R.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),mL||(i=`${i}`),R.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import pL from"fs";import{tmpdir as gL}from"os";import hL from"path";import{registry as Ca}from"playwright-core/lib/server";import xb from"proper-lockfile";var Mb=hL.join(gL(),"momenticBrowserInstallation");var fm=["chrome","chromium","chrome-for-testing","ffmpeg"],fL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},_b={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function Pb(r){let e=_b[fL[r]??""]??"",t=Ca.findExecutable(e);return!t||t.installType==="none"?!1:Sm(t)}function Sm(r){let e=r.executablePath();return pL.existsSync(e)}function SL(r,e){let t=_b[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Ca.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&Sm(n)))return n}async function yL({browser:r,force:e}){let t=SL(r,e);if(!t){R.info(`Browser '${r}' is already installed, skipping...`);return}R.info(`Installing browser '${r}'...`);try{await Ca.installDeps([t],!1),await Ca.install([t],!1)}catch(n){if(n.message.includes("Lock file is already being held")){R.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Ca.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!Sm(o);)R.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Cl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?fm:Array.from(new Set(r));try{await xb.lock(Mb,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){R.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 yL({browser:i,force:e})}catch(a){o=a,R.error(`Failed to install the ${i} browser: ${a}`)}}finally{await xb.unlock(Mb,{realpath:!1})}if(o)throw o}import{createServer as bL}from"http";async function xl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await Ml(o))return o}R.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function Ml(r){return new Promise((e,t)=>{let n=bL();n.once("error",o=>{o.code==="EADDRINUSE"?e(!1):(R.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 JQ from"blocked-at";import QQ from"why-is-node-running";import Xk from"fs";import{tmpdir as Jk}from"os";import Zk from"path";import{remote as Qk}from"webdriverio";import{createInstanceClient as Vk}from"@limrun/api";import{execSync as Wk}from"child_process";import u7,{multistream as m7}from"pino";import g7 from"pino-pretty";var S7=5*1024,EL="...[truncated]",y7=Buffer.byteLength(EL,"utf8");import{PostHog as M7}from"posthog-node";var Sn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ib=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(Ib(m));l=()=>c(Ib(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 Sn(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 U7}from"posthog-node";import{execSync as TL}from"child_process";import Yo from"os";import vL from"v8";var Ob,Or,Nb=Yo.platform(),AL=Yo.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),{}),Lb=r=>{try{let e={},t=!1,n=wL(),o=RL(),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=vL.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"),Zn&&R.warn(`Low machine resources detected (memory: ${i} free, cpu: ${a} free)`)):r.debug({memory:n,cpu:o},"Got machine resource usage metrics")}catch{}};function Db(r){if(!Pr)return Lb(r),{interval:setInterval(()=>Lb(r),2e4),cpuMetadata:AL,platform:Nb}}function wL(){let r=Yo.totalmem(),e=Nb==="darwin"?CL():(()=>{let n=Yo.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function RL(){let r=Yo.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,!Or)return Or=t,null;let n={user:t.user-Or.user,nice:t.nice-Or.nice,sys:t.sys-Or.sys,idle:t.idle-Or.idle,irq:t.irq-Or.irq,total:t.total-Or.total};return Ob={measurementTime:e,intervalMs:e-Or.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},Or=t,Ob}function CL(){try{let r=TL("/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=Yo.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var _l=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function xL(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 Pl(r,e){let t=xL(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var lE="=",Nl=";",_m=",";var cE=8192;var Qo={};xx(Qo,{getKeyPairs:()=>aN,parseKeyPairsIntoRecord:()=>sN,parsePairKeyValue:()=>uE,serializeKeyPairs:()=>iN});_e();var oN=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 iN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?_m:"")+t;return n.length>cE?e:n},"")}function aN(r){return r.getAllEntries().map(function(e){var t=oN(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Nl+o.metadata.toString()),i})}function uE(r){var e=r.split(Nl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(lE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=bm(e.join(Nl))),{key:o,value:i,metadata:a}}}}}function sN(r){return typeof r!="string"||r.length===0?{}:r.split(_m).map(function(e){return uE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}_e();var Dl;(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"})(Dl||(Dl={}));var lN=",",cN=["OTEL_SDK_DISABLED"];function uN(r){return cN.indexOf(r)>-1}var dN=["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 mN(r){return dN.indexOf(r)>-1}var pN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function gN(r){return pN.indexOf(r)>-1}var Pm=1/0,Im=128,hN=128,fN=128,Om={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:Ne.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Pm,OTEL_ATTRIBUTE_COUNT_LIMIT:Im,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Pm,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Im,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Pm,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Im,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:hN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:fN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Dl.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 SN(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function yN(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 bN(r,e,t,n){n===void 0&&(n=lN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var EN={ALL:Ne.ALL,VERBOSE:Ne.VERBOSE,DEBUG:Ne.DEBUG,INFO:Ne.INFO,WARN:Ne.WARN,ERROR:Ne.ERROR,NONE:Ne.NONE};function TN(r,e,t){var n=t[r];if(typeof n=="string"){var o=EN[n.toUpperCase()];o!=null&&(e[r]=o)}}function dE(r){var e={};for(var t in Om){var n=t;switch(n){case"OTEL_LOG_LEVEL":TN(n,e,r);break;default:if(uN(n))SN(n,e,r);else if(mN(n))yN(n,e,r);else if(gN(n))bN(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function ht(){var r=dE(process.env);return Object.assign({},Om,r)}function mE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function kl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=mE(r.charCodeAt(n)),i=mE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var pE="1.25.1";var vN="deployment.environment";var AN="process.runtime.name";var wN="service.name";var RN="service.instance.id";var CN="telemetry.sdk.name",xN="telemetry.sdk.language",MN="telemetry.sdk.version";var gE=vN;var hE=AN;var Ul=wN;var fE=RN;var La=CN,Na=xN,Da=MN;var _N="nodejs";var SE=_N;var ei,Fl=(ei={},ei[La]="opentelemetry",ei[hE]="node",ei[Na]=SE,ei[Da]=pE,ei);var PN=9,IN=6,ON=Math.pow(10,IN),LN=Math.pow(10,PN);function yE(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*ON);return[t,n]}function bE(r){return r[0]*LN+r[1]}function ka(r){return r[0]*1e6+r[1]/1e3}var eo;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(eo||(eo={}));var EE=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 NN=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},DN=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))},TE=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new EE}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,DN([this._that],NN(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 nr;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(nr||(nr={}));var Rt;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Rt||(Rt={}));var kN=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 sre=function(r){kN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function vE(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}_e();var or;(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"})(or||(or={}));var AE=function(){function r(){this.kind=or.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 oe;(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"})(oe||(oe={}));var 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};function FN(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 Lm=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=FN(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=vE(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 Nm=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=or.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Lm(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 Lm(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 Lm(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:Rt.HISTOGRAM,dataPoints:n.map(function(i){var a=UN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.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}();_e();var Dm=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))},Um=function(){function r(e,t,n,o){e===void 0&&(e=new BN),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 BN=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],Dm(this._counts.slice(t)),!1)),o.splice.apply(o,km([0,t],Dm(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([],Dm(this._counts),!1))},r}();var wE=52,zN=2146435072,HN=1048575,Fm=1023,Bl=-Fm+1,zl=Fm,Ua=Math.pow(2,-1022);function Hl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&zN)>>20;return n-Fm}function Gl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&HN)*Math.pow(2,32);return o+n}function Fa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function CE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var GN=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)}}(),yn=function(r){GN(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var ME=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ua)return this._minNormalLowerBoundaryIndex();var t=Hl(e),n=this._rightShift(Gl(e)-1,wE);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new yn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new yn("overflow: "+e+" is > maximum lower boundary: "+n);return Fa(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=Bl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return zl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var _E=function(){function r(e){this._scale=e,this._scaleFactor=Fa(Math.LOG2E,e),this._inverseFactor=Fa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ua)return this._minNormalLowerBoundaryIndex()-1;if(Gl(e)===0){var t=Hl(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 yn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ua;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new yn("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 Bl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(zl+1<<this._scale)-1},r}();var PE=-10,IE=20,VN=Array.from({length:31},function(r,e){return e>10?new _E(e-10):new ME(e-10)});function Bm(r){if(r>IE||r<PE)throw new yn("expected scale >= "+PE+" && <= "+IE+", got: "+r);return VN[r+10]}var WN=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},Vl=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}(),jN=20,$N=160,zm=2,qN=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=$N),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 Um),u===void 0&&(u=new Um),d===void 0&&(d=Bm(jN)),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<zm&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+zm),this._maxSize=zm)}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=CE(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=Bm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Vl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Vl.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 Vl(0,-1);var o=t-n;return new Vl(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 OE=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=or.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new qN(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:Rt.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=WN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===oe.GAUGE||e.type===oe.UP_DOWN_COUNTER||e.type===oe.OBSERVABLE_GAUGE||e.type===oe.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 KN=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},Hm=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=yE(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var LE=function(){function r(){this.kind=or.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Hm(e)},r.prototype.merge=function(e,t){var n=ka(t.sampleTime)>=ka(e.sampleTime)?t:e;return new Hm(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ka(t.sampleTime)>=ka(e.sampleTime)?t:e;return new Hm(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Rt.GAUGE,dataPoints:n.map(function(i){var a=KN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var YN=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},Ba=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 Gm=function(){function r(e){this.monotonic=e,this.kind=or.SUM}return r.prototype.createAccumulation=function(e){return new Ba(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ba(t.startTime,this.monotonic,o,t.reset):new Ba(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 Ba(t.startTime,this.monotonic,o,!0):new Ba(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Rt.SUM,dataPoints:n.map(function(i){var a=YN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var to=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)}}(),Nr=function(){function r(){}return r.Drop=function(){return HE},r.Sum=function(){return GE},r.LastValue=function(){return VE},r.Histogram=function(){return WE},r.ExponentialHistogram=function(){return XN},r.Default=function(){return JN},r}();var NE=function(r){to(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 AE,e}(Nr);var DE=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Gm(!0),e.NON_MONOTONIC_INSTANCE=new Gm(!1),e}(Nr);var kE=function(r){to(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 LE,e}(Nr);var UE=function(r){to(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 Nm([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Nr);var FE=function(r){to(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 Nm(this._boundaries,this._recordMinMax)},e}(Nr);var BE=function(r){to(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 OE(this._maxSize,this._recordMinMax)},e}(Nr);var zE=function(r){to(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case oe.COUNTER:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return GE;case oe.GAUGE:case oe.OBSERVABLE_GAUGE:return VE;case oe.HISTOGRAM:return t.advice.explicitBucketBoundaries?new FE(t.advice.explicitBucketBoundaries):WE}return H.warn("Unable to recognize instrument type: "+t.type),HE},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Nr);var HE=new NE,GE=new DE,VE=new kE,WE=new UE,XN=new BE,JN=new zE;_e();function Wl(){return"unknown_service:"+process.argv0}var bn=function(){return bn=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},bn.apply(this,arguments)},ZN=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())})},QN=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}}},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},Vm=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[Ul]=Wl(),e[Na]=Fl[Na],e[La]=Fl[La],e[Da]=Fl[Da],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 ZN(this,void 0,void 0,function(){return QN(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=bn(bn({},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=eD(a,2),l=c[0],u=c[1];return bn(bn(bn(bn({},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 ro;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(ro||(ro={}));_e();var tD=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())})},rD=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}}},Wm=function(){return nr.CUMULATIVE},jE=function(r){switch(r){case oe.COUNTER:case oe.OBSERVABLE_COUNTER:case oe.GAUGE:case oe.HISTOGRAM:case oe.OBSERVABLE_GAUGE:return nr.DELTA;case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:return nr.CUMULATIVE}},$E=function(r){switch(r){case oe.COUNTER:case oe.HISTOGRAM:return nr.DELTA;case oe.GAUGE:case oe.UP_DOWN_COUNTER:case oe.OBSERVABLE_UP_DOWN_COUNTER:case oe.OBSERVABLE_COUNTER:case oe.OBSERVABLE_GAUGE:return nr.CUMULATIVE}};function nD(){var r=ht(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Wm:e==="delta"?jE:e==="lowmemory"?$E:(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."),Wm)}function oD(r){return r!=null?r===ro.DELTA?jE:r===ro.LOWMEMORY?$E:Wm:nD()}function iD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Nr.Default()}}var qE=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=iD(t),this._aggregationTemporalitySelector=oD(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return tD(this,void 0,void 0,function(){return rD(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}();_e();_e();var aD=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},KE=1e4,YE=5,XE=1e3,JE=5e3,ZE=1.5;function za(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=aD(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 jm(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function $m(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 qm(r){return typeof r=="number"?r<=0?Km(r,KE):r:sD()}function sD(){var r,e=Number((r=ht().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:ht().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Km(e,KE):e}function Km(r,e){return H.warn("Timeout must be greater than 0",r),e}function QE(r){var e=[429,502,503,504];return e.includes(r)}function eT(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 tT=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 TE(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=qm(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:eo.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:eo.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:eo.SUCCESS})}).catch(function(n){t({code:eo.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}();_e();import*as Ym from"url";import*as $l from"http";import*as ql from"https";import*as rT from"zlib";import{Readable as cD}from"stream";var En;(function(r){r.NONE="none",r.GZIP="gzip"})(En||(En={}));var lD=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(r){lD(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 jl=function(){return jl=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},jl.apply(this,arguments)};function Xm(r,e,t,n,o){var i=r.timeoutMillis,a=new Ym.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 ti("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:jl({"Content-Type":t},r.headers),agent:r.agent},p=a.protocol==="http:"?$l.request:ql.request,g=function(h,f){switch(h===void 0&&(h=YE),f===void 0&&(f=XE),l=p(m,function(b){var x="";b.on("data",function(T){return x+=T}),b.on("aborted",function(){if(u){var T=new ti("Request Timeout");o(T)}}),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&&QE(b.statusCode)&&h>0){var T=void 0;f=ZE*f,b.headers["retry-after"]?T=eT(b.headers["retry-after"]):T=Math.round(Math.random()*(JE-f)+f),c=setTimeout(function(){g(h-1,f)},T)}else{var v=new ti(b.statusMessage,b.statusCode,x);o(v),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var x=new ti("Request Timeout",b.code);o(x)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new ti("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case En.GZIP:{l.setHeader("Content-Encoding","gzip");var E=uD(e);E.on("error",o).pipe(rT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};g()}function uD(r){var e=new cD;return e.push(r),e.push(null),e}function Jm(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 Ym.URL(r.url),t=e.protocol==="http:"?$l.Agent:ql.Agent;return new t(jl({keepAlive:!0},r.httpAgentOptions))}catch(n){H.error("collector exporter failed to create http agent. err: "+n.message);return}}function Zm(r){if(r)return r;var e=ht().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||ht().OTEL_EXPORTER_OTLP_COMPRESSION;return e===En.GZIP?En.GZIP:En.NONE}_e();var dD=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)}}(),Kl=function(r){dD(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,za(t.headers),Qo.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Jm(t),i.compression=Zm(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;Xm(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}(tT);function oT(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function mD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function iT(r){var e=oT(r);return mD(e)}function pD(r){var e=oT(r);return e.toString()}var gD=typeof BigInt<"u"?pD:bE;function nT(r){return r}function aT(r){if(r!==void 0)return kl(r)}var hD={encodeHrTime:iT,encodeSpanContext:kl,encodeOptionalSpanContext:aT};function sT(r){var e,t;if(r===void 0)return hD;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?iT:gD,encodeSpanContext:o?nT:kl,encodeOptionalSpanContext:o?nT:aT}}var fD=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 lT(r){return{name:r.name,version:r.version}}function ri(r){return Object.keys(r).map(function(e){return cT(e,r[e])})}function cT(r,e){return{key:r,value:uT(e)}}function uT(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(uT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=fD(t,2),o=n[0],i=n[1];return cT(o,i)})}}:{}}function dT(r){return{attributes:ri(r.attributes),droppedAttributesCount:0}}_e();function pT(r,e){var t=sT(e);return{resource:dT(r.resource),schemaUrl:void 0,scopeMetrics:SD(r.scopeMetrics,t)}}function SD(r,e){return Array.from(r.map(function(t){return{scope:lT(t.scope),metrics:t.metrics.map(function(n){return yD(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function yD(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=vD(r.aggregationTemporality);switch(r.dataPointType){case Rt.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:mT(r,e)};break;case Rt.GAUGE:t.gauge={dataPoints:mT(r,e)};break;case Rt.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:ED(r,e)};break;case Rt.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:TD(r,e)};break}return t}function bD(r,e,t){var n={attributes:ri(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Gt.INT:n.asInt=r.value;break;case Gt.DOUBLE:n.asDouble=r.value;break}return n}function mT(r,e){return r.dataPoints.map(function(t){return bD(t,r.descriptor.valueType,e)})}function ED(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ri(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 TD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ri(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 vD(r){switch(r){case nr.DELTA:return 1;case nr.CUMULATIVE:return 2}}function gT(r,e){return{resourceMetrics:r.map(function(t){return pT(t,e)})}}var Qm={serializeRequest:function(r){var e=gT(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 hT="0.52.1";var fT=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)}}(),ni=function(){return ni=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},ni.apply(this,arguments)},ST="v1/metrics",AD="http://localhost:4318/"+ST,wD={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+hT},RD=function(r){fT(e,r);function e(t){var n=r.call(this,t,Qm,"application/json")||this;return n.headers=ni(ni(ni(ni({},n.headers),wD),Qo.parseKeyPairsIntoRecord(ht().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),za(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?$m(ht().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):ht().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?jm(ht().OTEL_EXPORTER_OTLP_ENDPOINT,ST):AD},e}(Kl),yT=function(r){fT(e,r);function e(t){return r.call(this,new RD(t),t)||this}return e}(qE);var oi;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(oi||(oi={}));var Dr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Dr||(Dr={}));_e();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)}}(),bT=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())})},ET=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}}},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},MD=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))},_D=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 TT(r){return r!=null}function Yl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function vT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var ep=function(r){CD(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Tn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new ep("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function AT(r){return bT(this,void 0,void 0,function(){var e=this;return ET(this,function(t){return[2,Promise.all(r.map(function(n){return bT(e,void 0,void 0,function(){var o,i;return ET(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 wT(r){return r.status==="rejected"}function tp(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,MD([],xD(e(n)),!1))}),t}function RT(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=_D(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 CT(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 xT(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var ir;(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"})(ir||(ir={}));var rp=function(){function r(){this.kind=ir.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}();_e();var ge;(function(r){r.COUNTER="COUNTER",r.GAUGE="GAUGE",r.HISTOGRAM="HISTOGRAM",r.UP_DOWN_COUNTER="UP_DOWN_COUNTER",r.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",r.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",r.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"})(ge||(ge={}));function kr(r,e,t){var n,o,i,a;return ID(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:Gt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function MT(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 _T(r,e){return xT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var PD=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function ID(r){return r.match(PD)!=null}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};function LD(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 Xl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=LD(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=CT(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 Jl=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Xl(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 Xl(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 Xl(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:Dr.HISTOGRAM,dataPoints:n.map(function(i){var a=OD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ge.GAUGE||e.type===ge.UP_DOWN_COUNTER||e.type===ge.OBSERVABLE_GAUGE||e.type===ge.OBSERVABLE_UP_DOWN_COUNTER;return{attributes: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}();_e();var np=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},op=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))},ip=function(){function r(e,t,n,o){e===void 0&&(e=new ND),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 ND=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,op([n,this._counts.length-t],np(this._counts.slice(t)),!1)),o.splice.apply(o,op([0,t],np(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(op([],np(this._counts),!1))},r}();var PT=52,DD=2146435072,kD=1048575,ap=1023,Zl=-ap+1,Ql=ap,Ha=Math.pow(2,-1022);function ec(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&DD)>>20;return n-ap}function tc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&kD)*Math.pow(2,32);return o+n}function Ga(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function OT(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var UD=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)}}(),vn=function(r){UD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var NT=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ha)return this._minNormalLowerBoundaryIndex();var t=ec(e),n=this._rightShift(tc(e)-1,PT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new vn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new vn("overflow: "+e+" is > maximum lower boundary: "+n);return Ga(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=Zl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Ql>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var DT=function(){function r(e){this._scale=e,this._scaleFactor=Ga(Math.LOG2E,e),this._inverseFactor=Ga(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ha)return this._minNormalLowerBoundaryIndex()-1;if(tc(e)===0){var t=ec(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 vn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ha;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new vn("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 Zl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Ql+1<<this._scale)-1},r}();var kT=-10,UT=20,FD=Array.from({length:31},function(r,e){return e>10?new DT(e-10):new NT(e-10)});function sp(r){if(r>UT||r<kT)throw new vn("expected scale >= "+kT+" && <= "+UT+", got: "+r);return FD[r+10]}var BD=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},rc=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}(),zD=20,HD=160,lp=2,FT=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=HD),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 ip),u===void 0&&(u=new ip),d===void 0&&(d=sp(zD)),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<lp&&(H.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+lp),this._maxSize=lp)}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=OT(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=sp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=rc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=rc.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 rc(0,-1);var o=t-n;return new rc(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 cp=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new FT(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:Dr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=BD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ge.GAUGE||e.type===ge.UP_DOWN_COUNTER||e.type===ge.OBSERVABLE_GAUGE||e.type===ge.OBSERVABLE_UP_DOWN_COUNTER;return{attributes: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}();_e();var GD=Em("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function BT(r){return r.setValue(GD,!0)}_e();function zT(){return function(r){H.error(VD(r))}}function VD(r){return typeof r=="string"?r:JSON.stringify(WD(r))}function WD(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 jD=zT();function nc(r){try{jD(r)}catch{}}var HT="1.30.1";var $D="process.runtime.name";var qD="service.name";var KD="telemetry.sdk.name",YD="telemetry.sdk.language",XD="telemetry.sdk.version";var GT=$D;var VT=qD;var Va=KD,Wa=YD,ja=XD;var JD="nodejs";var WT=JD;var ii,no=(ii={},ii[Va]="opentelemetry",ii[GT]="node",ii[Wa]=WT,ii[ja]=HT,ii);function $a(r){r.unref()}var ok=9,ik=6,ak=Math.pow(10,ik),die=Math.pow(10,ok);function oo(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*ak);return[t,n]}function ai(r){return r[0]*1e6+r[1]/1e3}var qa;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(qa||(qa={}));_e();function jT(r,e){return new Promise(function(t){Zo.with(BT(Zo.active()),function(){r.export(e,function(n){t(n)})})})}var $T={_export:jT};var sk=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},oc=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=oo(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var up=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new oc(e)},r.prototype.merge=function(e,t){var n=ai(t.sampleTime)>=ai(e.sampleTime)?t:e;return new oc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ai(t.sampleTime)>=ai(e.sampleTime)?t:e;return new oc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.GAUGE,dataPoints:n.map(function(i){var a=sk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var lk=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},si=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 ic=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new si(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new si(t.startTime,this.monotonic,o,t.reset):new si(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 si(t.startTime,this.monotonic,o,!0):new si(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.SUM,dataPoints:n.map(function(i){var a=lk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var io=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)}}(),ar=function(){function r(){}return r.Drop=function(){return QT},r.Sum=function(){return ev},r.LastValue=function(){return tv},r.Histogram=function(){return rv},r.ExponentialHistogram=function(){return ck},r.Default=function(){return uk},r}();var qT=function(r){io(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 rp,e}(ar);var KT=function(r){io(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ge.COUNTER:case ge.OBSERVABLE_COUNTER:case ge.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ic(!0),e.NON_MONOTONIC_INSTANCE=new ic(!1),e}(ar);var YT=function(r){io(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 up,e}(ar);var XT=function(r){io(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 Jl([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(ar);var Ka=function(r){io(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 Jl(this._boundaries,this._recordMinMax)},e}(ar);var JT=function(r){io(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 cp(this._maxSize,this._recordMinMax)},e}(ar);var ZT=function(r){io(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ge.COUNTER:case ge.UP_DOWN_COUNTER:case ge.OBSERVABLE_COUNTER:case ge.OBSERVABLE_UP_DOWN_COUNTER:return ev;case ge.GAUGE:case ge.OBSERVABLE_GAUGE:return tv;case ge.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Ka(t.advice.explicitBucketBoundaries):rv}return H.warn("Unable to recognize instrument type: "+t.type),QT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(ar);var QT=new qT,ev=new KT,tv=new YT,rv=new XT,ck=new JT,uk=new ZT;var nv=function(r){return ar.Default()},ov=function(r){return oi.CUMULATIVE};var dp=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())})},mp=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}}},iv=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))},av=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:nv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:ov,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 dp(this,void 0,void 0,function(){var t,n,o,i,a,s;return mp(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(dk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],iv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=iv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(tp(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(tp(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return dp(this,void 0,void 0,function(){return mp(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,Tn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return dp(this,void 0,void 0,function(){return mp(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,Tn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var mk=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)}}(),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())})},sc=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}}},pk=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},gk=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))},pp=function(r){mk(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 ac(this,void 0,void 0,function(){var t;return sc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Tn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof ep?(H.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(nc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return ac(this,void 0,void 0,function(){var o,i,a,s,c,l;return sc(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,gk(["PeriodicExportingMetricReader: metrics collection errors"],pk(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),nc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,$T._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==qa.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),$a(this._interval)},e.prototype.onForceFlush=function(){return ac(this,void 0,void 0,function(){return sc(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 ac(this,void 0,void 0,function(){return sc(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}(av);_e();_e();function lc(){return"unknown_service:"+process.argv0}var An=function(){return An=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},An.apply(this,arguments)},hk=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())})},fk=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}}},Sk=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},cc=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[VT]=lc(),e[Wa]=no[Wa],e[Va]=no[Va],e[ja]=no[ja],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 hk(this,void 0,void 0,function(){return fk(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=An(An({},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=Sk(a,2),l=c[0],u=c[1];return An(An(An(An({},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 sv=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}();_e();var ao=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)}}(),uc=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=Zo.active()),typeof e!="number"){H.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Gt.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,oo(Date.now()))},r}();var lv=function(r){ao(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}(uc);var cv=function(r){ao(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}(uc);var uv=function(r){ao(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}(uc);var dv=function(r){ao(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}(uc);var dc=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 mv=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dc);var pv=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dc);var gv=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dc);function Ya(r){return r instanceof dc}var hv=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=kr(e,ge.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new uv(o,n)},r.prototype.createHistogram=function(e,t){var n=kr(e,ge.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new dv(o,n)},r.prototype.createCounter=function(e,t){var n=kr(e,ge.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new cv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=kr(e,ge.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new lv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=kr(e,ge.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new pv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=kr(e,ge.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new mv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=kr(e,ge.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new gv(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 mc=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=kr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();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)}}(),fv=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}}},bk=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 fv(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 fv(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 yr=function(r){yk(e,r);function e(){return r.call(this,Yl)||this}return e}(bk);var Ek=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},pc=function(){function r(e,t){this._aggregator=e,this._activeCollectionStorage=new yr,this._cumulativeMemoStorage=new yr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Yl(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=Ek(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 yr,e},r}();var gp=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.")},Sv=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},gc=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===oi.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=Tk(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=gp(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 yr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=gp(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=Sv(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=gp(e.keys()),s=a.next();!s.done;s=a.next()){var c=Sv(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 Tk(r){return Array.from(r.entries())}var vk=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)}}(),Ak=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},yv=function(r){vk(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 pc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new gc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new yr;Array.from(t.entries()).forEach(function(a){var s=Ak(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}(mc);_e();function hp(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
23
|
+
`),globalThis.console=e}}var gp=" ".repeat(6);import sL from"fetch-retry";import lL from"os";import Wb,{multistream as cL}from"pino";import uL from"pino-pretty";import dL from"pino-std-serializers";var Yo=new Map,pL=!0,$b="Log throttle exceeded",mL=100,gL=5e3,hL=sL(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}}),hp=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??lL.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=pL?Wb(a):Wb(a,cL([{stream:uL({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 hL(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Zn(e),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw new Error(`Got error status (${t.statusText}) from SigNoz`)}catch{}}shouldAllowLog(e){if(e===$b)return!0;let t=Date.now();return t-this.lastWindowStart>gL&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,$b),this.droppedLogsInWindow=!1,this.lastWindowStart=t),this.logsInCurrentWindow<mL?(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(va[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=dL.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:Dy({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,Yo.set("app",this),Yo.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=ky[e]):(this.minLevelValue=va[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Xo=({app:r,hostname:e,disableConsoleLogs:t})=>(Yo.has(r)||Yo.set(r,new hp({bindings:{app:r},hostname:e,disableConsoleLogs:t})),Yo.get(r));async function qb(){await Promise.all([...Yo.values()].map(r=>r.flush()))}import{hostname as fL}from"os";var nr=Xo({app:"cli",hostname:fL(),disableConsoleLogs:!0}).child({cliVersion:"0.8.0"});function fp(r){if(!r)return;r=r.toLowerCase();let e=Sl.safeParse(r);if(e.success)return C.setMinLevel(e.data),e.data}function Kb({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 jb(()=>{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 Ra=({status:r,testLogRef:e,getRunningTestsCount:t,getTotalTestsCount:n,additionalText:o})=>{r=r.toUpperCase();let i=r,a;r.includes("FAIL")?(i=Jo.bgRed.white("FAIL"),a=3):r.includes("PASS")?(i=Jo.bgGreen.white("PASS"),a=3):r.includes("START")?(i=Jo.bgBlue.white("START"),a=2):r.includes("CANCEL")?(i=Jo.bgRgb(191,68,11).white("CANCEL"),a=1):r.includes("RETRY")?(i=Jo.bgRgb(191,68,11).white("RETRY"),a=2):r.includes("RUN")||r.includes("PROG")?(i=Jo.bgMagenta.white("RUNNING"),a=0):(C.warn(`Unknown status tried to be logged in run test locally: ${r}`),a=0),SL||(i=`${i}`),C.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${t()}/${n()})`)};import yL from"fs";import{tmpdir as bL}from"os";import EL from"path";import{registry as Ca}from"playwright-core/lib/server";import Yb from"proper-lockfile";var Xb=EL.join(bL(),"momenticBrowserInstallation");var Sp=["chrome","chromium","chrome-for-testing","ffmpeg"],TL={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Jb={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell",ffmpeg:"ffmpeg"};function Zb(r){let e=Jb[TL[r]??""]??"",t=Ca.findExecutable(e);return!t||t.installType==="none"?!1:yp(t)}function yp(r){let e=r.executablePath();return yL.existsSync(e)}function vL(r,e){let t=Jb[r];if(!t)throw new Error(`Requested install of unknown browser type ${r}`);let n=Ca.findExecutable(t);if(!n||n.installType==="none")throw new Error(`Requested install of unknown browser type ${r}`);if(!(!e&&yp(n)))return n}async function AL({browser:r,force:e}){let t=vL(r,e);if(!t){C.info(`Browser '${r}' is already installed, skipping...`);return}C.info(`Installing browser '${r}'...`);try{await Ca.installDeps([t],!1),await Ca.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=Ca.findExecutable(r),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!yp(o);)C.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw n}}async function Cl({rawBrowsers:r,force:e=!1,all:t=!1}){let n=t?Sp:Array.from(new Set(r));try{await Yb.lock(Xb,{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 AL({browser:i,force:e})}catch(a){o=a,C.error(`Failed to install the ${i} browser: ${a}`)}}finally{await Yb.unlock(Xb,{realpath:!1})}if(o)throw o}import{createServer as wL}from"http";async function xl(r,e,t=30){for(let n=0;n<t;n+=1){let o=r+n;if(await Ml(o))return o}C.error(`Could not find an available port for ${e} starting from ${r} after ${t} attempts`),process.exit(1)}async function Ml(r){return new Promise((e,t)=>{let n=wL();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 t7 from"blocked-at";import n7 from"why-is-node-running";import t0 from"fs";import{tmpdir as r0}from"os";import n0 from"path";import{remote as o0}from"webdriverio";import{createInstanceClient as Kk}from"@limrun/api";import{execSync as Yk}from"child_process";import g7,{multistream as f7}from"pino";import y7 from"pino-pretty";var T7=5*1024,RL="...[truncated]",v7=Buffer.byteLength(RL,"utf8");import{PostHog as O7}from"posthog-node";var Sn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Qb=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:p}=e;if(p.aborted)return c(Qb(p));l=()=>c(Qb(p)),p.addEventListener("abort",l,{once:!0})}let u=()=>{if(e.signal&&e.signal.removeEventListener("abort",l),n)try{s(n())}catch(p){c(p)}else{typeof r.cancel=="function"&&Promise.resolve().then(()=>r.cancel()).catch(()=>{});let p=o instanceof Error?o:new Sn(o??`Promise timed out after ${t}ms`);c(p)}};t<1/0&&(a=i.setTimeout(u,t));let d=()=>{i.clearTimeout(a),e.signal&&e.signal.removeEventListener("abort",l)};Promise.resolve(r).then(p=>{d(),s(p)}).catch(p=>{d(),c(p)})})}import{PostHog as H7}from"posthog-node";import{execSync as CL}from"child_process";import Zo from"os";import xL from"v8";var eE,Or,rE=Zo.platform(),ML=Zo.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),{}),tE=r=>{try{let e={},t=!1,n=_L(),o=PL(),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=xL.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"),Qn&&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 nE(r){if(!Pr)return tE(r),{interval:setInterval(()=>tE(r),2e4),cpuMetadata:ML,platform:rE}}function _L(){let r=Zo.totalmem(),e=rE==="darwin"?IL():(()=>{let n=Zo.freemem();return{availableMemory:n,rawFreeMemory:n,cachedMemory:0}})(),t=e.availableMemory/r;return{totalMemory:r,freeMemory:e.availableMemory,freePercentage:t}}function PL(){let r=Zo.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,!Or)return Or=t,null;let n={user:t.user-Or.user,nice:t.nice-Or.nice,sys:t.sys-Or.sys,idle:t.idle-Or.idle,irq:t.irq-Or.irq,total:t.total-Or.total};return eE={measurementTime:e,intervalMs:e-Or.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},Or=t,eE}function IL(){try{let r=CL("/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 p=r.match(new RegExp(`${u}:\\s+(\\d+)\\.`,"i"))?.[1];return p?Number.parseInt(p,10):0},i=o("Pages free"),a=o("Pages inactive"),s=o("Pages speculative"),c=i*n,l=(a+s)*n;return{availableMemory:c+l,rawFreeMemory:c,cachedMemory:l}}catch{let e=Zo.freemem();return{availableMemory:e,rawFreeMemory:e,cachedMemory:0}}}var _l=class{increment(e,t,n){}gauge(e,t){}distribution(e,t,n){}async flush(){}async recordDuration({fn:e}){return await e()}};function OL(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 Pl(r,e){let t=OL(r);return!e||Object.keys(e).length===0?t:{...e,...t}}var PE="=",Nl=";",Pp=",";var IE=8192;var ri={};Yx(ri,{getKeyPairs:()=>dN,parseKeyPairsIntoRecord:()=>pN,parsePairKeyValue:()=>OE,serializeKeyPairs:()=>uN});_e();var cN=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 uN(r){return r.reduce(function(e,t){var n=""+e+(e!==""?Pp:"")+t;return n.length>IE?e:n},"")}function dN(r){return r.getAllEntries().map(function(e){var t=cN(e,2),n=t[0],o=t[1],i=encodeURIComponent(n)+"="+encodeURIComponent(o.value);return o.metadata!==void 0&&(i+=Nl+o.metadata.toString()),i})}function OE(r){var e=r.split(Nl);if(!(e.length<=0)){var t=e.shift();if(t){var n=t.indexOf(PE);if(!(n<=0)){var o=decodeURIComponent(t.substring(0,n).trim()),i=decodeURIComponent(t.substring(n+1).trim()),a;return e.length>0&&(a=Ep(e.join(Nl))),{key:o,value:i,metadata:a}}}}}function pN(r){return typeof r!="string"||r.length===0?{}:r.split(Pp).map(function(e){return OE(e)}).filter(function(e){return e!==void 0&&e.value.length>0}).reduce(function(e,t){return e[t.key]=t.value,e},{})}_e();var Dl;(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"})(Dl||(Dl={}));var mN=",",gN=["OTEL_SDK_DISABLED"];function hN(r){return gN.indexOf(r)>-1}var fN=["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 SN(r){return fN.indexOf(r)>-1}var yN=["OTEL_NO_PATCH_MODULES","OTEL_PROPAGATORS"];function bN(r){return yN.indexOf(r)>-1}var Ip=1/0,Op=128,EN=128,TN=128,Lp={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:ke.INFO,OTEL_NO_PATCH_MODULES:[],OTEL_PROPAGATORS:["tracecontext","baggage"],OTEL_RESOURCE_ATTRIBUTES:"",OTEL_SERVICE_NAME:"",OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:Ip,OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT:Op,OTEL_SPAN_EVENT_COUNT_LIMIT:128,OTEL_SPAN_LINK_COUNT_LIMIT:128,OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:EN,OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:TN,OTEL_TRACES_EXPORTER:"",OTEL_TRACES_SAMPLER:Dl.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 vN(r,e,t){if(!(typeof t[r]>"u")){var n=String(t[r]);e[r]=n.toLowerCase()==="true"}}function AN(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 wN(r,e,t,n){n===void 0&&(n=mN);var o=t[r];typeof o=="string"&&(e[r]=o.split(n).map(function(i){return i.trim()}))}var RN={ALL:ke.ALL,VERBOSE:ke.VERBOSE,DEBUG:ke.DEBUG,INFO:ke.INFO,WARN:ke.WARN,ERROR:ke.ERROR,NONE:ke.NONE};function CN(r,e,t){var n=t[r];if(typeof n=="string"){var o=RN[n.toUpperCase()];o!=null&&(e[r]=o)}}function LE(r){var e={};for(var t in Lp){var n=t;switch(n){case"OTEL_LOG_LEVEL":CN(n,e,r);break;default:if(hN(n))vN(n,e,r);else if(SN(n))AN(n,e,r);else if(bN(n))wN(n,e,r);else{var o=r[n];typeof o<"u"&&o!==null&&(e[n]=String(o))}}}return e}function St(){var r=LE(process.env);return Object.assign({},Lp,r)}function NE(r){return r>=48&&r<=57?r-48:r>=97&&r<=102?r-87:r-55}function kl(r){for(var e=new Uint8Array(r.length/2),t=0,n=0;n<r.length;n+=2){var o=NE(r.charCodeAt(n)),i=NE(r.charCodeAt(n+1));e[t++]=o<<4|i}return e}var DE="1.25.1";var xN="deployment.environment";var MN="process.runtime.name";var _N="service.name";var PN="service.instance.id";var IN="telemetry.sdk.name",ON="telemetry.sdk.language",LN="telemetry.sdk.version";var kE=xN;var UE=MN;var Ul=_N;var FE=PN;var La=IN,Na=ON,Da=LN;var NN="nodejs";var BE=NN;var ni,Fl=(ni={},ni[La]="opentelemetry",ni[UE]="node",ni[Na]=BE,ni[Da]=DE,ni);var DN=9,kN=6,UN=Math.pow(10,kN),FN=Math.pow(10,DN);function zE(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*UN);return[t,n]}function HE(r){return r[0]*FN+r[1]}function ka(r){return r[0]*1e6+r[1]/1e3}var to;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(to||(to={}));var GE=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 BN=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},zN=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))},VE=function(){function r(e,t){this._callback=e,this._that=t,this._isCalled=!1,this._deferred=new GE}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,zN([this._that],BN(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 or;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(or||(or={}));var Ct;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Ct||(Ct={}));var HN=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 dre=function(r){HN(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function jE(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}_e();var ir;(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"})(ir||(ir={}));var WE=function(){function r(){this.kind=ir.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 ae;(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"})(ae||(ae={}));var GN=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 VN(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 Np=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=VN(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=jE(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 Dp=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ir.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Np(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 Np(e.startTime,n.buckets.boundaries,this._recordMinMax,{buckets:{boundaries:n.buckets.boundaries,counts:s},count:n.count+o.count,sum:n.sum+o.sum,hasMinMax:this._recordMinMax&&(n.hasMinMax||o.hasMinMax),min:l,max:u})},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 Np(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:Ct.HISTOGRAM,dataPoints:n.map(function(i){var a=GN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ae.GAUGE||e.type===ae.UP_DOWN_COUNTER||e.type===ae.OBSERVABLE_GAUGE||e.type===ae.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}();_e();var kp=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},Up=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))},Fp=function(){function r(e,t,n,o){e===void 0&&(e=new jN),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 jN=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,Up([n,this._counts.length-t],kp(this._counts.slice(t)),!1)),o.splice.apply(o,Up([0,t],kp(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(Up([],kp(this._counts),!1))},r}();var $E=52,WN=2146435072,$N=1048575,Bp=1023,Bl=-Bp+1,zl=Bp,Ua=Math.pow(2,-1022);function Hl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&WN)>>20;return n-Bp}function Gl(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&$N)*Math.pow(2,32);return o+n}function Fa(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function KE(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var qN=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)}}(),yn=function(r){qN(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var XE=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ua)return this._minNormalLowerBoundaryIndex();var t=Hl(e),n=this._rightShift(Gl(e)-1,$E);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new yn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new yn("overflow: "+e+" is > maximum lower boundary: "+n);return Fa(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=Bl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return zl>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var JE=function(){function r(e){this._scale=e,this._scaleFactor=Fa(Math.LOG2E,e),this._inverseFactor=Fa(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ua)return this._minNormalLowerBoundaryIndex()-1;if(Gl(e)===0){var t=Hl(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 yn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ua;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new yn("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 Bl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(zl+1<<this._scale)-1},r}();var ZE=-10,QE=20,KN=Array.from({length:31},function(r,e){return e>10?new JE(e-10):new XE(e-10)});function zp(r){if(r>QE||r<ZE)throw new yn("expected scale >= "+ZE+" && <= "+QE+", got: "+r);return KN[r+10]}var YN=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},Vl=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}(),XN=20,JN=160,Hp=2,ZN=function(){function r(e,t,n,o,i,a,s,c,l,u,d){e===void 0&&(e=e),t===void 0&&(t=JN),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 Fp),u===void 0&&(u=new Fp),d===void 0&&(d=zp(XN)),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<Hp&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+Hp),this._maxSize=Hp)}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=KE(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=zp(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=Vl.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=Vl.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 Vl(0,-1);var o=t-n;return new Vl(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 eT=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ir.EXPONENTIAL_HISTOGRAM}return r.prototype.createAccumulation=function(e){return new ZN(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:Ct.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=YN(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===ae.GAUGE||e.type===ae.UP_DOWN_COUNTER||e.type===ae.OBSERVABLE_GAUGE||e.type===ae.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 QN=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},Gp=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=zE(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var tT=function(){function r(){this.kind=ir.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new Gp(e)},r.prototype.merge=function(e,t){var n=ka(t.sampleTime)>=ka(e.sampleTime)?t:e;return new Gp(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ka(t.sampleTime)>=ka(e.sampleTime)?t:e;return new Gp(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Ct.GAUGE,dataPoints:n.map(function(i){var a=QN(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();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},Ba=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 Vp=function(){function r(e){this.monotonic=e,this.kind=ir.SUM}return r.prototype.createAccumulation=function(e){return new Ba(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new Ba(t.startTime,this.monotonic,o,t.reset):new Ba(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 Ba(t.startTime,this.monotonic,o,!0):new Ba(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Ct.SUM,dataPoints:n.map(function(i){var a=eD(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var ro=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)}}(),Nr=function(){function r(){}return r.Drop=function(){return cT},r.Sum=function(){return uT},r.LastValue=function(){return dT},r.Histogram=function(){return pT},r.ExponentialHistogram=function(){return tD},r.Default=function(){return rD},r}();var rT=function(r){ro(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 WE,e}(Nr);var nT=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case ae.COUNTER:case ae.OBSERVABLE_COUNTER:case ae.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new Vp(!0),e.NON_MONOTONIC_INSTANCE=new Vp(!1),e}(Nr);var oT=function(r){ro(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 tT,e}(Nr);var iT=function(r){ro(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 Dp([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(Nr);var aT=function(r){ro(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 Dp(this._boundaries,this._recordMinMax)},e}(Nr);var sT=function(r){ro(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 eT(this._maxSize,this._recordMinMax)},e}(Nr);var lT=function(r){ro(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case ae.COUNTER:case ae.UP_DOWN_COUNTER:case ae.OBSERVABLE_COUNTER:case ae.OBSERVABLE_UP_DOWN_COUNTER:return uT;case ae.GAUGE:case ae.OBSERVABLE_GAUGE:return dT;case ae.HISTOGRAM:return t.advice.explicitBucketBoundaries?new aT(t.advice.explicitBucketBoundaries):pT}return z.warn("Unable to recognize instrument type: "+t.type),cT},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(Nr);var cT=new rT,uT=new nT,dT=new oT,pT=new iT,tD=new sT,rD=new lT;_e();function jl(){return"unknown_service:"+process.argv0}var bn=function(){return bn=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},bn.apply(this,arguments)},nD=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())})},oD=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}}},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},jp=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 z.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[Ul]=jl(),e[Na]=Fl[Na],e[La]=Fl[La],e[Da]=Fl[Da],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 nD(this,void 0,void 0,function(){return oD(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=bn(bn({},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=iD(a,2),l=c[0],u=c[1];return bn(bn(bn(bn({},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 no;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE",r[r.LOWMEMORY=2]="LOWMEMORY"})(no||(no={}));_e();var aD=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())})},sD=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}}},Wp=function(){return or.CUMULATIVE},mT=function(r){switch(r){case ae.COUNTER:case ae.OBSERVABLE_COUNTER:case ae.GAUGE:case ae.HISTOGRAM:case ae.OBSERVABLE_GAUGE:return or.DELTA;case ae.UP_DOWN_COUNTER:case ae.OBSERVABLE_UP_DOWN_COUNTER:return or.CUMULATIVE}},gT=function(r){switch(r){case ae.COUNTER:case ae.HISTOGRAM:return or.DELTA;case ae.GAUGE:case ae.UP_DOWN_COUNTER:case ae.OBSERVABLE_UP_DOWN_COUNTER:case ae.OBSERVABLE_COUNTER:case ae.OBSERVABLE_GAUGE:return or.CUMULATIVE}};function lD(){var r=St(),e=r.OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.trim().toLowerCase();return e==="cumulative"?Wp:e==="delta"?mT:e==="lowmemory"?gT:(z.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."),Wp)}function cD(r){return r!=null?r===no.DELTA?mT:r===no.LOWMEMORY?gT:Wp:lD()}function uD(r){return r?.aggregationPreference?r.aggregationPreference:function(e){return Nr.Default()}}var hT=function(){function r(e,t){this._otlpExporter=e,this._aggregationSelector=uD(t),this._aggregationTemporalitySelector=cD(t?.temporalityPreference)}return r.prototype.export=function(e,t){this._otlpExporter.export([e],t)},r.prototype.shutdown=function(){return aD(this,void 0,void 0,function(){return sD(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}();_e();_e();var dD=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},fT=1e4,ST=5,yT=1e3,bT=5e3,ET=1.5;function za(r){r===void 0&&(r={});var e={};return Object.entries(r).forEach(function(t){var n=dD(t,2),o=n[0],i=n[1];typeof i<"u"?e[o]=String(i):z.warn('Header "'+o+'" has invalid value ('+i+") and will be ignored")}),e}function $p(r,e){return r.endsWith("/")||(r=r+"/"),r+e}function qp(r){try{var e=new URL(r);return e.pathname===""&&(e.pathname=e.pathname+"/"),e.toString()}catch{return z.warn("Could not parse export URL: '"+r+"'"),r}}function Kp(r){return typeof r=="number"?r<=0?Yp(r,fT):r:pD()}function pD(){var r,e=Number((r=St().OTEL_EXPORTER_OTLP_TRACES_TIMEOUT)!==null&&r!==void 0?r:St().OTEL_EXPORTER_OTLP_TIMEOUT);return e<=0?Yp(e,fT):e}function Yp(r,e){return z.warn("Timeout must be greater than 0",r),e}function TT(r){var e=[429,502,503,504];return e.includes(r)}function vT(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 AT=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 VE(this._shutdown,this),this._concurrencyLimit=typeof e.concurrencyLimit=="number"?e.concurrencyLimit:30,this.timeoutMillis=Kp(e.timeoutMillis),this.onInit(e)}return r.prototype.export=function(e,t){if(this._shutdownOnce.isCalled){t({code:to.FAILED,error:new Error("Exporter has been shutdown")});return}if(this._sendingPromises.length>=this._concurrencyLimit){t({code:to.FAILED,error:new Error("Concurrent export limit reached")});return}this._export(e).then(function(){t({code:to.SUCCESS})}).catch(function(n){t({code:to.FAILED,error:n})})},r.prototype._export=function(e){var t=this;return new Promise(function(n,o){try{z.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 z.debug("shutdown started"),this.onShutdown(),this.forceFlush()},r}();_e();import*as Xp from"url";import*as $l from"http";import*as ql from"https";import*as wT from"zlib";import{Readable as gD}from"stream";var En;(function(r){r.NONE="none",r.GZIP="gzip"})(En||(En={}));var mD=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)}}(),oi=function(r){mD(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 Wl=function(){return Wl=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},Wl.apply(this,arguments)};function Jp(r,e,t,n,o){var i=r.timeoutMillis,a=new Xp.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 oi("Request Timeout");o(h)}else s>=14?l.destroy():l.abort()},i),p={hostname:a.hostname,port:a.port,path:a.pathname,method:"POST",headers:Wl({"Content-Type":t},r.headers),agent:r.agent},g=a.protocol==="http:"?$l.request:ql.request,m=function(h,f){switch(h===void 0&&(h=ST),f===void 0&&(f=yT),l=g(p,function(b){var R="";b.on("data",function(A){return R+=A}),b.on("aborted",function(){if(u){var A=new oi("Request Timeout");o(A)}}),b.on("end",function(){if(u===!1)if(b.statusCode&&b.statusCode<299)z.debug("statusCode: "+b.statusCode,R),n(),clearTimeout(d),clearTimeout(c);else if(b.statusCode&&TT(b.statusCode)&&h>0){var A=void 0;f=ET*f,b.headers["retry-after"]?A=vT(b.headers["retry-after"]):A=Math.round(Math.random()*(bT-f)+f),c=setTimeout(function(){m(h-1,f)},A)}else{var T=new oi(b.statusMessage,b.statusCode,R);o(T),clearTimeout(d),clearTimeout(c)}})}),l.on("error",function(b){if(u){var R=new oi("Request Timeout",b.code);o(R)}else o(b);clearTimeout(d),clearTimeout(c)}),l.on("abort",function(){if(u){var b=new oi("Request Timeout");o(b)}clearTimeout(d),clearTimeout(c)}),r.compression){case En.GZIP:{l.setHeader("Content-Encoding","gzip");var E=hD(e);E.on("error",o).pipe(wT.createGzip()).on("error",o).pipe(l);break}default:l.end(Buffer.from(e));break}};m()}function hD(r){var e=new gD;return e.push(r),e.push(null),e}function Zp(r){if(r.httpAgentOptions&&r.keepAlive===!1){z.warn("httpAgentOptions is used only when keepAlive is true");return}if(!(r.keepAlive===!1||!r.url))try{var e=new Xp.URL(r.url),t=e.protocol==="http:"?$l.Agent:ql.Agent;return new t(Wl({keepAlive:!0},r.httpAgentOptions))}catch(n){z.error("collector exporter failed to create http agent. err: "+n.message);return}}function Qp(r){if(r)return r;var e=St().OTEL_EXPORTER_OTLP_TRACES_COMPRESSION||St().OTEL_EXPORTER_OTLP_COMPRESSION;return e===En.GZIP?En.GZIP:En.NONE}_e();var fD=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)}}(),Kl=function(r){fD(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&&z.warn("Metadata cannot be set when using http"),i.headers=Object.assign(i.DEFAULT_HEADERS,za(t.headers),ri.parseKeyPairsIntoRecord(St().OTEL_EXPORTER_OTLP_HEADERS)),i.agent=Zp(t),i.compression=Qp(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){z.debug("Shutdown already started. Cannot send objects");return}var a=new Promise(function(c,l){var u;Jp(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}(AT);function CT(r){var e=BigInt(1e9);return BigInt(r[0])*e+BigInt(r[1])}function SD(r){var e=Number(BigInt.asUintN(32,r)),t=Number(BigInt.asUintN(32,r>>BigInt(32)));return{low:e,high:t}}function xT(r){var e=CT(r);return SD(e)}function yD(r){var e=CT(r);return e.toString()}var bD=typeof BigInt<"u"?yD:HE;function RT(r){return r}function MT(r){if(r!==void 0)return kl(r)}var ED={encodeHrTime:xT,encodeSpanContext:kl,encodeOptionalSpanContext:MT};function _T(r){var e,t;if(r===void 0)return ED;var n=(e=r.useLongBits)!==null&&e!==void 0?e:!0,o=(t=r.useHex)!==null&&t!==void 0?t:!1;return{encodeHrTime:n?xT:bD,encodeSpanContext:o?RT:kl,encodeOptionalSpanContext:o?RT:MT}}var TD=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 PT(r){return{name:r.name,version:r.version}}function ii(r){return Object.keys(r).map(function(e){return IT(e,r[e])})}function IT(r,e){return{key:r,value:OT(e)}}function OT(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(OT)}}:e==="object"&&r!=null?{kvlistValue:{values:Object.entries(r).map(function(t){var n=TD(t,2),o=n[0],i=n[1];return IT(o,i)})}}:{}}function LT(r){return{attributes:ii(r.attributes),droppedAttributesCount:0}}_e();function DT(r,e){var t=_T(e);return{resource:LT(r.resource),schemaUrl:void 0,scopeMetrics:vD(r.scopeMetrics,t)}}function vD(r,e){return Array.from(r.map(function(t){return{scope:PT(t.scope),metrics:t.metrics.map(function(n){return AD(n,e)}),schemaUrl:t.scope.schemaUrl}}))}function AD(r,e){var t={name:r.descriptor.name,description:r.descriptor.description,unit:r.descriptor.unit},n=xD(r.aggregationTemporality);switch(r.dataPointType){case Ct.SUM:t.sum={aggregationTemporality:n,isMonotonic:r.isMonotonic,dataPoints:NT(r,e)};break;case Ct.GAUGE:t.gauge={dataPoints:NT(r,e)};break;case Ct.HISTOGRAM:t.histogram={aggregationTemporality:n,dataPoints:RD(r,e)};break;case Ct.EXPONENTIAL_HISTOGRAM:t.exponentialHistogram={aggregationTemporality:n,dataPoints:CD(r,e)};break}return t}function wD(r,e,t){var n={attributes:ii(r.attributes),startTimeUnixNano:t.encodeHrTime(r.startTime),timeUnixNano:t.encodeHrTime(r.endTime)};switch(e){case Vt.INT:n.asInt=r.value;break;case Vt.DOUBLE:n.asDouble=r.value;break}return n}function NT(r,e){return r.dataPoints.map(function(t){return wD(t,r.descriptor.valueType,e)})}function RD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ii(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 CD(r,e){return r.dataPoints.map(function(t){var n=t.value;return{attributes:ii(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 xD(r){switch(r){case or.DELTA:return 1;case or.CUMULATIVE:return 2}}function kT(r,e){return{resourceMetrics:r.map(function(t){return DT(t,e)})}}var em={serializeRequest:function(r){var e=kT(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 UT="0.52.1";var FT=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)}}(),ai=function(){return ai=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},ai.apply(this,arguments)},BT="v1/metrics",MD="http://localhost:4318/"+BT,_D={"User-Agent":"OTel-OTLP-Exporter-JavaScript/"+UT},PD=function(r){FT(e,r);function e(t){var n=r.call(this,t,em,"application/json")||this;return n.headers=ai(ai(ai(ai({},n.headers),_D),ri.parseKeyPairsIntoRecord(St().OTEL_EXPORTER_OTLP_METRICS_HEADERS)),za(t?.headers)),n}return e.prototype.getDefaultUrl=function(t){return typeof t.url=="string"?t.url:St().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT.length>0?qp(St().OTEL_EXPORTER_OTLP_METRICS_ENDPOINT):St().OTEL_EXPORTER_OTLP_ENDPOINT.length>0?$p(St().OTEL_EXPORTER_OTLP_ENDPOINT,BT):MD},e}(Kl),zT=function(r){FT(e,r);function e(t){return r.call(this,new PD(t),t)||this}return e}(hT);var si;(function(r){r[r.DELTA=0]="DELTA",r[r.CUMULATIVE=1]="CUMULATIVE"})(si||(si={}));var Dr;(function(r){r[r.HISTOGRAM=0]="HISTOGRAM",r[r.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",r[r.GAUGE=2]="GAUGE",r[r.SUM=3]="SUM"})(Dr||(Dr={}));_e();var ID=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)}}(),HT=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())})},GT=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}}},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},LD=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))},ND=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 VT(r){return r!=null}function Yl(r){var e=Object.keys(r);return e.length===0?"":(e=e.sort(),JSON.stringify(e.map(function(t){return[t,r[t]]})))}function jT(r){var e,t;return r.name+":"+((e=r.version)!==null&&e!==void 0?e:"")+":"+((t=r.schemaUrl)!==null&&t!==void 0?t:"")}var tm=function(r){ID(e,r);function e(t){var n=r.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return e}(Error);function Tn(r,e){var t,n=new Promise(function(i,a){t=setTimeout(function(){a(new tm("Operation timed out."))},e)});return Promise.race([r,n]).then(function(o){return clearTimeout(t),o},function(o){throw clearTimeout(t),o})}function WT(r){return HT(this,void 0,void 0,function(){var e=this;return GT(this,function(t){return[2,Promise.all(r.map(function(n){return HT(e,void 0,void 0,function(){var o,i;return GT(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 $T(r){return r.status==="rejected"}function rm(r,e){var t=[];return r.forEach(function(n){t.push.apply(t,LD([],OD(e(n)),!1))}),t}function qT(r,e){var t,n;if(r.size!==e.size)return!1;try{for(var o=ND(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 KT(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 YT(r,e){return r.toLowerCase()===e.toLowerCase()}_e();var ar;(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"})(ar||(ar={}));var nm=function(){function r(){this.kind=ar.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}();_e();var me;(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"})(me||(me={}));function kr(r,e,t){var n,o,i,a;return kD(r)||z.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:Vt.DOUBLE,advice:(a=t?.advice)!==null&&a!==void 0?a:{}}}function XT(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 JT(r,e){return YT(r.name,e.name)&&r.unit===e.unit&&r.type===e.type&&r.valueType===e.valueType}var DD=/^[a-z][a-z0-9_.\-/]{0,254}$/i;function kD(r){return r.match(DD)!=null}var 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};function FD(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 Xl=function(){function r(e,t,n,o){n===void 0&&(n=!0),o===void 0&&(o=FD(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=KT(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 Jl=function(){function r(e,t){this._boundaries=e,this._recordMinMax=t,this.kind=ar.HISTOGRAM}return r.prototype.createAccumulation=function(e){return new Xl(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 Xl(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 Xl(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:Dr.HISTOGRAM,dataPoints:n.map(function(i){var a=UD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.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}();_e();var om=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},im=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))},am=function(){function r(e,t,n,o){e===void 0&&(e=new BD),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 BD=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,im([n,this._counts.length-t],om(this._counts.slice(t)),!1)),o.splice.apply(o,im([0,t],om(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(im([],om(this._counts),!1))},r}();var ZT=52,zD=2146435072,HD=1048575,sm=1023,Zl=-sm+1,Ql=sm,Ha=Math.pow(2,-1022);function ec(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=(t&zD)>>20;return n-sm}function tc(r){var e=new DataView(new ArrayBuffer(8));e.setFloat64(0,r);var t=e.getUint32(0),n=e.getUint32(4),o=(t&HD)*Math.pow(2,32);return o+n}function Ga(r,e){return r===0||r===Number.POSITIVE_INFINITY||r===Number.NEGATIVE_INFINITY||Number.isNaN(r)?r:r*Math.pow(2,e)}function ev(r){return r--,r|=r>>1,r|=r>>2,r|=r>>4,r|=r>>8,r|=r>>16,r++,r}var GD=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)}}(),vn=function(r){GD(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(Error);var rv=function(){function r(e){this._shift=-e}return r.prototype.mapToIndex=function(e){if(e<Ha)return this._minNormalLowerBoundaryIndex();var t=ec(e),n=this._rightShift(tc(e)-1,ZT);return t+n>>this._shift},r.prototype.lowerBoundary=function(e){var t=this._minNormalLowerBoundaryIndex();if(e<t)throw new vn("underflow: "+e+" is < minimum lower boundary: "+t);var n=this._maxNormalLowerBoundaryIndex();if(e>n)throw new vn("overflow: "+e+" is > maximum lower boundary: "+n);return Ga(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=Zl>>this._shift;return this._shift<2&&e--,e},r.prototype._maxNormalLowerBoundaryIndex=function(){return Ql>>this._shift},r.prototype._rightShift=function(e,t){return Math.floor(e*Math.pow(2,-t))},r}();var nv=function(){function r(e){this._scale=e,this._scaleFactor=Ga(Math.LOG2E,e),this._inverseFactor=Ga(Math.LN2,-e)}return r.prototype.mapToIndex=function(e){if(e<=Ha)return this._minNormalLowerBoundaryIndex()-1;if(tc(e)===0){var t=ec(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 vn("overflow: "+e+" is > maximum lower boundary: "+t)}var n=this._minNormalLowerBoundaryIndex();if(e<=n){if(e===n)return Ha;if(e===n-1)return Math.exp((e+(1<<this._scale))/this._scaleFactor)/2;throw new vn("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 Zl<<this._scale},r.prototype._maxNormalLowerBoundaryIndex=function(){return(Ql+1<<this._scale)-1},r}();var ov=-10,iv=20,VD=Array.from({length:31},function(r,e){return e>10?new nv(e-10):new rv(e-10)});function lm(r){if(r>iv||r<ov)throw new vn("expected scale >= "+ov+" && <= "+iv+", got: "+r);return VD[r+10]}var jD=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},rc=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}(),WD=20,$D=160,cm=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=$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 am),u===void 0&&(u=new am),d===void 0&&(d=lm(WD)),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<cm&&(z.warn("Exponential Histogram Max Size set to "+this._maxSize+", changing to the minimum size of: "+cm),this._maxSize=cm)}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=ev(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=lm(t)}},r.prototype._minScale=function(e){var t=Math.min(this.scale,e.scale),n=rc.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),o=rc.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 rc(0,-1);var o=t-n;return new rc(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 um=function(){function r(e,t){this._maxSize=e,this._recordMinMax=t,this.kind=ar.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:Dr.EXPONENTIAL_HISTOGRAM,dataPoints:n.map(function(i){var a=jD(i,2),s=a[0],c=a[1],l=c.toPointValue(),u=e.type===me.GAUGE||e.type===me.UP_DOWN_COUNTER||e.type===me.OBSERVABLE_GAUGE||e.type===me.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}();_e();var qD=Tp("OpenTelemetry SDK Context Key SUPPRESS_TRACING");function sv(r){return r.setValue(qD,!0)}_e();function lv(){return function(r){z.error(KD(r))}}function KD(r){return typeof r=="string"?r:JSON.stringify(YD(r))}function YD(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 XD=lv();function nc(r){try{XD(r)}catch{}}var cv="1.30.1";var JD="process.runtime.name";var ZD="service.name";var QD="telemetry.sdk.name",ek="telemetry.sdk.language",tk="telemetry.sdk.version";var uv=JD;var dv=ZD;var Va=QD,ja=ek,Wa=tk;var rk="nodejs";var pv=rk;var li,oo=(li={},li[Va]="opentelemetry",li[uv]="node",li[ja]=pv,li[Wa]=cv,li);function $a(r){r.unref()}var ck=9,uk=6,dk=Math.pow(10,uk),hie=Math.pow(10,ck);function io(r){var e=r/1e3,t=Math.trunc(e),n=Math.round(r%1e3*dk);return[t,n]}function ci(r){return r[0]*1e6+r[1]/1e3}var qa;(function(r){r[r.SUCCESS=0]="SUCCESS",r[r.FAILED=1]="FAILED"})(qa||(qa={}));_e();function mv(r,e){return new Promise(function(t){ti.with(sv(ti.active()),function(){r.export(e,function(n){t(n)})})})}var gv={_export:mv};var pk=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},oc=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=io(Date.now())},r.prototype.setStartTime=function(e){this.startTime=e},r.prototype.toPointValue=function(){return this._current},r}();var dm=function(){function r(){this.kind=ar.LAST_VALUE}return r.prototype.createAccumulation=function(e){return new oc(e)},r.prototype.merge=function(e,t){var n=ci(t.sampleTime)>=ci(e.sampleTime)?t:e;return new oc(e.startTime,n.toPointValue(),n.sampleTime)},r.prototype.diff=function(e,t){var n=ci(t.sampleTime)>=ci(e.sampleTime)?t:e;return new oc(t.startTime,n.toPointValue(),n.sampleTime)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.GAUGE,dataPoints:n.map(function(i){var a=pk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}})}},r}();var mk=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},ui=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 ic=function(){function r(e){this.monotonic=e,this.kind=ar.SUM}return r.prototype.createAccumulation=function(e){return new ui(e,this.monotonic)},r.prototype.merge=function(e,t){var n=e.toPointValue(),o=t.toPointValue();return t.reset?new ui(t.startTime,this.monotonic,o,t.reset):new ui(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 ui(t.startTime,this.monotonic,o,!0):new ui(t.startTime,this.monotonic,o-n)},r.prototype.toMetricData=function(e,t,n,o){return{descriptor:e,aggregationTemporality:t,dataPointType:Dr.SUM,dataPoints:n.map(function(i){var a=mk(i,2),s=a[0],c=a[1];return{attributes:s,startTime:c.startTime,endTime:o,value:c.toPointValue()}}),isMonotonic:this.monotonic}},r}();var ao=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)}}(),sr=function(){function r(){}return r.Drop=function(){return Tv},r.Sum=function(){return vv},r.LastValue=function(){return Av},r.Histogram=function(){return wv},r.ExponentialHistogram=function(){return gk},r.Default=function(){return hk},r}();var hv=function(r){ao(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 nm,e}(sr);var fv=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.createAggregator=function(t){switch(t.type){case me.COUNTER:case me.OBSERVABLE_COUNTER:case me.HISTOGRAM:return e.MONOTONIC_INSTANCE;default:return e.NON_MONOTONIC_INSTANCE}},e.MONOTONIC_INSTANCE=new ic(!0),e.NON_MONOTONIC_INSTANCE=new ic(!1),e}(sr);var Sv=function(r){ao(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 dm,e}(sr);var yv=function(r){ao(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 Jl([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0),e}(sr);var Ka=function(r){ao(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 Jl(this._boundaries,this._recordMinMax)},e}(sr);var bv=function(r){ao(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 um(this._maxSize,this._recordMinMax)},e}(sr);var Ev=function(r){ao(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype._resolve=function(t){switch(t.type){case me.COUNTER:case me.UP_DOWN_COUNTER:case me.OBSERVABLE_COUNTER:case me.OBSERVABLE_UP_DOWN_COUNTER:return vv;case me.GAUGE:case me.OBSERVABLE_GAUGE:return Av;case me.HISTOGRAM:return t.advice.explicitBucketBoundaries?new Ka(t.advice.explicitBucketBoundaries):wv}return z.warn("Unable to recognize instrument type: "+t.type),Tv},e.prototype.createAggregator=function(t){return this._resolve(t).createAggregator(t)},e}(sr);var Tv=new hv,vv=new fv,Av=new Sv,wv=new yv,gk=new bv,hk=new Ev;var Rv=function(r){return sr.Default()},Cv=function(r){return si.CUMULATIVE};var pm=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())})},mm=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}}},xv=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},fk=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))},Mv=function(){function r(e){var t,n,o;this._shutdown=!1,this._aggregationSelector=(t=e?.aggregationSelector)!==null&&t!==void 0?t:Rv,this._aggregationTemporalitySelector=(n=e?.aggregationTemporalitySelector)!==null&&n!==void 0?n:Cv,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 pm(this,void 0,void 0,function(){var t,n,o,i,a,s;return mm(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(fk([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis})],xv(this._metricProducers.map(function(l){return l.collect({timeoutMillis:e?.timeoutMillis})})),!1))];case 1:return t=xv.apply(void 0,[c.sent()]),n=t[0],o=t.slice(1),i=n.errors.concat(rm(o,function(l){return l.errors})),a=n.resourceMetrics.resource,s=n.resourceMetrics.scopeMetrics.concat(rm(o,function(l){return l.resourceMetrics.scopeMetrics})),[2,{resourceMetrics:{resource:a,scopeMetrics:s},errors:i}]}})})},r.prototype.shutdown=function(e){return pm(this,void 0,void 0,function(){return mm(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,Tn(this.onShutdown(),e.timeoutMillis)];case 3:t.sent(),t.label=4;case 4:return this._shutdown=!0,[2]}})})},r.prototype.forceFlush=function(e){return pm(this,void 0,void 0,function(){return mm(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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,Tn(this.onForceFlush(),e.timeoutMillis)];case 3:return t.sent(),[2]}})})},r}();_e();var Sk=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)}}(),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())})},sc=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}}},yk=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},bk=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))},gm=function(r){Sk(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 ac(this,void 0,void 0,function(){var t;return sc(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,Tn(this._doRun(),this._exportTimeout)];case 1:return n.sent(),[3,3];case 2:return t=n.sent(),t instanceof tm?(z.error("Export took longer than %s milliseconds and timed out.",this._exportTimeout),[2]):(nc(t),[3,3]);case 3:return[2]}})})},e.prototype._doRun=function(){var t,n;return ac(this,void 0,void 0,function(){var o,i,a,s,c,l;return sc(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=z).error.apply(l,bk(["PeriodicExportingMetricReader: metrics collection errors"],yk(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(),z.debug("Error while resolving async portion of resource: ",s),nc(s),[3,5];case 5:return i.scopeMetrics.length===0?[2]:[4,gv._export(this._exporter,i)];case 6:if(c=u.sent(),c.code!==qa.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),$a(this._interval)},e.prototype.onForceFlush=function(){return ac(this,void 0,void 0,function(){return sc(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 ac(this,void 0,void 0,function(){return sc(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}(Mv);_e();_e();function lc(){return"unknown_service:"+process.argv0}var An=function(){return An=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},An.apply(this,arguments)},Ek=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())})},Tk=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}}},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},cc=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 z.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[dv]=lc(),e[ja]=oo[ja],e[Va]=oo[Va],e[Wa]=oo[Wa],e))},Object.defineProperty(r.prototype,"attributes",{get:function(){var e;return this.asyncAttributesPending&&z.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 Ek(this,void 0,void 0,function(){return Tk(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=An(An({},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=vk(a,2),l=c[0],u=c[1];return An(An(An(An({},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}();_e();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)}}(),uc=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=ti.active()),typeof e!="number"){z.warn("non-number value provided to metric "+this._descriptor.name+": "+e);return}this._descriptor.valueType===Vt.INT&&!Number.isInteger(e)&&(z.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,io(Date.now()))},r}();var Pv=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}(uc);var Iv=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){z.warn("negative value provided to counter "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(uc);var Ov=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}(uc);var Lv=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){z.warn("negative value provided to histogram "+this._descriptor.name+": "+t);return}this._record(t,n,o)},e}(uc);var dc=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 Nv=function(r){so(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dc);var Dv=function(r){so(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dc);var kv=function(r){so(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e}(dc);function Ya(r){return r instanceof dc}var Uv=function(){function r(e){this._meterSharedState=e}return r.prototype.createGauge=function(e,t){var n=kr(e,me.GAUGE,t),o=this._meterSharedState.registerMetricStorage(n);return new Ov(o,n)},r.prototype.createHistogram=function(e,t){var n=kr(e,me.HISTOGRAM,t),o=this._meterSharedState.registerMetricStorage(n);return new Lv(o,n)},r.prototype.createCounter=function(e,t){var n=kr(e,me.COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Iv(o,n)},r.prototype.createUpDownCounter=function(e,t){var n=kr(e,me.UP_DOWN_COUNTER,t),o=this._meterSharedState.registerMetricStorage(n);return new Pv(o,n)},r.prototype.createObservableGauge=function(e,t){var n=kr(e,me.OBSERVABLE_GAUGE,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Dv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableCounter=function(e,t){var n=kr(e,me.OBSERVABLE_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new Nv(n,o,this._meterSharedState.observableRegistry)},r.prototype.createObservableUpDownCounter=function(e,t){var n=kr(e,me.OBSERVABLE_UP_DOWN_COUNTER,t),o=this._meterSharedState.registerAsyncMetricStorage(n);return new kv(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 pc=function(){function r(e){this._instrumentDescriptor=e}return r.prototype.getInstrumentDescriptor=function(){return this._instrumentDescriptor},r.prototype.updateDescription=function(e){this._instrumentDescriptor=kr(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})},r}();var Ak=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)}}(),Fv=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}}},wk=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 Fv(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 Fv(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 Sr=function(r){Ak(e,r);function e(){return r.call(this,Yl)||this}return e}(wk);var Rk=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){this._aggregator=e,this._activeCollectionStorage=new Sr,this._cumulativeMemoStorage=new Sr,this._overflowAttributes={"otel.metric.overflow":!0},this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=Yl(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=Rk(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 p=n._activeCollectionStorage.get(a,c);u=n._aggregator.merge(p,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 Sr,e},r}();var hm=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.")},Bv=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},gc=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=Ck(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=hm(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 Sr,i=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),i===void 0)return o;try{for(var a=hm(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=Bv(a.value,3),c=s[0],l=s[1],u=s[2];if(e.has(c,u)){var d=e.get(c,u),p=n.merge(d,l);o.set(c,p,u)}else o.set(c,l,u);a=i.next()}return o},r.calibrateStartTime=function(e,t,n){var o,i;try{for(var a=hm(e.keys()),s=a.next();!s.done;s=a.next()){var c=Bv(s.value,2),l=c[0],u=c[1],d=t.get(l,u);d?.setStartTime(n)}}catch(p){o={error:p}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(o)throw o.error}}return t},r}();function Ck(r){return Array.from(r.entries())}var xk=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)}}(),Mk=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},zv=function(r){xk(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 mc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new gc(n,i),s}return e.prototype.record=function(t,n){var o=this,i=new Sr;Array.from(t.entries()).forEach(function(a){var s=Mk(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}(pc);_e();function fm(r,e){var t="";return r.unit!==e.unit&&(t+=" - Unit '"+r.unit+"' does not match '"+e.unit+`'
|
|
24
24
|
`),r.type!==e.type&&(t+=" - Type '"+r.type+"' does not match '"+e.type+`'
|
|
25
25
|
`),r.valueType!==e.valueType&&(t+=" - Value Type '"+r.valueType+"' does not match '"+e.valueType+`'
|
|
26
26
|
`),r.description!==e.description&&(t+=" - Description '"+r.description+"' does not match '"+e.description+`'
|
|
27
|
-
`),t}function
|
|
27
|
+
`),t}function _k(r,e){return" - use valueType '"+r.valueType+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function Pk(r,e){return" - use unit '"+r.unit+"' on instrument creation or use an instrument name other than '"+e.name+"'"}function Ik(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+"'"}function Ok(r,e){var t={name:e.name,type:e.type,unit:e.unit},n=JSON.stringify(t);return" - create a new view with a name other than '"+r.name+"' and InstrumentSelector '"+n+`'
|
|
28
28
|
- OR - create a new view with the name `+r.name+" and description '"+r.description+"' and InstrumentSelector "+n+`
|
|
29
|
-
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function
|
|
29
|
+
- OR - create a new view with the name `+e.name+" and description '"+r.description+"' and InstrumentSelector "+n}function Sm(r,e){return r.valueType!==e.valueType?_k(r,e):r.unit!==e.unit?Pk(r,e):r.type!==e.type?Ik(r,e):r.description!==e.description?Ok(r,e):""}var ym=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.")},Hv=function(){function r(){this._sharedRegistry=new Map,this._perCollectorRegistry=new Map}return r.create=function(){return new r},r.prototype.getStorages=function(e){var t,n,o,i,a=[];try{for(var s=ym(this._sharedRegistry.values()),c=s.next();!c.done;c=s.next()){var l=c.value;a=a.concat(l)}}catch(g){t={error:g}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}var u=this._perCollectorRegistry.get(e);if(u!=null)try{for(var d=ym(u.values()),p=d.next();!p.done;p=d.next()){var l=p.value;a=a.concat(l)}}catch(g){o={error:g}}finally{try{p&&!p.done&&(i=d.return)&&i.call(d)}finally{if(o)throw o.error}}return a},r.prototype.register=function(e){this._registerStorage(e,this._sharedRegistry)},r.prototype.registerForCollector=function(e,t){var n=this._perCollectorRegistry.get(e);n==null&&(n=new Map,this._perCollectorRegistry.set(e,n)),this._registerStorage(t,n)},r.prototype.findOrUpdateCompatibleStorage=function(e){var t=this._sharedRegistry.get(e.name);return t===void 0?null:this._findOrUpdateCompatibleStorage(e,t)},r.prototype.findOrUpdateCompatibleCollectorStorage=function(e,t){var n=this._perCollectorRegistry.get(e);if(n===void 0)return null;var o=n.get(t.name);return o===void 0?null:this._findOrUpdateCompatibleStorage(t,o)},r.prototype._registerStorage=function(e,t){var n=e.getInstrumentDescriptor(),o=t.get(n.name);if(o===void 0){t.set(n.name,[e]);return}o.push(e)},r.prototype._findOrUpdateCompatibleStorage=function(e,t){var n,o,i=null;try{for(var a=ym(t),s=a.next();!s.done;s=a.next()){var c=s.value,l=c.getInstrumentDescriptor();JT(l,e)?(l.description!==e.description&&(e.description.length>l.description.length&&c.updateDescription(e.description),z.warn("A view or instrument with the name ",e.name,` has already been registered, but has a different description and is incompatible with another registered view.
|
|
30
30
|
`,`Details:
|
|
31
|
-
`,
|
|
32
|
-
To resolve the conflict:`,
|
|
31
|
+
`,fm(l,e),`The longer description will be used.
|
|
32
|
+
To resolve the conflict:`,Sm(l,e))),i=c):z.warn("A view or instrument with the name ",e.name,` has already been registered and is incompatible with another registered view.
|
|
33
33
|
`,`Details:
|
|
34
|
-
`,
|
|
35
|
-
`,fp(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 Ev=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}();_e();_e();var Tv=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new yr}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===Gt.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 vv=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ya(e)){var o=this._buffer.get(e);if(o==null&&(o=new yr,this._buffer.set(e,o)),typeof t!="number"){H.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Gt.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 yp=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())})},bp=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}}},Av=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},wv=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))},Rv=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(Ya));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(Ya)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return yp(this,void 0,void 0,function(){var n,o,i,a;return bp(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,AT(wv(wv([],Av(n),!1),Av(o),!1))];case 1:return i=s.sent(),a=i.filter(wT).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 yp(n,void 0,void 0,function(){var s,c;return bp(this,function(l){switch(l.label){case 0:return s=new Tv(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),t!=null&&(c=Tn(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 yp(n,void 0,void 0,function(){var s,c;return bp(this,function(l){switch(l.label){case 0:return s=new vv,c=Promise.resolve(i(s)),t!=null&&(c=Tn(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&&RT(n.instruments,t)})},r}();var Mk=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)}}(),Cv=function(r){Mk(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 pc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new gc(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}(mc);var xv=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)}}(),li=function(){function r(){}return r.Noop=function(){return Pk},r}();var _k=function(r){xv(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(li);var Mv=function(r){xv(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}(li);var Pk=new _k;var Ik=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())})},Ok=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}}},Lk=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},_v=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new bv,this.observableRegistry=new Rv,this.meter=new hv(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,Cv);return t.length===1?t[0]:new Ev(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,yv);return t},r.prototype.collect=function(e,t,n){return Ik(this,void 0,void 0,function(){var o,i,a;return Ok(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(TT),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=MT(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=Lk(c,2),u=l[0],d=l[1],m=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(m!=null)return m;var p=d.createAggregator(e),g=u.selectCardinalityLimit(e.type),h=new t(e,p,li.Noop(),[u],g);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var Nk=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.")},Pv=function(){function r(e){this.resource=e,this.viewRegistry=new sv,this.metricCollectors=[],this.meterSharedStates=new Map}return r.prototype.getMeterSharedState=function(e){var t=vT(e),n=this.meterSharedStates.get(t);return n==null&&(n=new _v(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=Nk(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 hc=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())})},fc=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}}},Dk=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))},Iv=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return hc(this,void 0,void 0,function(){var t,n,o,i,a=this;return fc(this,function(s){switch(s.label){case 0:return t=oo(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return hc(a,void 0,void 0,function(){var l;return fc(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,kk([],Dk(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 hc(this,void 0,void 0,function(){return fc(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 hc(this,void 0,void 0,function(){return fc(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 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())})},Lv=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}}},Nv=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 Uk(r,e){var t=e??cc.empty();return r?cc.default().merge(t):t}var Ep=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new Pv(Uk((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=Nv(e.views),c=s.next();!c.done;c=s.next()){var l=c.value;this._sharedState.viewRegistry.addView(l)}}catch(p){t={error:p}}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=Nv(e.readers),d=u.next();!d.done;d=u.next()){var m=d.value;this.addMetricReader(m)}}catch(p){o={error:p}}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"),Rm()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new Iv(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return Ov(this,void 0,void 0,function(){return Lv(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 Ov(this,void 0,void 0,function(){return Lv(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 Fk=/[\^$\\.+?()[\]{}|]/g,Sc=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(Fk,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var ci=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 Dv=function(){function r(e){var t;this._nameFilter=new Sc((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new ci(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 kv=function(){function r(e){this._nameFilter=new ci(e?.name),this._versionFilter=new ci(e?.version),this._schemaUrlFilter=new ci(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 Bk(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var yc=function(){function r(e){var t;if(Bk(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Sc.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 Mv(e.attributeKeys):this.attributesProcessor=li.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:ar.Default(),this.instrumentSelector=new Dv({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new kv({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var $se=process.env.APP||"unknown";_e();import{v4 as zk}from"uuid";function Hk(){return new yT({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:ro.DELTA})}var Gk=[new yc({instrumentName:"test_event_duration",instrumentType:ge.HISTOGRAM,aggregation:new Ka([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new yc({instrumentName:"test_step_duration",instrumentType:ge.HISTOGRAM,aggregation:new Ka([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],Ec=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 Vm({[Ul]:e.serviceName,[gE]:t,[fE]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:zk()}),o=Hk(),i=new pp({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Ep({resource:n,readers:[i],views:Gk}),Ll.setGlobalMeterProvider(this.provider),this.meter=Ll.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Pl(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=Pl(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 ft=new _l;function Uv(r){r.disabled||(ft=new Ec(r))}import{hostname as jk}from"os";import $k from"path";import{_android as qk}from"playwright";async function Fv(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:p,playwrightServerUrl:g}=await e.createAndroidEmulator({...n,hostname:jk(),sessionId:s}),h;try{Wk("adb --version"),h="adb"}catch{if(process.env.ANDROID_HOME)h=$k.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:p,apkDownloadUrl:m,sessionId:s,playwrightServerUrl:g},"Android instance creation ok");let f=await ft.recordDuration({fn:async()=>await Vk({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 T=await ft.recordDuration({fn:async()=>await f.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]}),v=()=>{T.close(),f.disconnect()},O;return g&&(o("Opening Playwright connection"),O=await ft.recordDuration({fn:async()=>await qk.connect(g),name:"test_event_duration",tags:["name:playwright-device-connect",`orgId:${a}`]})),{adbPort:T.address.port,close:v,limbarToken:c,limbarUrl:l,emulatorName:d,playwrightDevice:O,client:f}}async function Tc({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 Fv({apiClient:t,logger:n,creationOpts:e,onStatusUpdate:r,orgId:s,sessionId:c});let g=d.emulatorName;u.push(()=>t.deleteAndroidEmulator(g),d.close)}let m=async()=>{for(let g=u.length-1;g>=0;g-=1)try{await u[g]()}catch(h){if(h instanceof Error&&h.message.includes("ECONNREFUSED"))return;n.warn({err:h},"Error running cleanup task")}},p=async()=>{if(a&&!a.connected)throw await m(),new Error("Client disconnected before Appium driver could be started")};await p();try{let g=await e0({logger:n,driverLogLevel:o,appiumPort:i,emulatorStart:l,emulatorCreationParams:d,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:s,sessionId:c});return u.push(g.appiumClose),u.push(async()=>g.driver.deleteSession()),await p(),{...d,...g,cleanup:m,appiumPort:i}}catch(g){throw await m(),new Error(`Failed to start Appium driver: ${g}`)}}async function e0({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 T=0;for(;T<30;){let v=5560+Math.floor(Math.random()*100);if(v%2!==0&&(v=Math.min(v+1,5658)),await Ml(v)&&await Ml(v+1)){u=v,c=v+1;break}T+=1}if(!c)throw new Error(`Failed to find an available ADB port after ${T} attempts`)}l||(l=`emulator-${u}`,s.push(async()=>{let T=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{Yk(`${T} -s ${l} emu kill`,{stdio:"inherit"})}catch(v){r.warn({err:v,emulatorName:l},"Failed to kill emulator")}}));let d=Date.now(),{close:m,logFile:p}=await t0({logger:r,logLevel:e,appiumPort:n}),g={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:g,connectionRetryTimeout:15e3,connectionRetryCount:2};"avdId"in o&&(g["appium:avd"]=o.avdId,g["appium:avdLaunchTimeout"]=18e4,g["appium:avdReadyTimeout"]=18e4,g["appium:skipDeviceInitialization"]=!1,g["appium:skipServerInstallation"]=!1,g["appium:udid"]=void 0,g["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 Qk(h)}catch(T){throw i(`Emulator creation failed: ${T}`),await Promise.all(s.map(v=>v())),T}if(await E.updateSettings({enableMultiWindows:!0}),"avdId"in a){let T=a.apkFilePath?.trim();if(T){let v=Zk.resolve(T);if(!Xk.existsSync(v))throw new Error(`APK not found at path: ${v}`);i("Installing local APK...");let O=Date.now();try{await E.installApp(v),r.info({apkFilePath:v,installDurationMs:Date.now()-O},"Installed local APK")}catch(w){throw r.error({err:w,apkFilePath:v},"Failed to install local APK"),new Error(`Failed to install APK from ${v}: ${w.message}`)}}}let b=new Map;return E.on("command",T=>{b.set(T.command,Date.now())}),E.on("result",T=>{let v=b.get(T.command);if(!v)return;let O=Date.now()-v;T.result instanceof Error?r.warn({err:T.result,command:T.command,args:T.body,durationMs:O},"Appium cmd failed"):O>1e4&&r.warn({command:T.command,args:T.body,durationMs:O},"Appium cmd took very long"),b.delete(T.command)}),r.info({timings:{emulatorDuration:d-t,appiumDuration:f-d,wdioDuration:Date.now()-f},capabilities:g,emulatorName:l},"Started Appium driver"),{driver:E,appiumClose:async()=>{await m(),await Promise.all(s.map(T=>T()))},appiumPort:n,appiumLogFile:p,emulatorName:l,adbPort:c}}async function t0({logger:r,logLevel:e,appiumPort:t}){let n=`${Jk()}/appium-port-${Date.now()}.log`,o=await Kk.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 Bv from"crypto";import r0 from"fs";async function vc({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await r0.promises.readFile(t),a=Bv.createHash("md5").update(i).digest("base64"),s=Bv.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 zv}from"child_process";import{existsSync as n0}from"fs";import{platform as Hv}from"os";import{dirname as o0,join as i0,resolve as a0}from"path";import{fileURLToPath as s0}from"url";var Gv,l0=s0(import.meta.url),c0=o0(l0);Gv=a0(c0,"..");var Xa=Gv;R.info(`Setting APPIUM_HOME to ${Xa}`);process.env.APPIUM_HOME=Xa;var u0="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.",d0="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.",m0="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",Vv="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",Wv="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function p0(){if(!process.env.JAVA_HOME)R.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)&&R.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)=>i0(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");n0(e)||R.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{zv("java --version",{stdio:"pipe",encoding:"utf-8"})||(R.error(`Could not find a Java installation. ${u0}`),process.exit(1))}catch(r){R.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function g0(){process.env.ANDROID_HOME||(R.error(`The ANDROID_HOME environment variable is not set. ${m0} ${Hv()==="darwin"?Vv:Wv}`),process.exit(1))}function h0(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{zv(`${r} version`,{stdio:"pipe",encoding:"utf-8"})||(R.error(`Could not find the Android Debug Bridge (ADB) tool locally. This tool is included with Android Studio. ${d0} Finally, ensure that the 'adb' command is available in your shell. ${Hv()==="darwin"?Vv:Wv}`),process.exit(1))}catch(e){R.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function jv(){p0(),g0(),h0()}import{create as f0,windowedFiniteBatchScheduler as S0}from"@yornaath/batshit";import y0 from"ws";var b0=100,E0=2500,$v=4e3,T0="\u2026";async function Ac({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=f0({fetcher:async l=>{e(l)},resolver:()=>{},scheduler:S0({windowMs:E0,maxBatchSize:b0})}),{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 y0(s);return c.on("message",l=>{let u=l.toString().trim();u.length!==0&&(u.length>$v&&(u=u.slice(0,$v)+T0),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}try{t.next()}catch{}}}import{Server as jz}from"socket.io";import Ez from"path";import{randomUUID as O0}from"crypto";import{faker as v0}from"@faker-js/faker";import A0 from"assert";import w0 from"axios";import*as R0 from"child_process";import C0 from"moment";import*as x0 from"otpauth";import M0 from"pg";async function qv(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Qs(n,e);t.push(...o)}),t}function _0(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 P0(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 I0=Object.getPrototypeOf(async function(){}).constructor;async function Kv(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,T)=>{o[x]=T,l[x]=T},d={},m=(x,T)=>{o[x]=T,d[x]=T},p;n.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let g;n.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new I0("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(w0,C0,c.fakerInstance??v0,A0,M0,p,g,x0,R0,qv,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:m,T=>c.sms.send(T),T=>c.sms.fetchLatest(T),c.email,c.sms,c.ai,_0(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 P0(e.options.responseSerialization??"RAW",x)}catch(x){t.error({err:x,env:o,evalCode:n},`[${r}] Error executing code: ${x}`),f=!1,x instanceof Sn?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 Yv({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=pn,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=O0(),m=await Kv(d,{code:r,options:{fragment:e,timeoutMs:a,disallowVariableUpdates:s,responseSerialization:l},bindings:{...t.toObjectCopy(),...u,additionalBindings:c},tools:n,signal:i},o);return R.debug(`[${d}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as L0,randomUUID as N0}from"crypto";import D0 from"fetch-retry";var k0=D0(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}}),Xv=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Jv=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Zv({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=pn,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!Xv)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,p,g=0;if(!Jv)throw new Error("Missing lambda auth secret.");let h=L0("sha256",Jv).update(r).digest("hex");for(;g<=i;){g++,a?.throwIfAborted();let E={id:N0(),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(k0(Xv,{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}`);p=void 0;break}catch(b){p=b}}if(p)throw s.error({err:p},"Failed to evaluate code remotely"),p;if(!m)throw new Error(`An unexpected code evaluation error occurred${p?`: ${p}`:""}`);let f;try{f=QS.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 Ur(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Zv(r);else if(r.localTools)e=await Yv({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
34
|
+
`,fm(l,e),`To resolve the conflict:
|
|
35
|
+
`,Sm(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 Gv=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}();_e();_e();var Vv=function(){function r(e,t){this._instrumentName=e,this._valueType=t,this._buffer=new Sr}return r.prototype.observe=function(e,t){if(t===void 0&&(t={}),typeof e!="number"){z.warn("non-number value provided to metric "+this._instrumentName+": "+e);return}this._valueType===Vt.INT&&!Number.isInteger(e)&&(z.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 jv=function(){function r(){this._buffer=new Map}return r.prototype.observe=function(e,t,n){if(n===void 0&&(n={}),!!Ya(e)){var o=this._buffer.get(e);if(o==null&&(o=new Sr,this._buffer.set(e,o)),typeof t!="number"){z.warn("non-number value provided to metric "+e._descriptor.name+": "+t);return}e._descriptor.valueType===Vt.INT&&!Number.isInteger(t)&&(z.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 bm=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())})},Em=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},$v=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},qv=function(){function r(){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(Ya));if(n.size===0){z.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(Ya)),o=this._findBatchCallback(e,n);o<0||this._batchCallbacks.splice(o,1)},r.prototype.observe=function(e,t){return bm(this,void 0,void 0,function(){var n,o,i,a;return Em(this,function(s){switch(s.label){case 0:return n=this._observeCallbacks(e,t),o=this._observeBatchCallbacks(e,t),[4,WT($v($v([],Wv(n),!1),Wv(o),!1))];case 1:return i=s.sent(),a=i.filter($T).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 bm(n,void 0,void 0,function(){var s,c;return Em(this,function(l){switch(l.label){case 0:return s=new Vv(a._descriptor.name,a._descriptor.valueType),c=Promise.resolve(i(s)),t!=null&&(c=Tn(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 bm(n,void 0,void 0,function(){var s,c;return Em(this,function(l){switch(l.label){case 0:return s=new jv,c=Promise.resolve(i(s)),t!=null&&(c=Tn(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(p){p.record(d,e)})}),[2]}})})})},r.prototype._findCallback=function(e,t){return this._callbacks.findIndex(function(n){return n.callback===e&&n.instrument===t})},r.prototype._findBatchCallback=function(e,t){return this._batchCallbacks.findIndex(function(n){return n.callback===e&&qT(n.instruments,t)})},r}();var Lk=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)}}(),Kv=function(r){Lk(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 mc(n,s._aggregationCardinalityLimit),s._temporalMetricStorage=new gc(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}(pc);var Yv=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)}}(),di=function(){function r(){}return r.Noop=function(){return Dk},r}();var Nk=function(r){Yv(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.process=function(t,n){return t},e}(di);var Xv=function(r){Yv(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}(di);var Dk=new Nk;var kk=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())})},Uk=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}}},Fk=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},Jv=function(){function r(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.metricStorageRegistry=new Hv,this.observableRegistry=new qv,this.meter=new Uv(this)}return r.prototype.registerMetricStorage=function(e){var t=this._registerMetricStorage(e,Kv);return t.length===1?t[0]:new Gv(t)},r.prototype.registerAsyncMetricStorage=function(e){var t=this._registerMetricStorage(e,zv);return t},r.prototype.collect=function(e,t,n){return kk(this,void 0,void 0,function(){var o,i,a;return Uk(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(VT),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=XT(c,e),u=n.metricStorageRegistry.findOrUpdateCompatibleStorage(l);if(u!=null)return u;var d=c.aggregation.createAggregator(l),p=new t(l,d,c.attributesProcessor,n._meterProviderSharedState.metricCollectors,c.aggregationCardinalityLimit);return n.metricStorageRegistry.register(p),p});if(i.length===0){var a=this._meterProviderSharedState.selectAggregations(e.type),s=a.map(function(c){var l=Fk(c,2),u=l[0],d=l[1],p=n.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(u,e);if(p!=null)return p;var g=d.createAggregator(e),m=u.selectCardinalityLimit(e.type),h=new t(e,g,di.Noop(),[u],m);return n.metricStorageRegistry.registerForCollector(u,h),h});i=i.concat(s)}return i},r}();var Bk=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.")},Zv=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=jT(e),n=this.meterSharedStates.get(t);return n==null&&(n=new Jv(this,e),this.meterSharedStates.set(t,n)),n},r.prototype.selectAggregations=function(e){var t,n,o=[];try{for(var i=Bk(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 hc=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())})},fc=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}}},zk=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},Hk=function(r,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,i;n<o;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return r.concat(i||Array.prototype.slice.call(e))},Qv=function(){function r(e,t){this._sharedState=e,this._metricReader=t}return r.prototype.collect=function(e){return hc(this,void 0,void 0,function(){var t,n,o,i,a=this;return fc(this,function(s){switch(s.label){case 0:return t=io(Date.now()),n=[],o=[],i=Array.from(this._sharedState.meterSharedStates.values()).map(function(c){return hc(a,void 0,void 0,function(){var l;return fc(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,Hk([],zk(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 hc(this,void 0,void 0,function(){return fc(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 hc(this,void 0,void 0,function(){return fc(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 eA=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())})},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}}},rA=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 Gk(r,e){var t=e??cc.empty();return r?cc.default().merge(t):t}var Tm=function(){function r(e){var t,n,o,i,a;if(this._shutdown=!1,this._sharedState=new Zv(Gk((a=e?.mergeResourceWithDefaults)!==null&&a!==void 0?a:!0,e?.resource)),e?.views!=null&&e.views.length>0)try{for(var s=rA(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=rA(e.readers),d=u.next();!d.done;d=u.next()){var p=d.value;this.addMetricReader(p)}}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?(z.warn("A shutdown MeterProvider cannot provide a Meter"),Cp()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:n.schemaUrl}).meter},r.prototype.addMetricReader=function(e){var t=new Qv(this._sharedState,e);e.setMetricProducer(t),this._sharedState.metricCollectors.push(t)},r.prototype.shutdown=function(e){return eA(this,void 0,void 0,function(){return tA(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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 eA(this,void 0,void 0,function(){return tA(this,function(t){switch(t.label){case 0:return this._shutdown?(z.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 Vk=/[\^$\\.+?()[\]{}|]/g,Sc=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(Vk,"\\$&").replace("*",".*")+"$"},r.hasWildcard=function(e){return e.includes("*")},r}();var pi=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 nA=function(){function r(e){var t;this._nameFilter=new Sc((t=e?.name)!==null&&t!==void 0?t:"*"),this._type=e?.type,this._unitFilter=new pi(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 oA=function(){function r(e){this._nameFilter=new pi(e?.name),this._versionFilter=new pi(e?.version),this._schemaUrlFilter=new pi(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 jk(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}var yc=function(){function r(e){var t;if(jk(e))throw new Error("Cannot create view with no selector arguments supplied");if(e.name!=null&&(e?.instrumentName==null||Sc.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 Xv(e.attributeKeys):this.attributesProcessor=di.Noop(),this.name=e.name,this.description=e.description,this.aggregation=(t=e.aggregation)!==null&&t!==void 0?t:sr.Default(),this.instrumentSelector=new nA({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new oA({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}return r}();var Xse=process.env.APP||"unknown";_e();import{v4 as Wk}from"uuid";function $k(){return new zT({url:"https://us-west.metrics.momentic.ai/v1/metrics",headers:{"x-momentic-metrics-api-key":"c60c6a0f-60da-41a7-a61b-07969a0aa303"},temporalityPreference:no.DELTA})}var qk=[new yc({instrumentName:"test_event_duration",instrumentType:me.HISTOGRAM,aggregation:new Ka([100,500,1e3,5e3,7500,1e4,15e3,2e4])}),new yc({instrumentName:"test_step_duration",instrumentType:me.HISTOGRAM,aggregation:new Ka([100,500,1e3,5e3,7500,1e4,15e3,2e4])})],Ec=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 jp({[Ul]:e.serviceName,[kE]:t,[FE]:typeof process<"u"&&process.env.SERVICE_INSTANCE_ID?process.env.SERVICE_INSTANCE_ID:Wk()}),o=$k(),i=new gm({exporter:o,exportIntervalMillis:e.exportIntervalMs??15e3});this.provider=new Tm({resource:n,readers:[i],views:qk}),Ll.setGlobalMeterProvider(this.provider),this.meter=Ll.getMeter("momentic-serverless")}increment(e,t,n){try{let o=Pl(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=Pl(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 yt=new _l;function iA(r){r.disabled||(yt=new Ec(r))}import{hostname as Xk}from"os";import Jk from"path";import{_android as Zk}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:p,region:g,playwrightServerUrl:m}=await e.createAndroidEmulator({...n,hostname:Xk(),sessionId:s}),h;try{Yk("adb --version"),h="adb"}catch{if(process.env.ANDROID_HOME)h=Jk.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:p,sessionId:s,playwrightServerUrl:m},"Android instance creation ok");let f=await yt.recordDuration({fn:async()=>await Kk({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"];p&&E.push(p);let b=n.apkToInstall?.channel,R=n.apkToInstall?.tag;o(`Installing APK${b?` with channel ${b}`:""}${R?` and tag ${R}`:""}`),await Promise.all(E.map(w=>f.sendAsset(w))),o("Starting ADB tunnel");let A=await yt.recordDuration({fn:async()=>await f.startAdbTunnel(),name:"test_event_duration",tags:["name:limbar-tunnel-connect",`orgId:${a}`]}),T=()=>{A.close(),f.disconnect()},_;return m&&(o("Opening Playwright connection"),_=await yt.recordDuration({fn:async()=>await Zk.connect(m),name:"test_event_duration",tags:["name:playwright-device-connect",`orgId:${a}`]})),{adbPort:A.address.port,close:T,limbarToken:c,limbarUrl:l,emulatorName:d,playwrightDevice:_,client:f}}async function Tc({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 m=d.emulatorName;u.push(()=>t.deleteAndroidEmulator(m),d.close)}let p=async()=>{for(let m=u.length-1;m>=0;m-=1)try{await u[m]()}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 p(),new Error("Client disconnected before Appium driver could be started")};await g();try{let m=await i0({logger:n,driverLogLevel:o,appiumPort:i,emulatorStart:l,emulatorCreationParams:d,apiClient:t,onStatusUpdate:r,creationOpts:e,orgId:s,sessionId:c});return u.push(m.appiumClose),u.push(async()=>m.driver.deleteSession()),await g(),{...d,...m,cleanup:p,appiumPort:i}}catch(m){throw await p(),new Error(`Failed to start Appium driver: ${m}`)}}async function i0({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 A=0;for(;A<30;){let T=5560+Math.floor(Math.random()*100);if(T%2!==0&&(T=Math.min(T+1,5658)),await Ml(T)&&await Ml(T+1)){u=T,c=T+1;break}A+=1}if(!c)throw new Error(`Failed to find an available ADB port after ${A} attempts`)}l||(l=`emulator-${u}`,s.push(async()=>{let A=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{e0(`${A} -s ${l} emu kill`,{stdio:"inherit"})}catch(T){r.warn({err:T,emulatorName:l},"Failed to kill emulator")}}));let d=Date.now(),{close:p,logFile:g}=await a0({logger:r,logLevel:e,appiumPort:n}),m={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:m,connectionRetryTimeout:15e3,connectionRetryCount:2};"avdId"in o&&(m["appium:avd"]=o.avdId,m["appium:avdLaunchTimeout"]=18e4,m["appium:avdReadyTimeout"]=18e4,m["appium:skipDeviceInitialization"]=!1,m["appium:skipServerInstallation"]=!1,m["appium:udid"]=void 0,m["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 o0(h)}catch(A){throw i(`Emulator creation failed: ${A}`),await Promise.all(s.map(T=>T())),A}if(await E.updateSettings({enableMultiWindows:!0}),"avdId"in a){let A=a.apkFilePath?.trim();if(A){let T=n0.resolve(A);if(!t0.existsSync(T))throw new Error(`APK not found at path: ${T}`);i("Installing local APK...");let _=Date.now();try{await E.installApp(T),r.info({apkFilePath:T,installDurationMs:Date.now()-_},"Installed local APK")}catch(w){throw r.error({err:w,apkFilePath:T},"Failed to install local APK"),new Error(`Failed to install APK from ${T}: ${w.message}`)}}}let b=new Map;return E.on("command",A=>{b.set(A.command,Date.now())}),E.on("result",A=>{let T=b.get(A.command);if(!T)return;let _=Date.now()-T;A.result instanceof Error?r.warn({err:A.result,command:A.command,args:A.body,durationMs:_},"Appium cmd failed"):_>1e4&&r.warn({command:A.command,args:A.body,durationMs:_},"Appium cmd took very long"),b.delete(A.command)}),r.info({timings:{emulatorDuration:d-t,appiumDuration:f-d,wdioDuration:Date.now()-f},capabilities:m,emulatorName:l},"Started Appium driver"),{driver:E,appiumClose:async()=>{await p(),await Promise.all(s.map(A=>A()))},appiumPort:n,appiumLogFile:g,emulatorName:l,adbPort:c}}async function a0({logger:r,logLevel:e,appiumPort:t}){let n=`${r0()}/appium-port-${Date.now()}.log`,o=await Qk.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 sA from"crypto";import s0 from"fs";async function vc({tag:r,channel:e,filePath:t,apiClient:n,logger:o}){let i=await s0.promises.readFile(t),a=sA.createHash("md5").update(i).digest("base64"),s=sA.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 lA}from"child_process";import{existsSync as l0}from"fs";import{platform as cA}from"os";import{dirname as c0,join as u0,resolve as d0}from"path";import{fileURLToPath as p0}from"url";var uA,m0=p0(import.meta.url),g0=c0(m0);uA=d0(g0,"..");var Xa=uA;C.info(`Setting APPIUM_HOME to ${Xa}`);process.env.APPIUM_HOME=Xa;var h0="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.",f0="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.",S0="Follow the instructions at https://developer.android.com/tools/variables to set the ANDROID_HOME environment variable.",dA="On Mac OS, the SDK is typically installed at /Users/<username>/Library/Android/sdk.",pA="On Windows, the SDK is typically installed at C:\\Users\\<username>\\AppData\\Local\\Android\\Sdk.";function y0(){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)=>u0(t,"bin",process.platform==="win32"?`${n}.exe`:n))(process.env.JAVA_HOME,"java");l0(e)||C.warn(`JAVA_HOME does not appear to point to a valid Java installation: expected the 'java' binary to exist at ${e}`)}try{lA("java --version",{stdio:"pipe",encoding:"utf-8"})||(C.error(`Could not find a Java installation. ${h0}`),process.exit(1))}catch(r){C.error(`Got error while checking if the Java JDK is installed: ${r}`),process.exit(1)}}function b0(){process.env.ANDROID_HOME||(C.error(`The ANDROID_HOME environment variable is not set. ${S0} ${cA()==="darwin"?dA:pA}`),process.exit(1))}function E0(){let r=process.env.ANDROID_HOME?`${process.env.ANDROID_HOME}/platform-tools/adb`:"adb";try{lA(`${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. ${f0} Finally, ensure that the 'adb' command is available in your shell. ${cA()==="darwin"?dA:pA}`),process.exit(1))}catch(e){C.error(`Got error while checking if ADB is installed: ${e}`),process.exit(1)}}function mA(){y0(),b0(),E0()}import{create as T0,windowedFiniteBatchScheduler as v0}from"@yornaath/batshit";import A0 from"ws";var w0=100,R0=2500,gA=4e3,C0="\u2026";async function Ac({driver:r,onLogs:e}){await r.execute("mobile: startLogsBroadcast");let t=T0({fetcher:async l=>{e(l)},resolver:()=>{},scheduler:v0({windowMs:R0,maxBatchSize:w0})}),{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 A0(s);return c.on("message",l=>{let u=l.toString().trim();u.length!==0&&(u.length>gA&&(u=u.slice(0,gA)+C0),t.fetch(u).catch(()=>{}))}),async()=>{try{c.close()}catch{}try{await r.execute("mobile: stopLogsBroadcast")}catch{}try{t.next()}catch{}}}import{Server as Jz}from"socket.io";import Cz from"path";import{randomUUID as U0}from"crypto";import{faker as x0}from"@faker-js/faker";import M0 from"assert";import _0 from"axios";import*as P0 from"child_process";import I0 from"moment";import*as O0 from"otpauth";import L0 from"pg";async function hA(r){let e;try{e=new URL(r.url).hostname}catch{}let t=[];return r.headers.getSetCookie()?.forEach(n=>{let o=Qs(n,e);t.push(...o)}),t}function N0(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 D0(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 k0=Object.getPrototypeOf(async function(){}).constructor;async function fA(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=(R,A)=>{o[R]=A,l[R]=A},d={},p=(R,A)=>{o[R]=A,d[R]=A},g;n.includes("Octokit")&&(g=(await import("@octokit/rest")).Octokit);let m;n.includes("createAppAuth")&&(m=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new k0("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(i??{}),n)(_0,I0,c.fakerInstance??x0,M0,L0,g,m,O0,P0,hA,o,e.options.disallowVariableUpdates?void 0:u,e.options.disallowVariableUpdates?void 0:p,A=>c.sms.send(A),A=>c.sms.fetchLatest(A),c.email,c.sms,c.ai,N0(a,s),...Object.values(i??{}))),f=!0,E,b;try{let R=await k(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});E=await D0(e.options.responseSerialization??"RAW",R)}catch(R){t.error({err:R,env:o,evalCode:n},`[${r}] Error executing code: ${R}`),f=!1,R instanceof Sn?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=R instanceof Error?R.message:`${R}`}return{result:E,variableUpdates:l,persistentVariableUpdates:d,success:f,error:b}}async function SA({code:r,fragment:e,context:t,localTools:n,logger:o,signal:i,timeoutMs:a=mn,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:u}){let d=U0(),p=await fA(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(p)}`),p}import{createHmac as F0,randomUUID as B0}from"crypto";import z0 from"fetch-retry";var H0=z0(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}}),yA=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,bA=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function EA({orgId:r,code:e,fragment:t,context:n,timeoutMs:o=mn,retries:i=2,signal:a,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:u,mock:d}){if(!yA)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let p,g,m=0;if(!bA)throw new Error("Missing lambda auth secret.");let h=F0("sha256",bA).update(r).digest("hex");for(;m<=i;){m++,a?.throwIfAborted();let E={id:B0(),orgId:r,momenticLambdaAuthHash:h,code:e,fragment:t,state:{...n.toObjectCopy(),...d,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:u};try{if(p=await k(H0(yA,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!p)throw new Error("Got empty response from code evaluation server");if(!p.ok)throw new Error(`Code evaluation server returned error code ${p.status}`);g=void 0;break}catch(b){g=b}}if(g)throw s.error({err:g},"Failed to evaluate code remotely"),g;if(!p)throw new Error(`An unexpected code evaluation error occurred${g?`: ${g}`:""}`);let f;try{f=Ty.parse(await p.json())}catch(E){throw new Error(`Code evaluation server returned invalid response: ${E}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Ur(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await EA(r);else if(r.localTools)e=await SA({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
36
36
|
${e.error}
|
|
37
37
|
Code received:
|
|
38
|
-
${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
|
|
39
|
-
${JSON.stringify(t)}`);let n=[];return n.push({key:z0(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Cc({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"&&Ku(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 xc(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;tA(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 Ap(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 rA(r,e){return r?tA(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:Ap(e.target),updatedAt:e.updatedAt}}function Nt(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var wn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Rn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},oA={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},iA={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var pde={CONTENT:"The page"};function aA(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 wp(r){return`${r.negated?Rn.CONTAINS:wn.CONTAINS} '${r.value}'`}function sA(r){switch(r.type){case"CONTENT":return wp(r);default:return r.type,""}}function G0(r){return typeof r=="object"&&r!==null}function so(r){if(Array.isArray(r))return r.map(so);if(G0(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=so(n))}),e}return r}function V0(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${Hd(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${Hd(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 ${sA(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"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 lA(r){switch(r.type){case"MOBILE_PRESET_STEP":return V0(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 cA}from"lodash-es";async function uA(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await Mc({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 Mc({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 Mc({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await dA({rawStep:Sr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function dA({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{...cA(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=Sr.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=>dA({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),l={...a,description:a.description||void 0,steps:c};return n[o]=cA(l),{...l,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_AI_ACTION_STEP":case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as W0}from"lodash-es";import{v4 as Rp}from"uuid";async function Cn(r){let e=new Map,t=new Set,n=W0(r.steps),o=await mA({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function mA({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?Rp():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Rp():d.id,"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(vp({id:d.id,orgId:n.orgId,testId:n.testId,value:mn.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),l.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Rp():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:p,stepsToSave:g,moduleUpdates:h}=await mA({...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(p),t.has(m)||(t.add(m),l.moduleUpdates.push({...Vo.parse(u),steps:Sr.array().parse(g),moduleId:m}));let f=ya.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 j0(r){let e={parentChain:[]};return pA(r,e),e}function pA(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),pA({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function $0(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 j0({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function gA({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!!$0([r],t,i).result}function hA(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 fA({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 ume}from"lodash-es";import mme from"truncate-json";import{v4 as Tme}from"uuid";import{cloneDeep as eme,unset as tme}from"lodash-es";import{cloneDeep as Cme}from"lodash-es";import{cloneDeep as Ype}from"lodash-es";import fpe from"diff-lines";import Cp,{gte as ype}from"semver";var SA={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 yA={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 q0=["target","fromTarget","toTarget"];function bA(r){for(let e of q0){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var EA={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 bA(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])bA(n);return e}default:return e}})};import{v4 as K0}from"uuid";var TA={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=K0()),e;default:return e}})};import{v4 as vA}from"uuid";var AA={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??vA(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??vA()}})),delete e.commands),e;default:return e}})};var wA={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 Y0}from"uuid";var RA={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=Y0()),e))};import{v4 as CA}from"uuid";var xA={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=CA())}return e.id=CA(),e})};var MA={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 X0}from"uuid";var _A={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=X0()),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 PA={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 IA={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&&OA(t),e})};function OA(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){OA(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 LA={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 NA={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 DA={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 kA={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 UA={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 FA={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 _c=new Set(["CLICK","TYPE","SELECT_OPTION"]),BA={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||_c.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||_c.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||_c.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let m=d?.elementDescriptor,p=d?.type;(m!==void 0||_c.has(p))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var zA={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 HA={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 Pc=[FA,zA,HA,BA,SA,yA,EA,TA,AA,wA,RA,xA,MA,_A,PA,IA,LA,NA,DA,kA,UA];if(ln!==Pc[Pc.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Pc.forEach((r,e)=>{if(!Cp.valid(r.toVersion)||!Cp.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Cp.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(Pc[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{diff as pge}from"deep-object-diff";import{cloneDeep as hge}from"lodash-es";import{v4 as Pge}from"uuid";import{cloneDeep as Nge}from"lodash-es";import{stringify as $ge}from"yaml";async function X(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 xp({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 Za({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 xp({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function Ic(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 J0 from"picomatch";var Oc=(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||J0(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},Lc=(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}},ui=r=>{try{return new URL(r),!0}catch{return!1}},VA=r=>!r.toLowerCase().startsWith("http"),di=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function lo(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 WA}from"uuid";function Mp(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Nc=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:Mp({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(JS(e.type)){this.creditsUsedV2+=1;return}let t=Id(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Od(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:WA(),properties:Mp({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:WA(),properties:Mp({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as xhe}from"lodash-es";import{CookieJar as bz}from"tough-cookie";var _p={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
|
|
38
|
+
${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 G0}from"lodash-es";async function Ja(r){let{orgId:e,s:t,context:n,logger:o,signal:i,retries:a=2,timeoutMs:s=mn,allowUndefined:c=!1}=r,l=/{{(.*?)}}/g,u=t.matchAll(l),d=t;for(let p of u){if(p.length<2)continue;let g=p[1].trim(),m;try{m=await Ur({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(m===void 0&&!c)throw new x("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 m=="string"?m:`${m}`;h=h.replaceAll(/\$/g,"$$$$"),d=d.replace(p[0],h)}return d}async function wc(r){return TA(r)}async function TA({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 Ja({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 TA({obj:l,bannedKeys:e,context:n,prefixPath:u,replacements:i,allowList:c?void 0:t,...a})}return i}function Rc(r,e){for(let{path:t,original:n}of e)G0(r,t,n)}import V0 from"fetch-retry";var mue=process.env.MAILINATOR_API_KEY,gue=V0(global.fetch,{retryOn:function(r,e,t){return r>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(r){return 500}});import Az from"fetch-cookie";import wz from"path";import{diff as j0}from"deep-object-diff";import{cloneDeep as Bue}from"lodash-es";function AA(r,e){return!r&&!e?!1:!r||!e?!0:Object.keys(j0(r,e)).length>0}function vm({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:i}=t,a=[],s=[],c=[],l=0,u=(p,g)=>{try{let m=pn.parse(g.value);if(m.type!==p.type){o.warn({parsedCacheEntry:m,command:p},"Not using step cache due to type mismatch"),s.push(g.key);return}p.cache=m.cache,a.push(g.key),c.push(g.uniqueKey)}catch(m){s.push(g.key),o.error({err:m,cacheEntry:g},"Not using step cache due to parsing error")}},d=(p,g)=>{let m=$0(p.id,g),h=m.find(f=>!!n[f]);if(h)u(p,n[h]);else{if(p.type==="AI_CHECK")return;s.push(m[0])}};for(let p of r)switch(p.type){case"MOBILE_PRESET_STEP":{if(!il(p.command)||p.command.type==="TYPE"&&!p.command.target||"cache"in p.command&&p.command.cache.cache)continue;l++,d(p.command,i);break}case"RESOLVED_MOBILE_MODULE":{l+=p.steps.length;let{cacheKeysHit:g,cacheKeysMissed:m,uniqueKeysHit:h}=vm({...t,steps:p.steps,keyPrefix:i?`${i}:${p.id}`:p.id,topLevel:!1});a.push(...g),s.push(...m),c.push(...h);break}case"MOBILE_AI_ACTION_STEP":{l++;break}default:{let g=p}}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheKeysMissed:s,cacheKeysHit:a,uniqueKeysHit:c,cacheEntriesKeys:Object.values(n).map(p=>p.uniqueKey)},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:s,uniqueKeysHit:c}}function W0(r,e){return e?`${e}:${r}`:r}function $0(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 Am(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
39
|
+
${JSON.stringify(t)}`);let n=[];return n.push({key:W0(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Cc({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"&&Ku(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 Za(r,e,t){let n=r.cache&&"memory"in r.cache?r.cache.memory?.traces:void 0;AA(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 wm(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 wA(r,e){return r?AA(r.target.memory,e.target.memory)?{target:{...r.target,memory:e.target.memory},updatedAt:e.updatedAt}:r:{target:wm(e.target),updatedAt:e.updatedAt}}function Nt(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var wn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},Rn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},CA={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},xA={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};var Sde={CONTENT:"The page"};function MA(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 Rm(r){return`${r.negated?Rn.CONTAINS:wn.CONTAINS} '${r.value}'`}function _A(r){switch(r.type){case"CONTENT":return Rm(r);default:return r.type,""}}function q0(r){return typeof r=="object"&&r!==null}function lo(r){if(Array.isArray(r))return r.map(lo);if(q0(r)){let e={};return Object.entries(r).forEach(([t,n])=>{n!==void 0&&(e[t]=lo(n))}),e}return r}function K0(r){switch(r.type){case"AI_CHECK":return`AI check: ${r.assertion}`;case"TAP":return`Tap on element: ${Gd(r.target)}`;case"TYPE":return`Type ${r.text} ${r.target?`into ${Gd(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 ${_A(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 PA(r){switch(r.type){case"MOBILE_PRESET_STEP":return K0(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 IA}from"lodash-es";async function OA(r){let e={},{resolvedSteps:t,newSchemaVersion:n}=await xc({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 xc({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 xc({rawSteps:r,onFetchModule:e,logger:t,metadata:n,resolvedModuleCache:o={}}){let i=[];for(let a of r)i.push(await LA({rawStep:fr.parse(a),onFetchModule:e,logger:t,resolvedModuleCache:o}));return{resolvedSteps:i,newSchemaVersion:n.schemaVersion}}async function LA({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{...IA(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=fr.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=>LA({rawStep:u,onFetchModule:e,logger:t,resolvedModuleCache:n}))),l={...a,description:a.description||void 0,steps:c};return n[o]=IA(l),{...l,...r,type:"RESOLVED_MOBILE_MODULE"}}case"MOBILE_AI_ACTION_STEP":case"MOBILE_PRESET_STEP":return r}}import{cloneDeep as Y0}from"lodash-es";import{v4 as Cm}from"uuid";async function Cn(r){let e=new Map,t=new Set,n=Y0(r.steps),o=await NA({...r,steps:n,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:t});return{stepsToSave:o.stepsToSave,cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates}}async function NA({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?Cm():u.id,u.type){case"MOBILE_PRESET_STEP":{let d=u.command;d.id=c?Cm():d.id,"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Am({id:d.id,orgId:n.orgId,testId:n.testId,value:pn.parse(d),moduleIdParents:o,moduleStepParents:i}))),delete d.cache),l.stepsToSave.push({...u,command:d});break}case"RESOLVED_MOBILE_MODULE":{let d=c?Cm():u.id,p=u.moduleId;a.has(p)?p=a.get(p):s!==void 0&&(p=await s(u),a.set(u.moduleId,p));let{cachesToSave:g,stepsToSave:m,moduleUpdates:h}=await NA({...e,steps:u.steps,cacheCreationParams:n?{...n}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(h),l.cachesToSave=l.cachesToSave.concat(g),t.has(p)||(t.add(p),l.moduleUpdates.push({...$o.parse(u),steps:fr.array().parse(m),moduleId:p}));let f=ya.parse({...u,type:"MOBILE_MODULE_STEP",moduleId:p,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 X0(r){let e={parentChain:[]};return DA(r,e),e}function DA(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),DA({...r,steps:i.steps},e)&&o))return!0;e.parentChain.pop();continue}if(t(i,e)&&o)return!0}return!1}function J0(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 X0({steps:r,earlyStop:!0,onPreset:i,onModule:i}),{result:n,parentChain:o}}function kA({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!!J0([r],t,i).result}function UA(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 FA({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 gpe}from"lodash-es";import fpe from"truncate-json";import{v4 as Rpe}from"uuid";import{cloneDeep as ope,unset as ipe}from"lodash-es";import{cloneDeep as Ppe}from"lodash-es";import{diff as hme}from"deep-object-diff";import{diff as Kpe}from"deep-object-diff";import{cloneDeep as Xpe}from"lodash-es";import{v4 as dme}from"uuid";import{cloneDeep as Cge}from"lodash-es";import qme from"diff-lines";import Mm,{gte as Yme}from"semver";var BA={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 zA={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 Z0=["target","fromTarget","toTarget"];function HA(r){for(let e of Z0){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var GA={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 HA(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])HA(n);return e}default:return e}})};import{v4 as Q0}from"uuid";var VA={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=Q0()),e;default:return e}})};import{v4 as jA}from"uuid";var WA={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??jA(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??jA()}})),delete e.commands),e;default:return e}})};var $A={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 eU}from"uuid";var qA={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=eU()),e))};import{v4 as KA}from"uuid";var YA={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=KA())}return e.id=KA(),e})};var XA={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 tU}from"uuid";var JA={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=tU()),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 ZA={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 QA={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&&ew(t),e})};function ew(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){ew(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 tw={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 rw={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 nw={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 ow={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 iw={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 aw={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 Mc=new Set(["CLICK","TYPE","SELECT_OPTION"]),sw={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||Mc.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||Mc.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||Mc.has(l))&&(s.target={elementDescriptor:c??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(d=>{let p=d?.elementDescriptor,g=d?.type;(p!==void 0||Mc.has(g))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var lw={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 cw={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 _c=[aw,lw,cw,sw,BA,zA,GA,VA,WA,$A,qA,YA,XA,JA,ZA,QA,tw,rw,nw,ow,iw];if(ln!==_c[_c.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");_c.forEach((r,e)=>{if(!Mm.valid(r.toVersion)||!Mm.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Mm.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(_c[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});import{cloneDeep as Gge}from"lodash-es";import{stringify as ehe}from"yaml";async function X(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 _m({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 Qa({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 _m({promiseGenerator:r,signal:a.signal,codePath:t,logger:n})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function Pc(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 rU from"picomatch";var Ic=(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||rU(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},Oc=(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}},mi=r=>{try{return new URL(r),!0}catch{return!1}},uw=r=>!r.toLowerCase().startsWith("http"),gi=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function co(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 dw}from"uuid";function Pm(r,e){return{...r,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}var Lc=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:Pm({},this.metadata)}]).catch(s=>e.error({err:s},"Failed to report billable event"))]}trackStepExecution(e){if(by(e.type)){this.creditsUsedV2+=1;return}let t=Od(e.type);if(this.creditsUsedV1+=t??0,e.type==="PRESET_ACTION"){this.creditsUsedV2+=1;let n=Ld(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:dw(),properties:Pm({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:dw(),properties:Pm({creditsUsed:this.creditsUsedV2},this.metadata)}]).catch(t=>e.error({err:t},"Failed to report credits used"))),await Promise.allSettled(this.asyncWork)}};import{cloneDeep as Dhe}from"lodash-es";import{CookieJar as Rz}from"tough-cookie";var Im={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
|
|
40
40
|
var momenticConstants = {
|
|
41
41
|
bannedClassSubstrings: [
|
|
42
42
|
"relative",
|
|
@@ -1487,11 +1487,13 @@ function addEvaluateCssSelectorsScript() {
|
|
|
1487
1487
|
};
|
|
1488
1488
|
}
|
|
1489
1489
|
const boundingBox = bestElement.getBoundingClientRect();
|
|
1490
|
+
const textContent = bestElement.textContent;
|
|
1490
1491
|
return {
|
|
1491
1492
|
logs,
|
|
1492
1493
|
result: {
|
|
1493
1494
|
serializedElement: bestElementSerialized,
|
|
1494
1495
|
boundingBox,
|
|
1496
|
+
textContent,
|
|
1495
1497
|
dataMomenticId: bestElement.getAttribute("data-momentic-id") ?? void 0,
|
|
1496
1498
|
workingSelectors: bestElementSelectors,
|
|
1497
1499
|
mPath: visualFlagOn ? customWindow.getMPath?.(bestElement) : void 0
|
|
@@ -1560,6 +1562,13 @@ function addAddIdsScript() {
|
|
|
1560
1562
|
return;
|
|
1561
1563
|
}
|
|
1562
1564
|
customWindow.addIdsToElement = (rootElement, startIndex, stopIndex = Infinity) => {
|
|
1565
|
+
try {
|
|
1566
|
+
if (window && "FS" in window && window.FS) {
|
|
1567
|
+
window.FS("shutdown");
|
|
1568
|
+
}
|
|
1569
|
+
} catch (err) {
|
|
1570
|
+
console.error(\`[MOMENTIC] Failed to shutdown FullStory: \${err}\`);
|
|
1571
|
+
}
|
|
1563
1572
|
const stack = [rootElement];
|
|
1564
1573
|
let currentId = startIndex;
|
|
1565
1574
|
while (stack.length > 0) {
|
|
@@ -2641,11 +2650,13 @@ Element 2:\${secondBestSerialized}
|
|
|
2641
2650
|
};
|
|
2642
2651
|
}
|
|
2643
2652
|
const boundingBox = winner.getBoundingClientRect();
|
|
2653
|
+
const textContent = winner.textContent;
|
|
2644
2654
|
return {
|
|
2645
2655
|
logs,
|
|
2646
2656
|
result: {
|
|
2647
2657
|
serializedElement: winnerSerialized ?? "",
|
|
2648
2658
|
boundingBox,
|
|
2659
|
+
textContent,
|
|
2649
2660
|
dataMomenticId: winner.getAttribute("data-momentic-id") ?? void 0,
|
|
2650
2661
|
mPath: visualFlagOn ? customWindow.getMPath?.(winner) : void 0,
|
|
2651
2662
|
winnerStrength,
|
|
@@ -4130,35 +4141,46 @@ function registerAllMomenticListeners() {
|
|
|
4130
4141
|
|
|
4131
4142
|
// src/html/index.ts
|
|
4132
4143
|
registerAllMomenticListeners();
|
|
4133
|
-
`};var
|
|
4144
|
+
`};var lr={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-index","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["data-test-id","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-index","data-row-index","data-col-index","for","title","alt","aria-label","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"],bannedAiRequiredCacheAttributes:["id","data-momentic-id","href","name","x","y","width","height","aria-keyshortcuts","data-ved","aria-controls","d"],ineligibleElementAttribute:"momentic-ineligible"};var pw="BoundingBoxMovedError",mw="ZeroOpacityError",Nc="visual_actions",Zr="data-momentic-id";function gw(r,e,t){if(r.length<t)return r;let n=r.indexOf(e);if(n===-1)return r;let o=Math.max(0,n-t/3),i=Math.min(n+t/3,r.length),a=r.indexOf(`
|
|
4134
4145
|
`,o);a>0&&a<n&&(o=a);let s=i,c=0;for(;c<1e3&&s>n&&r[s]!==`
|
|
4135
4146
|
`;)c++,s--;return s>n&&r[s]===`
|
|
4136
|
-
`&&(i=s),r.slice(o,i)}function
|
|
4137
|
-
`,""),t=t.replaceAll(" ","");let n=
|
|
4138
|
-
`,";").replace(/\s+/g," ");let a="",s=await
|
|
4139
|
-
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let l=await e.boundingBox({timeout:Z});l?l.height===0?c="The element you attempted to interact with has zero height.":l.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new C("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new C("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function CU(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new C("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}import{execSync as LU}from"child_process";import{existsSync as ts,mkdirSync as Xp,readdirSync as NU,rmSync as Ew}from"fs";import{homedir as Tw}from"os";import{basename as DU,join as Pn,resolve as kU}from"path";import{chromium as vw}from"playwright-core";import{addExtra as UU}from"playwright-extra";import FU from"puppeteer-extra-plugin-recaptcha";function fw(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:s}of r)(!s||s.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as MU}from"crypto";function Sw(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function yw(r){let{route:e,mock:t,entry:n,onHarEntry:o,requestId:i,requestRecorders:a,logger:s}=r,c={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(p=>[p.name,p.value]),body:n.request.postData?.text}},l;if(t.fetchOriginalResponse){let p=await e.fetch();l={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let u=await xU(t,c,l),d={};u.headers.forEach((p,g)=>{d[g]=p});let m={body:await u.text(),contentType:u.headers.get("content-type")||"text/plain",headers:d,status:u.status};await e.fulfill(m);try{n.response={status:m.status,statusText:u.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body},_mocked:!0},o?.(i,n);for(let p of Object.values(a))p.onRequestComplete(i,n)}catch(p){p.message.includes("has been closed")||s.warn({err:p},"Failed to add response to HAR")}}async function xU(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function jp(r){try{await _U(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function _U(r){let{pageId:e,route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,mocks:s}=r,c=MU(),l=await Wp(e,n);try{o?.(c,l);for(let d of Object.values(a))d.onRequestStart(c,l)}catch(d){i.warn({err:d},"Failed to add request to HAR")}let u=Sw(n,s);u?await yw({logger:i,route:t,mock:u,entry:l,onHarEntry:o,requestId:c,requestRecorders:a}):await PU({route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,entry:l,requestId:c})}async function PU({route:r,request:e,onHarEntry:t,logger:n,requestRecorders:o,entry:i,requestId:a}){await r.continue();try{let s=await e.response(),c;try{await s?.finished()}catch{}try{c=await e.sizes()}catch{}if(i&&await pw(e,i,c),!s||!i)return;await dw(i,e,s,c),t?.(a,i);for(let l of Object.values(o))l.onRequestComplete(a,i)}catch(s){s.message.includes("has been closed")||n.warn({err:s},"Failed to add response to HAR")}}async function IU(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function OU(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Fc(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function $p(r){let e=r.request(),t=r.status(),n=r.headers(),o=await OU(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await IU(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var _n=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:Oc(t,this.requestMatcher.urlMatcher)}};function es(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}import{homedir as qp,platform as Kp}from"os";import{join as Yp}from"path";function Bc(){let r=[];if(Kp()==="linux"){let e=qp();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(Yp(e,".config",t,"Crash Reports"))})}else if(Kp()==="darwin"){let e=qp();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(Yp(e,"Library","Application Support",t,"Crashpad"))})}else if(Kp()==="win32"){let e=qp();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(Yp(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function bw(){return{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}}var Jp=Pn(Tw(),"momentic","chromium"),Aw=UU(vw);Aw.use(FU({provider:{id:"2captcha",token:gi},visualFeedback:!0}));var BU=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],zU=["--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],HU=["--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-webgl2","--disable-audio-input","--disable-audio-output"];async function ww({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,iconKnowledgeBase:a,callbacks:s,videoOptions:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let l;switch(o.browserType){case"Google Chrome":l="chrome";break;case"Chrome for Testing":l=void 0;break;case"Chromium":l="chromium";break;default:l="chromium";break}let u=[...zU];!Pr&&VU()&&u.push("--disable-dev-shm-usage");let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:l},m={...i??{},geolocation:i?.geolocation||$s,locale:i?.locale||Qf,timezoneId:i?.timezoneId||eS,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??kc,viewport:i?.viewport??un,serviceWorkers:"block",storageState:{cookies:[bw()],origins:[]},proxy:o.proxy};o.initialLocalStorage&&(m.storageState.origins=Object.entries(o.initialLocalStorage).map(([b,x])=>({origin:b,localStorage:Object.entries(x).map(([T,v])=>({name:T,value:v}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let p=null,g,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,isNewHeadless:!1};(l==="chrome"||l==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let b=Bc();b.forEach(x=>{if(!ts(x))return;["new","pending","completed"].forEach(v=>{let O=Pn(x,v);if(!ts(O))return;let w=NU(O);for(let D=0;D<w.length;D++){let j=Pn(O,w[D]);Ew(j,{force:!0})}})}),b.forEach(x=>{ts(x)||Xp(x,{recursive:!0});let T=Pn(x,`write-test-${Date.now()}`);Xp(T,{recursive:!0}),Ew(T,{recursive:!0,force:!0})}),u.push(...BU)}catch(b){e.warn({err:b},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...HU);let E=o.localChromeExtensionPaths?.map(b=>b.startsWith("~")?Pn(Tw(),b.slice(1)):b);if(E?.length){if(l===void 0)throw new C("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let v of E){let O=Pn(v,"manifest.json");if(!ts(O))throw new C("UserConfigurationError",`Chrome extension path ${O} does not exist.`)}if(Pr)throw new C("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=Pn(Jp,`momentic-session-${Date.now()}`);if(!ts(b))try{Xp(b,{recursive:!0})}catch(v){throw new C("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Jp} folder: ${v}`)}let x=[...u],T=E.map(v=>kU(v)).join(",");x.push(`--disable-extensions-except=${T}`),m?.deviceScaleFactor&&x.push(`--force-device-scale-factor=${m.deviceScaleFactor}`,`--device-scale-factor=${m.deviceScaleFactor}`),m.viewport&&x.push(`--window-size=${m.viewport.width},${m.viewport.height}`),g=await vw.launchPersistentContext(Pn(Jp,`momentic-session-${Date.now()}`),{...d,...m,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:r}),e.info({sharedContextOptions:m,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:x,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=g.pages()[0]}else{p=await Aw.launch({...d,args:u});let b={...m,baseURL:r,recordVideo:c?{dir:c.videoOutputPath}:void 0};g=await p.newContext(b),e.info({contextArgs:b,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await g.newPage()}if(c){let b=await h.video()?.path();if(b){let x=DU(b);c.onVideoPageChange({videoName:x})}}Pr&&await g.route("**",es);try{let b=p?.version();e.info({browserVersion:b},"Got browser version")}catch(b){e.warn({err:b},"Could not get browser version string")}return{browser:p,context:g,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:m.viewport||un,properties:f,clientCallbacks:s,iconKnowledgeBase:a,onVideoPageChange:c?.onVideoPageChange}}function GU(){if(process.platform!=="linux")return null;try{let e=LU("df -k /dev/shm",{encoding:"utf8"}).trim().split(/\r?\n/),n=e[e.length-1]?.trim().split(/\s+/)??[];if(!n||n.length<2)return null;let o=parseInt(n[1],10);return Number.isNaN(o)||o<=0?null:o/1024}catch{return null}}function VU(){let e=process.env.BROWSER_ENABLE_DEV_SHM;if(e==="1")return!1;if(e==="0")return!0;let t=GU();return t==null?!1:t<128}async function Rw(r){try{return await WU(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function WU({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:Q}),o=await lr(r,e,500),i=await r.boundingBox({timeout:Q});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:Q}),{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 p={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)},g=l._MOMENTIC_FEATURE_FLAGS?.[Dc],h=c.getAttribute(Zr),f=!g&&h?br(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,serializedForm:u.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:Q});if(a.type==="error")throw new Error(a.error);let s=r.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:Q}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var xw=["date","datetime-local","month","time","week"],Cw={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 Mw(r){try{await k(jU(r),{milliseconds:Z})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function jU({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await rt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:Q,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!Cw[i])return;Cw[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 Bt}from"zod";var _w=Bt.object({doubleClick:Bt.boolean().optional(),rightClick:Bt.boolean().optional(),force:Bt.boolean().optional(),waitForDownload:Bt.boolean().optional(),delayMs:Bt.number().optional(),downloadTimeoutMs:Bt.number().optional(),relativePosition:Bt.object({x:Bt.number(),y:Bt.number()}).optional()}),mye=Bt.object({repeat:Bt.number().optional(),convertMeta:Bt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Bt.number().optional()});async function zc({locator:r,callbacks:e,logger:t,timeoutMs:n=Q}){try{await Zp(e,n);let o=r.evaluate(i=>{let a=window;a.momenticIsEligible=d=>{let p=window.getComputedStyle(d,null).getPropertyValue("display");if(p==="none"||p==="contents")return!1;let g=d.getBoundingClientRect();return!(!g.height||!g.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let c=i.style.getPropertyValue("outline"),l=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let u=`momentic${Math.floor(Math.random()*1e7)}`;a[u]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",c,l),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[u](),a.removeHighlightFunctions?.[u]&&delete a.removeHighlightFunctions[u]},5e3)),a.removeHighlightFunctions[u]=a[u]},void 0,{timeout:n});return await 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 Zp(r,e=Q){let t=await r.state.getRoot();await rt({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 Qp(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return uo({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>Iw({...r,targetingResult:t,useVisualClick:e})})}async function YU(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await XU(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 XU(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:Q});if(!i)throw r;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:Q}),t.warn({err:r},"Attempting locator redirection due to input being covered by label"),Iw({...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 JU(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=_w.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await eF({targetingResult:t,position:n,options:o,logger:e});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 ZU(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 Rw({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();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:Z,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(rF(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..."),YU(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function Iw(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Pp;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof KU.TimeoutError?new C("ActionFailureError",`Download did not complete in ${u}ms`):new C("ActionFailureError",`Download failed: ${d.message}`)}})());try{await zc({locator:a.locator,callbacks:n,logger:t,timeoutMs:Q})}catch(u){t.warn({err:u},"Error highlighting locator in click, continuing...")}let c,l;if(i?c=await JU(r):l=(await ZU(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new C("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");t.info("Waiting for download to start and complete");let u=await k(s,{milliseconds:e.downloadTimeoutMs??Pp});if(u instanceof Error)throw u;return{downloadedFile:await tF(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 QU(r,e){let t=await r.locator.boundingBox({timeout:Z});if(!t){let i=await lr(r.locator,e,500);throw new C("ActionFailureError",`${rd}${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 eF({options:r,targetingResult:e,position:t,logger:n}){let o,i,a;if(r?.relativePosition){let u=await e.locator.boundingBox({timeout:Z}),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:Z});o=(u?.x??0)+t.x,i=(u?.y??0)+t.y,a="predefined position"}else{let[u,d]=await QU(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 tF(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Hp(r.suggestedFilename()),i=e();await r.saveAs(qU(i,o)),Pw(n,{force:!0}),setTimeout(()=>{Pw(i,{recursive:!0,force:!0})},5*60*1e3);let a=rw($U(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function rF(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as nF}from"os";var oF={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 iF(){let r=nF();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function Ow(r){return JSON.stringify(r.split("+").sort())}function Hc(r,e){let t=iF(),n=Ow(r);for(let o of Object.values(oF))if(Object.values(o).some(i=>Ow(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function eg({frame:r,page:e,deltaX:t,directionX:n,deltaY:o,directionY:i,signal:a,callbacks:s,logger:c}){if(!t&&!o)return;let l=n==="left"?-1:1,u=i==="up"?-1:1;if(r)await rt({root:r,fn:([d,m,p,g])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:Se,codePath:"scrolling page"});else{let d=e.viewportSize()||un,m=await rt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:Se,codePath:"computing page height"}),[p,g,h]=await rt({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:Se,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<Se;){a?.throwIfAborted();let E=await k(e.evaluate(()=>document.body.scrollHeight),{milliseconds:Q}),[b,x,T]=await k(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let O=v.getBoundingClientRect();return[v.scrollTop,O.x,O.y]}),{milliseconds:Q});if(E===m&&b===p&&x===g&&T===h)break;m=E,p=b,g=x,h=T,await X(at)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function tg(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),await Promise.all(t.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){n=i,await X(at)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as pF}from"crypto";import{cloneDeep as og}from"lodash-es";function In(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as aF}from"crypto";var sF="v1";function rg(r,e){if(r.tagName.toLowerCase()==="svg"&&!cF(r))try{let t=Lw(r,e),n=lF(JSON.stringify(t));return{version:sF,json:t,hash:n}}catch{return}}function lF(r){return aF("md5").update(r).digest("hex")}function Lw(r,e){let t=r.tagName.toLowerCase(),n=uF(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=Lw(a,e);s&&o.children.push(s)}}return o}function cF(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function uF(r){let e={},t=r.attributes;for(let n of Object.keys(t))sr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var mo={r:147,g:196,b:125,a:.55},Dw={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:mo,paddingColor:mo,borderColor:mo,marginColor:mo,eventTargetColor:mo,shapeColor:mo,shapeMarginColor:mo,showInfo:!0,showAccessibilityInfo:!0};function kw({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=dF({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function dF({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,D)=>{u[w]=D});let d=l.styles,m=l.bounds??[],p=c.nodes,g=p.contentDocumentIndex??{index:[],value:[]},h=p.backendNodeId??[],f=p.attributes??[],E=p.parentIndex??[],b=p.nodeName??[],x=p.nodeType??[],T=p.pseudoType??{index:[],value:[]},v=p.inputChecked??{index:[]},O=e[c.frameId];for(let w=0;w<h.length;w++){let D=h[w],j=x[w],ie=f[w]??[],ee=E[w]!==void 0&&E[w]>=0?E[w]:void 0,fe=ee!==void 0?h[ee]:void 0,st=fe!==void 0?a[fe]:void 0,$=T.index.indexOf(w),B=$!==-1?e[T.value[$]]:void 0,ae=u[w],ue;ae?ue=m[ae]??[]:ue=[];let Ze=b[w]!==void 0?e[b[w]]?.toLowerCase():void 0;if(!Ze){s.warn({backendNodeId:D,frameId:O,frameIndex:o,nodeBounds:ue},"DOM node has no tag name");continue}let Ce={backendNodeId:D,psuedoType:B,nodeType:j,frameIndex:o,parentFrameId:O,ownedFrameId:void 0,bounds:{x:ue[0]??null,y:ue[1]??null,width:ue[2]??null,height:ue[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:fe??null,tagName:Ze,parent:st??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};st&&st.childrenBackendIds.push(D);let zt=g.index.indexOf(w);if(zt!==-1){let Ie=g.value[zt];i[Ie]=Ce;let qe=r[Ie]?.frameId;Ce.ownedFrameId=qe!==void 0?e[qe]:void 0}for(let Ie of Object.keys(Ce.bounds)){let qe=Ie;Ce.bounds[qe]!==null&&(Ce.bounds[qe]/=n)}let bt=ae!==void 0?d[ae]??[]:[];for(let Ie=0;Ie<bt.length&&!(Ie>=t.length);Ie++){let qe=bt[Ie];if(qe===void 0||isNaN(qe))continue;let mr=e[qe];if(mr===void 0)continue;let xt=t[Ie];Ce.computedStyles[xt]=mr}for(let Ie=0;Ie<ie.length;Ie+=2){let qe=ie[Ie],mr=ie[Ie+1];if(!qe||!mr)continue;let xt=e[qe],Vr=e[mr];!xt||!Vr||(Ce.attributes[xt]=Vr)}v.index.includes(w)&&(Ce.attributes.checked="true"),a[Ce.backendNodeId]=Ce}return a[h[0]]}function ng(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=`${ng(t,e)}${a}`}return r.mPathSelector=n,n}function Nw(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var mF=["html","#document","#document-fragment"];function Uw({node:r,domGraph:e}){let t=[],n=r,o=Nw(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=Nw(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++,mF.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 Fw(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 Bw(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:Se});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:Se}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:Se})).attributes,i=In(o,Zr);if(!i)throw new Error(`Could not find attribute ${Zr} for object ${e}`);return i}var gF=["focusable","keyshortcuts","controls","live","relevant","orientation"],hF=["selected","readonly","modal","required","invalid"],fF=["id","name","role","content"],zw=["absolute","fixed","sticky"],SF=["i","label"],yF=["path"],bF=["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"],Vw=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Ww=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],EF=["menulistpopup","statictext","inlinetextbox"],TF=80,Hw=100,jw=50,sg=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],vF=["cite"],AF={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"]},wF={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Gw={indentLevel:0},ig=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<jw?t:""),this.role=this.role||(e.domNode.attributes.role??""),MF(this.properties,e.domNode,e.importantProperties)}PF(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&&yF.includes(this.domNode.tagName)||this.ignoredReasons.some(n=>Ww.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>Xw(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>Jw(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&&SF.includes(this.domNode.tagName)||bF.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||sr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>Yw(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=Gw){let t=Object.assign({},Gw,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=og(this.properties),u=" ".repeat(n),d=this.role||"",m=this.tagName??"unknown",p=this.name;d==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===p&&(p="")}let f=sg.includes(this.role)||vF.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${p}
|
|
4140
|
-
|
|
4141
|
-
|
|
4142
|
-
|
|
4147
|
+
`&&(i=s),r.slice(o,i)}function yr(r){let e=typeof r=="string"?r:r.toString();return`[${Zr}="${e}"]`}import{execSync as YF}from"child_process";import{randomUUID as gg}from"crypto";import{diff as hg}from"deep-object-diff";import{existsSync as $c,readFileSync as XF,readdirSync as JF,statSync as MR,writeFileSync as ZF}from"fs";import{Jimp as _R}from"jimp";import QF from"js-beautify";import{cloneDeep as Ei}from"lodash-es";import eB from"mime";import{platform as tB}from"os";import{basename as PR,extname as rB,join as nB}from"path";import{v4 as oB}from"uuid";import{rmSync as Xw}from"fs";import{basename as ZU,join as QU}from"path";import{errors as eF}from"playwright-core";import{devices as oU}from"playwright-core";var hw=2,hi=8e3;var fi=250,lt=500;var fw=5e3,Sw=250,Q=3e3,he=2e3,te=1e3,Om=3e4,Lm=8e3,yw=10,Nm=.05;var bw=6e4,Ew=new Set(["about:blank","chrome-error://chromewebdata/"]);var Dm=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],km=1e4,es=500,Dc=oU["Desktop Chrome"].userAgent,Si=process.env.TWO_CAPTCHA_KEY;import{mkdirSync as iU,rmSync as Tw,statSync as aU}from"fs";import*as zm from"node:fs";import sU from"nodejs-file-downloader";import{tmpdir as lU}from"os";import xn,{basename as cU,dirname as uU}from"path";var Hm="file://",Bm=xn.join(lU(),"momentic","downloads"),Fm=1e4,dU=50*1024*1024;async function vw(r){let{uri:e}=r;if(e.startsWith(Hm))return mU(r);if(e.startsWith("http"))return hU(r);if(Ny)return gU(r);throw new x("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'")}function pU(r,e){let t=xn.join(Bm,r,e.slice(Hm.length)),n=xn.join(Bm,r),o=t.startsWith(n);if(!zm.existsSync(t)||!o)throw new x("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return t}async function mU({uri:r,orgId:e}){let t=pU(e,r);return{filePath:t,cleanup:()=>{Tw(uU(t),{recursive:!0,force:!0})}}}async function gU({uri:r}){let e=xn.resolve(r);if(!zm.existsSync(e))throw new x("UserConfigurationError",`The referenced file (${r}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function hU({uri:r,logger:e,orgId:t}){let n=new URL(r);n.search&&(n.search="");let o=cU(n.href),i=Vm(o),a=xn.extname(i);if(My.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let s=Gm(t),c,l;for(let m=1;m<=3;m++){let h=new sU({url:r,fileName:i,directory:s,maxAttempts:1,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:Fm});try{let{downloadStatus:f,filePath:E}=await k(h.download(),{milliseconds:Fm,message:`Download timed out after ${Fm}ms`});if(f!=="COMPLETE"||!E)throw new Error(`Download ended in non-success status: ${f}`);c=E;break}catch(f){l=f}}if(!c)throw new Error(`Download failed after 3 attempts. Last error: ${l instanceof Error?l.message:l}`);let u=c,p=aU(u).size;if(p>dU)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:i},"Downloaded file to disk");let g;return{filePath:u,cleanup:()=>{clearTimeout(g),g=setTimeout(()=>Tw(s,{recursive:!0,force:!0}),10*60*1e3)}}}function Aw(r,e){return`${Hm}${r}/${e}`}function Gm(r){let e=Math.random().toString(36).substring(4),t=xn.join(Bm,r,e);return iU(t,{recursive:!0}),t}function Vm(r){let e=xn.extname(r),t=xn.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function br(r,e,t){try{return await r.evaluate((o,{truncateToLength:i})=>window.serializeElementOnlyWithText?.(o,{truncateToLength:i}),{truncateToLength:t},{timeout:te})}catch(n){e.debug({err:n},"Failed to get HTML from locator for Playwright error translation");return}}var Mn=3.1783027;function fU(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Er(r){return Math.ceil(jm(r)/Mn)}function jm(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
4148
|
+
`,""),t=t.replaceAll(" ","");let n=fU(t);return t.length-n+Mn*n}if(typeof r>"u"||r===null)return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=jm(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*Mn:e+=85*Mn:n==="source"&&typeof t[n]=="object"&&t[n]?.type==="base64"?e+=1600*Mn:e+=jm(t[n])}),e}if(typeof r=="boolean")return r?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var kc=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>n-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let n=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(n),!1)}};async function ww(r,e){let t=r.evaluate(async()=>{let i=window,a={};try{let s=await indexedDB.databases();for(let c of s){if(!c.name)continue;let l=await i.exportIdbToObject?.(c.name,c.version);l&&(a[c.name]=l)}return[a,void 0]}catch(s){return[void 0,s.message]}}),[n,o]=await k(t,{milliseconds:Q});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),n}async function Rw(r,e,t){if(e){t.debug("Importing indexedDB data");try{let n=r.evaluate(async o=>{let i=window;for(let[a,s]of Object.entries(o))await i.importObjectToIdb?.(a,s)},e);await k(n,{milliseconds:Q})}catch(n){t.warn({err:n},"Failed to import indexedDB data")}}}async function Cw(r,e){try{let t=r.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(n=>{n.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await k(t,{milliseconds:Q})}catch(t){e.debug({err:t},"Failed clearing index db data, continuing...")}}async function xw(r,e,t,n,o){try{await SU(r,e,t,n)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function SU(r,e,t,n){let o=n.text();o.length>es&&(o=o.slice(0,es)+"...(TRUNCATED)");let i=[];for(let a of n.args())try{let s=await a.jsonValue(),c=JSON.stringify(s);c.length>es?i.push(c.slice(0,es)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&i.push(s)}catch{}Wm(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:i})}function Wm(r,e,t,n){let o=Date.now(),i=e.logsPerPage;if(i.length<=t||i[t]===void 0){i[t]=[];for(let a=0;a<t;a++)i[a]===void 0&&(i[a]=[])}i[t].length>km&&(i[t]=i[t].slice(Math.floor(km/2)),i[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),i[t].push({...n,tabIndex:t,timestamp:o})}async function cr({fn:r,codePath:e,logObject:t,signal:n,logger:o}){n?.throwIfAborted();let i=Date.now(),a=await _m({promiseGenerator:r,signal:n,codePath:e,logger:o}),s=Date.now();return t[e]=s-i,a}import yU from"truncate-json";var bU="[redacted due to size]",EU=5e3,TU=1e6,_w=1e3;function Pw(r,e,t,n){try{t?.({id:e,startedDateTime:new Date().toISOString(),title:void 0,pageTimings:{}})}catch(o){r.warn({err:o},"Unexpected error in onHarPage callback")}}async function $m(r,e){let t=e.timing(),n=new URL(e.url()),o=[...n.searchParams.entries()].map(([s,c])=>({name:s,value:c})),i={...await Ow(e),url:n.toString(),method:e.method(),queryString:o};return{pageref:r,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:Lw(t).timings}}async function Iw(r,e,t,n,o){let i={},s=((await t.headerValue("content-type"))?.toLowerCase()??void 0)?.split(";")[0]??void 0;if(n)try{i=await MU({response:t,mimeType:s,sizes:n,neverRedact:o})}catch{}let c={...await Ow(t),status:t.status(),statusText:t.statusText(),content:i,redirectURL:t.headers().location,_mocked:!1};r.response=c,r.response&&n&&(r.response.bodySize=n.responseBodySize,r.response.headersSize=n.responseHeadersSize,r.response.content.size=n.responseBodySize);let l=e.timing();r.startedDateTime=new Date(l.startTime).toISOString();let{timings:u,total:d}=Lw(l);r.time=d,r.timings=u}function Mw(r){try{return new Date(r).toISOString()}catch{return}}function vU(r){let e={name:"",value:""},t=!0;for(let n of r.split(/; */)){let o=n.indexOf("="),i=o!==-1?n.substring(0,o).trim():n.trim(),a=o!==-1?n.substring(o+1,n.length).trim():"";if(t){t=!1,e.name=Fr(i,!1),e.value=Fr(a,!1);continue}i==="Domain"&&(e.domain=Fr(a,!1)),i==="Expires"&&(e.expires=Mw(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=Mw(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Fr(a,!1)),i==="Secure"&&(e.secure=!0)}return e}async function Ow(r){let e=await r.allHeaders(),t=e.cookie?.split(";").map(vU)??[];return{headers:Object.entries(e).map(([n,o])=>({name:Fr(n,!1),value:Fr(o,!1)})),cookies:t}}async function Uc(r,e,t,n){let o=await r.headerValue("content-type")??"application/octet-stream";if(t&&(e.request.bodySize=t.requestBodySize,e.request.headersSize=t.requestHeadersSize),!n&&t&&t.requestBodySize>_w){e.request.postData={mimeType:o,text:"",params:[],_redactedReason:"Request body redacted due to size"};return}let i=r.postData();if(!i)return;let a={mimeType:o,text:Fr(i,n),params:[]};if(o==="application/x-www-form-urlencoded"){let s=new URLSearchParams(i.toString());for(let[c,l]of s.entries())a.params.push({name:Fr(c,n),value:l?Fr(l,n):void 0})}e.request.postData=a}var AU=["image","font","video","audio"],wU=["javascript"],RU=["text"],CU=["json","xml","html"];function xU(r){let[e,t]=r.split("/");return e&&AU.includes(e)||t&&wU.some(n=>t.includes(n))?!1:!!(e&&RU.includes(e)||t&&CU.some(n=>t.includes(n)))}async function MU({response:r,mimeType:e,sizes:t,neverRedact:n}){let o={mimeType:e,encoding:await r.headerValue("content-encoding")??void 0};return!n&&(!e||!xU(e))?o._redactedReason="Body redacted because it's not a viewable MIME type":!n&&t.responseBodySize>=_w?o._redactedReason="Response body redacted due to size":o.text=Fr(await r.text(),n),o}function Fr(r,e){let t=e?TU:EU;try{let n=JSON.parse(r),{jsonString:o}=yU(r,t);return o}catch{return r.length>t?r.slice(0,t)+bU:r}}function uo(r){return r<0?0:r}function Lw(r){return{timings:{blocked:uo(r.domainLookupStart),dns:uo(r.domainLookupEnd-r.domainLookupStart),connect:uo(r.connectEnd-r.connectStart),send:uo(r.responseStart-r.requestStart),wait:0,receive:uo(r.responseEnd-r.responseStart),ssl:uo(r.connectEnd-r.secureConnectionStart)},total:uo(r.responseEnd)}}function Nw(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o}=n||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${t}`:t)(o))}}}async function nt({root:r,fn:e,arg:t,timeout:n,waitForPageLoad:o,codePath:i}){return await o(),await k(r.evaluate(e,t),{milliseconds:n,message:`Timed out ${i} after ${n}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}import{errors as _U}from"playwright-core";async function po({func:r,action:e,logger:t,callbacks:n,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),s;for(;Date.now()-a<o;)try{return await r(i)}catch(c){if(c instanceof _U.TimeoutError)t.warn({err:c,rootUrl:(await n.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await PU(c,i.locator,n,t);else throw c}throw s instanceof x?s:new x("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function PU(r,e,t,n){return r.message.includes("attempt #")?IU(r,e,t,n):OU(r)}async function IU(r,e,t,n){let o=r.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return n.warn({err:r},"Failed to parse Playwright error message for translation, returning raw message"),r;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
|
|
4149
|
+
`,";").replace(/\s+/g," ");let a="",s=await br(e,n,150);if(s&&(a=`Target element HTML: ${Nt(s,100,!0)}`),i.includes("element is not enabled"))return new x("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}});if(i.includes("intercepts pointer events")){let c="",l=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(l){let u=(await t.state.getRoot()).locator(yr(l)),d=await br(u,n,150);d&&(c=`Covering element HTML: ${Nt(d,100,!0)}`)}return new x("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
|
|
4150
|
+
${c}`,{errOptions:{cause:r}})}if(i.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let l=await e.boundingBox({timeout:Q});l?l.height===0?c="The element you attempted to interact with has zero height.":l.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new x("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:r}})}return i.includes("element is outside of the viewport")?new x("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):r}function OU(r){let e=r.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new x("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:r}});return r}import{execSync as BU}from"child_process";import Bw from"dedent";import{existsSync as rs,mkdirSync as Zm,readdirSync as zU,rmSync as zw}from"fs";import{homedir as Hw}from"os";import{basename as HU,join as Pn,resolve as GU}from"path";import{chromium as Gw}from"playwright-core";import{addExtra as VU}from"playwright-extra";import jU from"puppeteer-extra-plugin-recaptcha";function Dw(r,e){return async(t,n)=>{try{let o=await n.allHeaders();for(let{key:i,value:a,matcher:s}of r)(!s||s.matches({url:n.url(),method:n.method()}))&&(o[i]=a);await t.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as NU}from"crypto";function kw(r,e){for(let t of Object.values(e))if(t.matcher.matches({url:r.url(),method:r.method()}))return t}async function Uw(r){let{route:e,mock:t,entry:n,onHarEntry:o,request:i,requestId:a,requestRecorders:s,logger:c}=r;await Uc(i,n,void 0,!0);let l={url:n.request.url,options:{method:n.request.method,headers:n.request.headers.map(m=>[m.name,m.value]),body:n.request.postData?.text}},u;if(t.fetchOriginalResponse){let m=await e.fetch();u={body:await m.text(),options:{status:m.status(),statusText:m.statusText(),headers:Object.entries(await m.headers())}}}let d=await LU(t,l,u),p={};d.headers.forEach((m,h)=>{p[h]=m});let g={body:await d.text(),contentType:d.headers.get("content-type")||"text/plain",headers:p,status:d.status};await e.fulfill(g);try{n.response={status:g.status,statusText:d.statusText,headers:Object.entries(g.headers).map(([m,h])=>({name:m,value:h})),cookies:[],content:{mimeType:g.contentType,text:g.body},_mocked:!0},o?.(a,n);for(let m of Object.values(s))m.matches(n)&&m.onRequestComplete(a,n)}catch(m){m.message.includes("has been closed")||c.warn({err:m},"Failed to add response to HAR")}}async function LU(r,e,t){try{return await r.generateResponse(e,t)}catch(n){let o=n instanceof Error?n.message:`${n}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function qm(r){try{await DU(r)}catch(e){r.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function DU(r){let{pageId:e,route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,mocks:s}=r,c=NU(),l=!1,u=await $m(e,n);try{o?.(c,u);for(let p of Object.values(a))p.matches(u)&&(l=!0,p.onRequestStart(c,u))}catch(p){i.warn({err:p},"Failed to add request to HAR")}let d=kw(n,s);d?await Uw({logger:i,route:t,mock:d,entry:u,onHarEntry:o,request:n,requestId:c,requestRecorders:a}):await kU({route:t,request:n,onHarEntry:o,logger:i,requestRecorders:a,entry:u,requestId:c,neverRedact:l})}async function kU({route:r,request:e,onHarEntry:t,logger:n,requestRecorders:o,entry:i,requestId:a,neverRedact:s}){await r.continue();try{let c=await e.response(),l;try{await c?.finished()}catch{}try{l=await e.sizes()}catch{}if(i&&await Uc(e,i,l,s),!c||!i)return;await Iw(i,e,c,l,s),t?.(a,i);for(let u of Object.values(o))u.matches(i)&&u.onRequestComplete(a,i)}catch(c){c.message.includes("has been closed")||n.warn({err:c},"Failed to add response to HAR")}}async function UU(r){let e=r.postData();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:r.postDataJSON()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function FU(r){let e=await r.text();if(e){if((await r.headerValue("content-type"))?.includes("json"))try{return{json:await r.json()}}catch{return{}}else if((await r.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Fc(r){return{request:{url:r.request.url,method:r.request.method,headers:r.request.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.request.postData?r.request.postData.mimeType.includes("json")?{json:JSON.parse(r.request.postData.text)}:{text:r.request.postData.text}:{}},response:r.response?{status:r.response.status,headers:r.response.headers.reduce((e,t)=>({...e,[t.name]:t.value}),{}),...r.response.content?r.response.content.mimeType?.includes("json")&&r.response.content.text?{json:JSON.parse(r.response.content.text)}:{text:r.response.content.text}:{}}:void 0}}async function Km(r){let e=r.request(),t=r.status(),n=r.headers(),o=await FU(r);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await UU(e)},response:{status:t,headers:n,...o},status:t,headers:n,...o}}var _n=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:t,method:n}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==n.toLowerCase()?!1:Ic(t,this.requestMatcher.urlMatcher)}};function ts(r){let e=new URL(r.request().url());return/^127\./.test(e.hostname)||/^192\.168\./.test(e.hostname)||/^10\./.test(e.hostname)||/^172\.(1[6-9]|2\d|3[0-1])\./.test(e.hostname)||e.hostname==="localhost"?r.abort():r.fallback()}import{homedir as Ym,platform as Xm}from"os";import{join as Jm}from"path";function Bc(){let r=[];if(Xm()==="linux"){let e=Ym();["chromium","google-chrome","chrome-canary"].forEach(t=>{r.push(Jm(e,".config",t,"Crash Reports"))})}else if(Xm()==="darwin"){let e=Ym();["Chromium","Google","Chrome for Testing"].forEach(t=>{r.push(Jm(e,"Library","Application Support",t,"Crashpad"))})}else if(Xm()==="win32"){let e=Ym();["Chromium","Google","Google Chrome Canary"].forEach(t=>{r.push(Jm(e,"AppData","Local",t,"User Data","Crashpad","reports"))})}return r}function Fw(){return[{name:"fs_optout",value:"1",domain:".fullstory.com",path:"/",expires:Date.now()/1e3+365*24*60*60,httpOnly:!1,secure:!0,sameSite:"None"}]}var Qm=Pn(Hw(),"momentic","chromium"),Vw=VU(Gw);Vw.use(jU({provider:{id:"2captcha",token:Si},visualFeedback:!0}));var WU=["--enable-crashpad","--crash-on-hang-threads=UI:18,IO:18"],$U=["--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream","--enable-logging=stderr","--log-level=2"],qU=["--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-webgl2","--disable-audio-input","--disable-audio-output"];async function jw({baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,contextArgs:i,iconKnowledgeBase:a,callbacks:s,videoOptions:c}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let l;switch(o.browserType){case"Google Chrome":l="chrome";break;case"Chrome for Testing":l=void 0;break;case"Chromium":l="chromium";break;default:l="chromium";break}let u=[...$U];!Pr&&YU()&&u.push("--disable-dev-shm-usage");let d={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:l},p={...i??{},geolocation:i?.geolocation||$s,locale:i?.locale||TS,timezoneId:i?.timezoneId||vS,colorScheme:i?.colorScheme,httpCredentials:o.basicAuthorization?{username:o.basicAuthorization.username??"",password:o.basicAuthorization.password??""}:void 0,javaScriptEnabled:o.disableJavaScript?!1:void 0,ignoreHTTPSErrors:o.ignoreHttpsErrors??!1,userAgent:o.userAgent??Dc,viewport:i?.viewport??un,serviceWorkers:"block",storageState:{cookies:[...Fw()],origins:[]},proxy:o.proxy};o.initialLocalStorage&&(p.storageState.origins=Object.entries(o.initialLocalStorage).map(([b,R])=>({origin:b,localStorage:Object.entries(R).map(([A,T])=>({name:A,value:T}))}))),process.env.MOMENTIC_CHROME_EXTRA_ARGS&&u.push(...process.env.MOMENTIC_CHROME_EXTRA_ARGS.split(","));let g=null,m,h,f={systemDevicePixelRatio:i?.deviceScaleFactor,isNewHeadless:!1};(l==="chrome"||l==="chromium")&&(f.isNewHeadless=!0,d.headless&&u.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&u.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`);try{let b=Bc();b.forEach(R=>{if(!rs(R))return;["new","pending","completed"].forEach(T=>{let _=Pn(R,T);if(!rs(_))return;let w=zU(_);for(let D=0;D<w.length;D++){let G=Pn(_,w[D]);zw(G,{force:!0})}})}),b.forEach(R=>{rs(R)||Zm(R,{recursive:!0});let A=Pn(R,`write-test-${Date.now()}`);Zm(A,{recursive:!0}),zw(A,{recursive:!0,force:!0})}),u.push(...WU)}catch(b){e.warn({err:b},"Could not create Chrome crash report directory, not enabling crashpad")}o.disableGpu&&u.push(...qU);let E=o.localChromeExtensionPaths?.map(b=>b.startsWith("~")?Pn(Hw(),b.slice(1)):b);if(E?.length){if(l===void 0)throw new x("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let T of E){let _=Pn(T,"manifest.json");if(!rs(_))throw new x("UserConfigurationError",`Chrome extension path ${_} does not exist.`)}if(Pr)throw new x("UserConfigurationError","Cannot use persistent browser context on Momentic Cloud");let b=Pn(Qm,`momentic-session-${Date.now()}`);if(!rs(b))try{Zm(b,{recursive:!0})}catch(T){throw new x("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Qm} folder: ${T}`)}let R=[...u],A=E.map(T=>GU(T)).join(",");R.push(`--disable-extensions-except=${A}`),p?.deviceScaleFactor&&R.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&R.push(`--window-size=${p.viewport.width},${p.viewport.height}`),m=await Gw.launchPersistentContext(Pn(Qm,`momentic-session-${Date.now()}`),{...d,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:R,baseURL:r}),e.info({sharedContextOptions:p,sharedBrowserOptions:d,userBrowserSettings:o,chromeArgs:R,properties:f,baseUrl:r},"Browser initialization context args (persistent)"),h=m.pages()[0]}else{g=await Vw.launch({...d,args:u});let b={...p,baseURL:r,recordVideo:c?{dir:c.videoOutputPath}:void 0};m=await g.newContext(b),e.info({contextArgs:b,sharedBrowserOptions:d,chromeArgs:u,userBrowserSettings:o,properties:f,baseUrl:r},"Browser initialization context args (standard)"),h=await m.newPage()}if(c){let b=await h.video()?.path();if(b){let R=HU(b);c.onVideoPageChange({videoName:R})}}Pr&&await m.route("**",ts);try{let b=g?.version();e.info({browserVersion:b},"Got browser version")}catch(b){e.warn({err:b},"Could not get browser version string")}return{browser:g,context:m,page:h,baseUrl:r,logger:e,storage:t,enricher:n,userBrowserSettings:o,viewport:p.viewport||un,properties:f,clientCallbacks:s,iconKnowledgeBase:a,onVideoPageChange:c?.onVideoPageChange}}function KU(){if(process.platform!=="linux")return null;try{let e=BU("df -k /dev/shm",{encoding:"utf8"}).trim().split(/\r?\n/),n=e[e.length-1]?.trim().split(/\s+/)??[];if(!n||n.length<2)return null;let o=parseInt(n[1],10);return Number.isNaN(o)||o<=0?null:o/1024}catch{return null}}function YU(){let e=process.env.BROWSER_ENABLE_DEV_SHM;if(e==="1")return!1;if(e==="0")return!0;let t=KU();return t==null?!1:t<128}function eg(r,e=!1){let t=Bw`window._MOMENTIC_BROWSER = true;
|
|
4151
|
+
window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(r)};
|
|
4152
|
+
window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`;return e&&(t+=Bw`
|
|
4153
|
+
window._fs_namespace = window._fs_namespace || 'FS';
|
|
4154
|
+
function FSNoop() {}
|
|
4155
|
+
FSNoop.q = [];
|
|
4156
|
+
Object.defineProperty(window, window._fs_namespace, {
|
|
4157
|
+
value: FSNoop,
|
|
4158
|
+
writable: false,
|
|
4159
|
+
configurable: false,
|
|
4160
|
+
});`),t}async function Ww(r){try{return await XU(r)}catch(e){r.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function XU({locator:r,logger:e}){let[t,n]=await r.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:te}),o=await br(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(),p=u.getBoundingClientRect();if(p.width===0||p.height===0)return{type:"error",error:"Parent element has no width or height"};let g={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)},m=l._MOMENTIC_FEATURE_FLAGS?.[Nc],h=c.getAttribute(Zr),f=!m&&h?yr(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 qw=["date","datetime-local","month","time","week"],$w={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 Kw(r){try{await k(JU(r),{milliseconds:Q})}catch(e){r.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function JU({root:r,text:e,options:t,logger:n,callbacks:o}){let i=(await nt({root:r,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:te,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!$w[i])return;$w[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 zt}from"zod";var Yw=zt.object({doubleClick:zt.boolean().optional(),rightClick:zt.boolean().optional(),force:zt.boolean().optional(),waitForDownload:zt.boolean().optional(),delayMs:zt.number().optional(),downloadTimeoutMs:zt.number().optional(),relativePosition:zt.object({x:zt.number(),y:zt.number()}).optional()}),Aye=zt.object({repeat:zt.number().optional(),convertMeta:zt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:zt.number().optional()});async function zc({locator:r,callbacks:e,logger:t,timeoutMs:n=te}){try{await tg(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 m=d.getBoundingClientRect();return!(!m.height||!m.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 tg(r,e=te){let t=await r.state.getRoot();await nt({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 rg(r){let e=!!r.browserCallbacks.state.userBrowserSettings.visualActions;return po({action:"clicking element",targetingResult:r.targetingResult,logger:r.logger,retryTimeoutMs:r.retryTimeoutMs,callbacks:r.browserCallbacks,func:async t=>Jw({...r,targetingResult:t,useVisualClick:e})})}async function tF(r,e){let{redirectionAttempts:t=0}=e;if(t>=2)throw r;try{return await rF(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 rF(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"),Jw({...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 nF(r){let{logger:e,targetingResult:t,position:n,options:o}=r,i=Yw.safeParse(o),a=Date.now(),{clickX:s,clickY:c,reason:l}=await aF({targetingResult:t,position:n,options:o,logger:e});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 oF(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 Ww({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();try{o.info({locator:c},"Locator click"),n?.doubleClick?await i.dblclick({button:n.rightClick?"right":"left",timeout:Q,position:a,delay:n?.delayMs??25,force:s}):await i.click({button:n?.rightClick?"right":"left",timeout:Q,position:a,delay:n?.delayMs??25,force:s})}catch(l){let u=l;if(lF(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..."),tF(u,{...r,targetingResult:{...i,locator:i}})}return{locatorSource:c}}async function Jw(r){let{options:e,logger:t,browserCallbacks:n,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=r,s;e?.waitForDownload&&(s=(async()=>{let u=e.downloadTimeoutMs??Om;try{return await a.locator.page().waitForEvent("download",{timeout:u})}catch(d){return d instanceof eF.TimeoutError?new x("ActionFailureError",`Download did not complete in ${u}ms`):new x("ActionFailureError",`Download failed: ${d.message}`)}})());try{await zc({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 nF(r):l=(await oF(r)).locatorSource,e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new x("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??Om});if(u instanceof Error)throw u;return{downloadedFile:await sF(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 iF(r,e){let t=await r.locator.boundingBox({timeout:Q});if(!t){let i=await br(r.locator,e,500);throw new x("ActionFailureError",`${rd}${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 aF({options:r,targetingResult:e,position:t,logger:n}){let o,i,a;if(r?.relativePosition){let u=await e.locator.boundingBox({timeout:Q}),d=r.relativePosition.x,p=r.relativePosition.y;u?.width&&(d=Math.max(0,Math.min(r.relativePosition.x,u.width))),u?.height&&(p=Math.max(0,Math.min(r.relativePosition.y,u.height))),o=(u?.x??0)+d,i=(u?.y??0)+p,a="relative position from user"}else if(t){let u=await e.locator.boundingBox({timeout:Q});o=(u?.x??0)+t.x,i=(u?.y??0)+t.y,a="predefined position"}else{let[u,d]=await iF(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 sF(r,e,t){t.info("Download detected, saving file to disk");let n=await r.path(),o=Vm(r.suggestedFilename()),i=e();await r.saveAs(QU(i,o)),Xw(n,{force:!0}),setTimeout(()=>{Xw(i,{recursive:!0,force:!0})},5*60*1e3);let a=Aw(ZU(i),o);return t.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function lF(r){return r.message.includes("locator.click: Timeout")&&r.message.includes("click action done")}import{platform as cF}from"os";var uF={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 dF(){let r=cF();return r==="win32"?"win32":r==="darwin"?"darwin":"linux"}function Zw(r){return JSON.stringify(r.split("+").sort())}function Hc(r,e){let t=dF(),n=Zw(r);for(let o of Object.values(uF))if(Object.values(o).some(i=>Zw(i)===n))return o[t];return process.platform==="darwin"&&!e?r=r.replaceAll("Control","Meta"):r=r.replaceAll("Meta","Control"),r}async function ng({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 nt({root:r,fn:([d,p,g,m])=>window.scrollTo(window.scrollX+(d??window.innerWidth)*g,window.scrollY+(p??window.innerHeight)*m),arg:[t,o,l,u],waitForPageLoad:s.waitForPageLoad,timeout:he,codePath:"scrolling page"});else{let d=e.viewportSize()||un,p=await nt({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:he,codePath:"computing page height"}),[g,m,h]=await nt({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:he,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<he;){a?.throwIfAborted();let E=await k(e.evaluate(()=>document.body.scrollHeight),{milliseconds:te}),[b,R,A]=await k(e.evaluate(()=>{let T=document.activeElement;if(!T)return[void 0,void 0,void 0];let _=T.getBoundingClientRect();return[T.scrollTop,_.x,_.y]}),{milliseconds:te});if(E===p&&b===g&&R===m&&A===h)break;p=E,g=b,m=R,h=A,await X(lt)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function og(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 X(lt)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}import{randomUUID as bF}from"crypto";import{cloneDeep as sg}from"lodash-es";function In(r,e){let t=r.findIndex(n=>n===e);if(!(t===-1||!r[t+1]))return r[t+1]}import{createHash as pF}from"crypto";var mF="v1";function ig(r,e){if(r.tagName.toLowerCase()==="svg"&&!hF(r))try{let t=Qw(r,e),n=gF(JSON.stringify(t));return{version:mF,json:t,hash:n}}catch{return}}function gF(r){return pF("md5").update(r).digest("hex")}function Qw(r,e){let t=r.tagName.toLowerCase(),n=fF(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=Qw(a,e);s&&o.children.push(s)}}return o}function hF(r){let e=r.computedStyles.display,t=r.computedStyles.visibility,n=r.computedStyles.opacity;return e==="none"||t==="hidden"||n==="0"}function fF(r){let e={},t=r.attributes;for(let n of Object.keys(t))lr.visualAttributesForSvgSerialization.includes(n)&&(e[n]=t[n]);return t.id&&r.tagName.toLowerCase()!=="svg"&&(e.id=t.id),e}var mo={r:147,g:196,b:125,a:.55},tR={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:mo,paddingColor:mo,borderColor:mo,marginColor:mo,eventTargetColor:mo,shapeColor:mo,shapeMarginColor:mo,showInfo:!0,showAccessibilityInfo:!0};function rR({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=SF({allDocuments:i,stringConstants:o,computedStylesToFetch:t,devicePixelRatio:e,frameIndex:u,backendIdToNode:a,frameIndexToIframeNode:s,logger:n});c.roots.push(d)}),c}function SF({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,D)=>{u[w]=D});let d=l.styles,p=l.bounds??[],g=c.nodes,m=g.contentDocumentIndex??{index:[],value:[]},h=g.backendNodeId??[],f=g.attributes??[],E=g.parentIndex??[],b=g.nodeName??[],R=g.nodeType??[],A=g.pseudoType??{index:[],value:[]},T=g.inputChecked??{index:[]},_=e[c.frameId];for(let w=0;w<h.length;w++){let D=h[w],G=R[w],ee=f[w]??[],Te=E[w]!==void 0&&E[w]>=0?E[w]:void 0,fe=Te!==void 0?h[Te]:void 0,ve=fe!==void 0?a[fe]:void 0,$=A.index.indexOf(w),j=$!==-1?e[A.value[$]]:void 0,se=u[w],J;se?J=p[se]??[]:J=[];let Ye=b[w]!==void 0?e[b[w]]?.toLowerCase():void 0;if(!Ye){s.warn({backendNodeId:D,frameId:_,frameIndex:o,nodeBounds:J},"DOM node has no tag name");continue}let Ne={backendNodeId:D,psuedoType:j,nodeType:G,frameIndex:o,parentFrameId:_,ownedFrameId:void 0,bounds:{x:J[0]??null,y:J[1]??null,width:J[2]??null,height:J[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:fe??null,tagName:Ye,parent:ve??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};ve&&ve.childrenBackendIds.push(D);let kt=m.index.indexOf(w);if(kt!==-1){let De=m.value[kt];i[De]=Ne;let Ie=r[De]?.frameId;Ne.ownedFrameId=Ie!==void 0?e[Ie]:void 0}for(let De of Object.keys(Ne.bounds)){let Ie=De;Ne.bounds[Ie]!==null&&(Ne.bounds[Ie]/=n)}let Ht=se!==void 0?d[se]??[]:[];for(let De=0;De<Ht.length&&!(De>=t.length);De++){let Ie=Ht[De];if(Ie===void 0||isNaN(Ie))continue;let xt=e[Ie];if(xt===void 0)continue;let gt=t[De];Ne.computedStyles[gt]=xt}for(let De=0;De<ee.length;De+=2){let Ie=ee[De],xt=ee[De+1];if(!Ie||!xt)continue;let gt=e[Ie],Vr=e[xt];!gt||!Vr||(Ne.attributes[gt]=Vr)}T.index.includes(w)&&(Ne.attributes.checked="true"),a[Ne.backendNodeId]=Ne}return a[h[0]]}function ag(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=`${ag(t,e)}${a}`}return r.mPathSelector=n,n}function eR(r,e){return r.parentBackendNodeId!==null?e.backendIdToNode[r.parentBackendNodeId]:r.frameIndex===0?void 0:e.frameIndexToIframeNode[r.frameIndex]}var yF=["html","#document","#document-fragment"];function nR({node:r,domGraph:e}){let t=[],n=r,o=eR(r,e);if(!o)return[r.tagName];let i=()=>{if(n=o,o=eR(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++,yF.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],p=e.backendIdToNode[d];if(d===n.backendNodeId){t.push(`${n.tagName}:nth-child(${l})`),c=!0;break}else p?.nodeType===1&&!p.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${n.tagName}) in parent's children list (${o.tagName})`)}i()}return t.reverse()}function oR(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 iR(r,e){await r.send({method:"DOM.getDocument",params:{depth:0},timeout:he});let t=await r.send({method:"DOM.requestNode",params:{objectId:e},timeout:he}),o=(await r.send({method:"DOM.getAttributes",params:{nodeId:t.nodeId},timeout:he})).attributes,i=In(o,Zr);if(!i)throw new Error(`Could not find attribute ${Zr} for object ${e}`);return i}var EF=["focusable","keyshortcuts","controls","live","relevant","orientation"],TF=["selected","readonly","modal","required","invalid"],vF=["id","name","role","content"],aR=["absolute","fixed","sticky"],AF=["i","label"],wF=["path"],RF=["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"],cR=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],uR=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],CF=["menulistpopup","statictext","inlinetextbox"],xF=80,sR=100,dR=50,ug=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],MF=["cite"],_F={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"]},PF={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},lR={indentLevel:0},lg=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<dR?t:""),this.role=this.role||(e.domNode.attributes.role??""),NF(this.properties,e.domNode,e.importantProperties)}kF(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&&wF.includes(this.domNode.tagName)||this.ignoredReasons.some(n=>uR.includes(n)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>fR(o,e)))return!0;let n=this.domNode?.attributes.class?.split(" ");if(n&&n.length>0&&n.some(o=>SR(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&&AF.includes(this.domNode.tagName)||RF.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||lr.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let t=this.properties.class;return typeof t=="string"&&t.split(" ").some(n=>hR(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=lR){let t=Object.assign({},lR,e),{indentLevel:n,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:c}=t,l=sg(this.properties),u=" ".repeat(n),d=this.role||"",p=this.tagName??"unknown",g=this.name;d==="heading"&&g==="heading"&&(g=""),this.nameSources?.find(T=>!T.superseded&&T.type==="contents")&&this.children.length>0&&(g="");let h=this.nameSources?.find(T=>!T.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let T=h.attributeValue?.relatedNodes??[];T.length===1&&T[0].text&&T[0].text===g&&(g="")}let f=ug.includes(this.role)||MF.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${u}${g}
|
|
4161
|
+
`;let E=`${u}<${p}`;!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!==p&&!(_F[d]??[]).includes(p)&&(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+=` ${lr.ineligibleElementAttribute}`),this.shouldSerializeBounds()&&this.domNode?.bounds){let T=this.domNode.bounds,_=Math.round(T.x??0),w=Math.round(T.y??0),D=Math.round((T.x??0)+(T.width??0)),G=Math.round((T.y??0)+(T.height??0));E+=` bounds=[${_} ${w} ${D} ${G}]`}let R=Date.now();if(Object.keys(l).length>0&&!i){if(Date.now()-R>1e3)throw new Error(`Serialization for the HTML element with tag ${p} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(l).forEach(([T,_])=>{if(!EF.includes(T)){{if(TF.includes(T)&&(!_||_==="false"))return;if(T==="value"&&b&&(l.type==="text"||this.role==="textbox"))return;if(T==="level"&&`${_}`=="1")return;if(T==="url"&&l.src&&p==="img")return;if(T==="url"&&l.href&&p==="a")return;if(T==="editable"&&_==="plaintext")return;if(T==="type"&&_===p)return;if(c&&!PF[T])return}typeof _=="string"?E+=` ${T}="${Nt(_,sR,!0)}"`:typeof _=="boolean"?_?E+=` ${T}`:E+=` ${T}={false}`:typeof _<"u"&&(E+=` ${T}={${Nt(JSON.stringify(_),sR,!0)}}`)}})}if(p==="::before"||p==="::after"){let T="";for(let _ of this.children)T+=_.serialize({...e,indentLevel:n,neighbors:0});return T}let A=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||A)E+=` />
|
|
4162
|
+
`;else{let T="";for(let w of this.children)T+=w.serialize({...e,indentLevel:n+2,neighbors:0});let _=T.trim();_.length<=xF&&!_.includes(`
|
|
4163
|
+
`)?E+=`>${_}</${p}>
|
|
4143
4164
|
`:E+=`>
|
|
4144
|
-
${
|
|
4145
|
-
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let
|
|
4165
|
+
${T}${u}</${p}>
|
|
4166
|
+
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let T=this.parent.children.findIndex(D=>D.id===this.id),_=T>0?this.parent.children[T-1]?.serialize({...e,neighbors:0}):"",w=T<this.parent.children.length-1?this.parent.children[T+1]?.serialize({...e,neighbors:0}):"";return`${_||""}
|
|
4146
4167
|
${E}
|
|
4147
|
-
${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:og(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=og(this.properties),e}},ag=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 p=n(m,s||u);p&&(d.push(p),p.parent=c,u=!0)}if(c.children=d,s||u)return c;if(sg.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 p=m,g=u-p;for(let h of c.children){let f=l+2,E=i(h,f).length;if(g<E)break;let{clone:b,used:x}=a(h,f,g);if(x>g)break;d.children.push(b),b.parent=d,p+=x,g-=x}return{clone:d,used:p}},{clone:s}=a(t,0,Math.max(1e4,e));return new r(s,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function RF(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 CF(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?(yl({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?(yl({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 $w({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:p,cdpClient:g,logger:h,callId:f}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let E=(B,ae={})=>{},b=r.backendDOMNodeId,x=EF.includes(r.role?.value?.toLowerCase()??"");if(!x&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let T=b?i.backendIdToNode[b]:void 0;if(!x&&!T)try{let B=await k(g.send({method:"DOM.describeNode",params:{backendNodeId:b}}),{milliseconds:750,fallback:()=>{h.debug("Timeout getting node from CDP while processing a11y tree")}});if(B&&B.node.nodeName.toLowerCase()==="slot"&&B.node.distributedNodes?.length)h.debug({redirectedDomNode:T,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:B},"Redirecting node to assigned slot");else return E("Filtering out node since it doesn't exist in the DOM",{cdpResult:B}),[]}catch(B){return E("Filtering out node since it doesn't exist in the DOM",{err:B}),[]}if(T&&e&&l&&u&&r.backendDOMNodeId&&!CF(T,u,h,f))return T.momenticIgnored=!0,[];if(T&&T.computedStyles.display==="none")return T.momenticIgnored=!0,[];if(T&&T.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&T.tagName.toLowerCase()!=="input")return T.momenticIgnored=!0,[];if(c===!1)return T.momenticIgnored=!0,[]}let v=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",O=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"",w=new ig({domNode:T,id:parseInt(r.nodeId),role:r.role?.value||"",name:v,nameSources:r.name?.sources,content:O,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(B=>(p??Vw).includes(B.name)||Ww.includes(B.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+RF(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:m,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),D=n,j=a[t],ie=t;if(T?.tagName.toLowerCase()==="iframe"&&T.ownedFrameId){let B=n.childFrames.find(Ze=>Ze.frameId===T.ownedFrameId),ae=o[B?.frameId??""]?.root,ue=a[B?.frameId??""];if(B&&ae&&ue){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Ze=ae;r.childIds=Ze.childIds,D=B,j=ue,ie=B.frameId}}let ee=T?.childrenBackendIds?.length??0,fe=(r.childIds??[]).filter(B=>!!j.get(parseInt(B))).length;if(ee>fe){let B=r.childIds?.map(ue=>j.get(parseInt(ue))).filter(Boolean).map(ue=>ue?.backendDOMNodeId).filter(ue=>ue!==void 0)??[],ae=0;for(let ue of T?.childrenBackendIds??[]){if(B.includes(ue)){ae=(r.childIds?.findIndex(Ie=>j.get(parseInt(Ie))?.backendDOMNodeId===ue)??0)+1;continue}let Ze=i.backendIdToNode[ue];if(!Ze||Ze?.tagName.toLowerCase()!=="svg")continue;let Ce=Math.floor(-1*Math.random()*1e7),zt={nodeId:Ce.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:ue,frameId:ie,role:{type:"string",value:"graphics-symbol"}};j.set(Ce,zt),r.childIds||(r.childIds=[]),r.childIds.splice(ae,0,Ce.toString()),ae++}}if(r.childIds?.length===1&&T){let B=j.get(parseInt(r.childIds[0])),ae=B?.role?.value,ue=T.childrenBackendIds;if(B&&ae==="StaticText"&&ue.length===1){let Ze=i.backendIdToNode[ue[0]];if(Ze?.tagName?.toLowerCase()==="span"){let Ce=Math.floor(-1*Math.random()*1e7).toString(),zt={nodeId:Ce,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Ze.backendNodeId,frameId:ie,childIds:[B.nodeId]};B.parentId=Ce,j.set(parseInt(Ce),zt),r.childIds=[Ce]}}}for(let B of r.childIds??[]){if(!B)continue;let ae=j.get(parseInt(B));if(!ae)continue;let ue=await $w({node:ae,parent:w,domGraph:i,axGraph:o,frameId:ie,frameContext:D,inputNodeMap:a,cdpClient:g,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:m,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});ue.length&&(w.children=w.children.concat(ue))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let B=w.name,ae=w.children[0]?.name;(B===ae||!ae)&&(w.children=[])}let st=[];for(let B=w.children.length-1;B>=0;B--){let ae=w.children[B];if(ae.role!=="StaticText"){st.push(ae);continue}if(B===0||w.children[B-1].role!=="StaticText"){st.push(ae);continue}w.children[B-1].name+=ae.name}if(w.children=st.reverse(),!w.isInteresting(m)&&r.parentId)return T&&(T.momenticIgnored=!0),w.children;for(let B of w.children)B.parent=w;return _F(w),T&&d&&ng(T,i),[w]}function qw({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:sg.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=rg(d,i),p=m?c[m.hash]:void 0,g=p?p.description:void 0;p&&(r.properties["data-momentic-description"]=g)}for(let m of r.children)l=qw({node:m,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function Kw({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:p}){let g=t??"root",h=r[g]?.root;if(!h)throw new Error("A11y tree has no root");let f=pF(),E=w=>{let D=w.allNodes.filter(ie=>!ie.ignoredReasons?.find(fe=>(p??Vw).includes(fe.name))),j=new Map;return D.forEach(ie=>{j.set(parseInt(ie.nodeId),ie)}),j},b={};Object.entries(r).forEach(([w,D])=>{b[w]=E(D)});let x=await $w({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:g,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:p});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 T={},v={},O={};return qw({node:x[0],a11yIdNodeMap:T,dataMomenticIdMap:v,selectorToNodeMap:O,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:m}),new ag(x[0],T,v,O)}function xF(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<jw&&!sr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(Yw(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 MF(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||fF.includes(a);if((sr.relevantElementAttributes.includes(a)||Xw(a,t))&&!c){let u=xF(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&zw.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of zw)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 _F(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(Nt(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 p=u.children.filter(g=>g.tagName==="th");if(p.length){if(i=p.map(g=>Nt(g.name,100,!1)),i.length===p.length)continue;i=void 0}}s+=1,u.properties["row-index"]||(u.properties["row-index"]=s);let d=u.children.filter(p=>p.tagName==="td"||p.tagName==="th"),m=d.length===i?.length;d.forEach((p,g)=>{p.tagName!=="th"&&(p.properties["col-index"]||(p.properties["col-index"]=g+1),m&&(p.properties.col||(p.properties.col=i[g])))})}}}function PF(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function Yw(r,e){if(e&&Jw(r,e))return!0;if(sr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(sr.alwaysInterestingClassNames.includes(r))return!0;for(let t of sr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function Xw(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 Jw(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 Gc=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 C("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await X(at),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 C("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 C("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await 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 C("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${n.url()})`)}});return this.logger.debug(`Created new CDP session for ${n.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let t=this.session;this.session=await this.createRawCDPSession(e),await 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 hi="<empty>";function IF(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 eR(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||IF(r.url)}async function OF(r,e){let t=await r.send({timeout:Z,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:Z,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:Z,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function fi({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:mi,method:"Page.getFrameTree",params:{}}),r.send({timeout:mi,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,m)=>{if(eR(d.frame))return null;try{return await tR({cdpClient:r,rawFrameTree:d,indices:[m],parent:n,warnings:o,logger:t})}catch(p){return o.push(`Failed to get child frame: ${p}`),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 tR({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await OF(r,a),c=s.attributes??[],l=null,u=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=In(c,g);h&&(u.push(`${g}=${JSON.stringify(h)}`),g==="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},p=(e.childFrames??[]).map(async(g,h)=>{if(eR(g.frame))return null;try{return await tR({cdpClient:r,rawFrameTree:g,indices:[...t,h],parent:d,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return d.childFrames=(await Promise.all(p)).filter(g=>g!==null),d}async function LF(r){try{return await r.owner().count()===1}catch{return!1}}async function NF(r){try{return await r.count()===1}catch{return!1}}async function Br(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,hi]){let m=o.frameLocator(d===hi?"iframe":`iframe[${d}]`);if(await LF(m)){u=!0,o=m,i.push(d);break}}if(!u)throw new C("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,hi]){let u=o.locator(l===hi?"iframe":`iframe[${l}]`);if(await NF(u)){a=u,i.push(l);break}}if(!a)throw new C("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${r.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(l=>l,{timeout:Q}),c=await s.asElement().contentFrame();if(!c)throw new C("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function Zw(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 rR({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===hi?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===hi?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 Br(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=Zw(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 Br(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=Zw(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 Br(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 Br(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Cr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function Vc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function lg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function nR(r){let e=lg(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 oR(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 iR({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await DF({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 DF({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Za({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:Se,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}import{create as kF,windowedFiniteBatchScheduler as UF}from"@yornaath/batshit";import{reduce as FF}from"lodash-es";var BF=100,zF=2e3;function aR(r){return kF({fetcher:async t=>{r(FF(t,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:UF({windowMs:zF,maxBatchSize:BF})})}async function sR({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(g=>g.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let m,p;if(l)try{let g=await n.frameElement();m=await k(g?.boundingBox(),{milliseconds:Z})??void 0;let h=await t.constructIframeRegex({urls:d,srcs:[],desiredUrl:l});if(h.urlRegex)p={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){i.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),p={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...r,screenshotBase64:o,frameConfig:p,frameBoundingBox:m})}catch(g){i.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as zr}from"crypto";import HF from"js-beautify";var GF=["Dead"],Wc=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:zr(),type:"PRESET_ACTION",command:jr(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=jr(i);a={id:zr(),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=jr(i);a={id:zr(),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=jr(i);a={id:zr(),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:he(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=HF.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=qA(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,...he(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=s}let p=this.recordedSteps.get(u)?.step??a,g=p?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...p,command:g},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(GF.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=jr("TYPE");i={id:zr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=jr("PRESS");i={id:zr(),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:zr(),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:zr(),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=jr(l);u.deltaY=Math.abs(i);let d={id:zr(),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=jr(l);u.deltaX=Math.abs(i);let d={id:zr(),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 cg}from"zod";var yEe=cg.object({type:cg.literal("url"),url:cg.string()});var jc=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];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 p=m.split(":");if(p.length!==2){this.logger.warn({style:m},"Invalid style property passed to importantStyles");continue}let g=p[0]?.trim(),h=p[1]?.trim();if(g===void 0||h===void 0){this.logger.warn({style:m},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(g)||this.computedStylesToFetch.push(g)}}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=lg(e),{frame:o,mPathSelectorTokens:i}=await Br(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 fi({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await rR({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(Vc(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:Vc(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await iR({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await fi({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[k(n.evaluate(e,t),{milliseconds:Se})],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(Br(c,n).then(({frame:u})=>k(u.evaluate(e,t),{milliseconds:Se})).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 fi({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 cr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new C("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await cr({fn:()=>fi({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 cr({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 cr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await cr({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 cr({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:fn,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=Uw({node:o,domGraph:this.domGraph});return Fw(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:Se});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await Bw(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(br(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 fi({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 C&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await X(at,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Vc(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=In(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 Br(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Br(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 C("ActionFailureError",`Failed to find frame with src matching: ${n}`)}async composeA11yDomGraph({opts:e,a11yGraph:t,domGraph:n,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:c,flagNotActionableNodes:l}){let u=await Kw({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 Br(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 rt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:Se,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(In(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=In(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:Z,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:Z,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:Z,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(p){i.warn({err:p},"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 p=0;p<3;p++)try{l=await cr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(g){c=g,i.warn({err:g},"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 p=d.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:p,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 ${p.frameId} with url ${p.url}, allowing it to be fetched: ${h}`)}d.push(...p.childFrames);let g=async()=>{try{let h=await cr({fn:()=>this.getRawA11yTreeForFrame({frameId:p.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${p.frameId}`,logObject:o,logger:i});u[p.frameId]=h}catch(h){i.warn({err:h,url:p.url,src:p.src},`Error getting raw a11y tree for child frame ${p.frameId}, continuing...`)}};m.push(g())}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 cr({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 cr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:Se}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await cr({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:Z}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await X(at,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new C("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${a?.message}`);return kw({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=nR(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 ug(r){let e=[],t="";for(let n of r)n==="+"&&t?(e.push(t),t=""):t+=n;return e.push(t),e}var rs=class r{static USER_AGENT=kc;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;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:p}){gb(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=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Dc]: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"];Pr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:_p.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(o)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`}),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:_p.htmlUtilsLibJs}),this.page.addScriptTag({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(o)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})])}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"&&YF()==="darwin"&&VF("system_profiler SPDisplaysDataType").toString().includes("Retina"))R.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 Gc.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 jc({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 ww(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 tg(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=dg(),o=`${e}-${n}`,i=Date.now(),a=!1,s=async()=>{try{await k(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&!this.closed&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=s().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()||!lo(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=dg(),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||e.on("console",a=>{aw(e,o,this.debugData,a,this.logger)});let i=async()=>{this.userBrowserSettings.disableBrowserMonitoring||(uw(this.logger,t,this.clientCallbacks?.onNetworkPage,e),!this.harBatcher&&this.clientCallbacks?.onNetworkLogs&&(this.harBatcher=aR(this.clientCallbacks.onNetworkLogs)),await e.route("**/*",async(a,s)=>{await jp({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("**/*",fw(this.customHeaders,this.logger))),Pr&&await e.route("**/*",es),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"||!lo(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(Zp(this.getBrowserCallbacks()),{milliseconds:Q})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0,this.cleanedUp=!0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.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<mi;){a++,n?.throwIfAborted();try{if(await rt({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:Q,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 X(at),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),rt({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:Z,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 X(pi),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??Se}),c=Buffer.from(s.data,"base64"),l=await cR.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&&$F(n,c),this.lastScreenshotForRecording=c,!e)return c;let m=await e.boundingBox({timeout:Z});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:p,y:g,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");p=Math.floor(p),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{let E=await cR.fromBuffer(c),b=E.bitmap.width,x=E.bitmap.height;p=Math.max(0,Math.min(p,b-1)),g=Math.max(0,Math.min(g,x-1)),h=Math.max(1,Math.min(h,b-p)),f=Math.max(1,Math.min(f,x-g)),c=await E.crop({x:p,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${p}, ${g}) 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}){VA(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 X(at),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:Q})}if(!i)throw new C("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(QA.has(s))throw new C("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);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 rt({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:Q,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 Mw({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 X(pi),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??Uh}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:Se})}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:Se})}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 zc({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:Q}),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 iw(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:Q});let n=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:Q,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 ow(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 nw(this.page,this.logger),o}catch(o){if(n=o,t++,t<=2){this.logger.warn({err:o,retryCount:t,maxRetries:2},`Error saving auth state, retrying (${t}/2)...`);let i=Math.pow(2,t)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:n},"Failed to save auth state after 2 retries"),new C("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return tg(this.context,e)}saveA11yDetailsToCache(e,t){t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,delete t.serializedForm,delete t.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:t,locator:n,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 xr)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(!Lp.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:Z})),!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:Z});if(!s||!s.width||!s.height)throw new C("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:Z});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||sr.bannedAiRequiredCacheAttributes.includes(l)))try{let u=await t.getAttribute(l,{timeout:Z});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 C("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new C("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,m,p;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let b=c.parentFrame,{cache:x,config:T}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=x,m=T,u=T.frame,p="auto iframe"}else c.parentFrame&&l?(m=l,u=await this.getActivePageOrFrame(),p="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),p="should not be possible");let g=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:u,node:c}),h={id:e,inputDescription:t??void 0,targetSource:n,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:he(i),frameCache:d},f,E=!1;o||(m&&(i.info({frameConfigSource:p,frameConfig:oR(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:g,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,target:h,root:u,locator:g,logger:i}));try{return{resolution:{locator:g,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:m,frameConfigSource:p}}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 p,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){p=f,await X(at,a)}if(!g)throw p}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 p=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{m=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,shouldLogOnFailure:p,logger:i,allowNotActionableNodesOverride:s,signal:a});break}catch(g){if(g instanceof Qi)break;if(g instanceof xr){if(d++,d>2)throw i.error({err:g},"Got multiple cache disqualification errors, giving up"),g;i.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await X(at,a)}a?.throwIfAborted(),p&&i.warn({err:g},`Could not resolve target using primary cache only (x${u})`),await X(at,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=Si(t),l=[],u,d=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),m;if(t.generatedSelectors||t.hybridSelector){let p;try{p=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s})}catch(g){m=g,g instanceof Cr&&(l.push(...g.decisions),u=g.cacheMissReason)}if(p)return{...p,pageState:void 0,decisions:[...l,...p.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:m?.message,selectors:Si(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw m;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let p=await this.resolveTargetWithSecondaryMethods({root:e,tree:d,target:t,decisions:l,logger:o,signal:i,allowNotActionableNodesOverride:a});if(p)return t.targetSource="HEURISTIC_HEALED",t.targetUpdateTime=new Date().toISOString(),t.targetUpdateLoggerTags=he(o),p;u="secondary-resolution-failed"}throw new Cr(`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 Qi("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:fn,s=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:Op,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 rt({fn:T=>window.evaluatePrimaryCaches(T),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:Z,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,m,p=[];if(s==="prefer"&&u?.result){d=u.result;let T={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};p.push(T),m="HYBRID_SELECTOR"}else if(l?.result){d=l.result;let T=`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,v=d.workingSelectors.slice(0,5);p.push({type:"CSS_SELECTOR",matched:!0,logs:l.logs,reason:T,selectors:v}),n.debug({reason:T,workingSelectors:v},"Resolved with CSS selectors"),m="CSS_SELECTOR"}else throw p.push({type:"CSS_SELECTOR",matched:!1,reason:l.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:l.logs}),u&&p.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 Cr("Cache evaluation failed",p,l.cacheMissReason);let g,h,f;if(this.userBrowserSettings.visualActions){let T=d.mPath;if(!T)throw new Error("Found element did not have an mPath despite using visual actions");let v=T.join(" > ");g=e.locator(v),h=this.stateManager.getNodeUsingMPathSelector(v)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?g=e.locator(d.workingSelectors[0]):g=e.locator(br(f));else throw new C("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=await lr(g,n);if(E&&E!==d.serializedElement)throw n.warn({currentNodeOnlySerializedHtml:E,cachedSerializedHtml:d.serializedElement},"Retrying cache resolution because element's HTML has changed since resolution"),new Error("Element's HTML has changed since cache was generated");let b=Si(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:g,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let x=mg(b,t);return x&&Object.keys(x).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=he(n),t.cacheResolutionUpdateSource=m),{a11yNode:h,displayString:d.serializedElement,locator:g,decisions:p}}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),p;try{return await m.waitFor({state:"attached",timeout:Q}),p=await lr(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:p,decisions:d}}catch(g){let h=g.message;u=new C("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 X(at,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:Z});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<JA){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 rt({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:Se,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(Op*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,p;if(d)m=this.stateManager.dataMomenticIdToNodeMap[d],p=e.locator(br(d));else if(l.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),p=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=l.closestNodeSerialized??await lr(p,o,500)??"unknown element";o.warn({result:l,originalTarget:t,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=Si(t);await this.updateCacheWithNewNodeDetails({node:m,target:t,locator:p,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=mg(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=he(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:g,savedElement:t.nodeOnlySerializedHtml}),{locator:p,a11yNode:m,displayString:g,decisions:n,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`)}}catch(l){o.info({err:l},"Failed to find closest HTML node using levenshtein distance"),n.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${l}`})}let s=t.screenshotUrl,c=t.role??"";if(s&&Lp.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=ZF(),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}),p=d.boundingBox?.width,g=d.boundingBox?.height;if(!p||!g)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=Si(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:m,allowNotActionableNodesOverride:o});let b=mg(E,t);return b&&Object.keys(b).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=he(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:Q})??"",i=xw.some(a=>a===o.toLowerCase());return await Qp({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()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return Qp({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Oc(s,t,n)){a=!0;break}await X(at,this.abortSignal)}if(!a)throw new C("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${aA(t)} in ${o}ms.
|
|
4148
|
-
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:Z});if(!o)throw new C("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=n.steps??5;await this.page.mouse.move(i,a,{steps:s}),await X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Se):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:Z});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 X(pi),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await uo({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:Z});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 uo({func:t=>t.locator.focus({timeout:Se}),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 rt({fn:()=>{let n=document.activeElement;n&&n.nodeType===1&&n.blur()},root:t,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:Q,codePath:"blurring the active element"});return}await this.highlight(e.locator),await uo({func:t=>t.locator.blur({timeout:Se}),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 uo({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(t.type==="INDEX"){let i=Number(t.index);if(isNaN(i))throw new C("UserConfigurationError",`Page index ${t.index} is not a number`)}await o.locator.selectOption({value:t.type==="VALUE"?t.value:void 0,label:t.type==="LABEL"?t.label:void 0,index:t.type==="INDEX"?Number(t.index):void 0},{force:n,timeout:Z})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Hc(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=Hc(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of ug(e))await this.page.keyboard.down(n)}async keyUp(e,t){if(t.convertMeta){let n=Hc(e,this.properties.isAndroid);n!==e&&(this.logger.info({keyString:e,convertedKey:n},"Converted platform dependent keys"),e=n)}for(let n of ug(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:fn;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(p){if(s?.throwIfAborted(),m=p instanceof Error?p.message:`${p}`,d>=t)throw p;u.warn({err:p,url:this.url()},"Error getting a11y tree, retrying...")}}throw new C("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${m}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await rt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:Z,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 X(pi,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<XA)){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 this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Ip):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o),await this.page.mouse.down(),await this.page.mouse.move(e+o.x,t+o.y,{steps:n}),await X(pi),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:Z}),n=await k(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:Se});process.platform==="darwin"&&n===1&&(n=KA);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,p=0,g=0,h=0]=u[d];m/=n,p/=n,g/=n,h/=n;let f=m+g/2,E=p+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return eg({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return eg({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async 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=uR(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 X(at)}}throw o}async switchToPageHelper(e,t){let n=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new C("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=n.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(n.map(a=>a.url))}`);o=n[i]}else{let i=n.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
|
|
4149
|
-
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!lo(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Qs(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:Z}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:gi,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let s=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},s),new Error(s)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<ZA;){await X(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:gi,taskId:o})});if(!s.ok){let l=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},l),new Error(l)}let c=await s.json();if(c.errorId){let l=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(l),new Error(l)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){try{await k(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&sR({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];lo(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},at);let s=async()=>{clearInterval(t)};e.addEventListener("abort",s,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:Q})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Za({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new C("UserInfrastructureError",`The page with URL ${Nt(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await Za({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return qF.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await rt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:Se,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new C("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=Se){let i=await this.getActivePageOrFrame();return rt({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=pn}){let i=hw(),a={code:e,fragment:t,context:n},{result:s}=await k(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new C("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:Se});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:Q})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new C("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(a),l=Math.round(s),u=Math.ceil(o*t),d=Math.ceil(i*n),m=u+l,p=d+c;return this.getDomNodeFromPixelPosition(m,p)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:Q,params:{highlightConfig:Dw,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:Q,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:Q})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[Zr],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(br(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:s}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await k(this.performTargetRedirectionHelper(e,t,n),{milliseconds:Z})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now();if(n===void 0&&(n=await e.boundingBox({timeout:Z})??void 0),!n){let x=await lr(e,t,500);t.error(`Attempted to click on element with no bounding box: ${x}`);return}let{x:i,y:a,width:s,height:c}=n,l=this.getViewport();if(i<0||a<0||!l||i+s>l.width||a+c>l.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:d,mPathSelector:m,error:p,serializedElement:g,foundElementRelativePoint:h,force:f,logs:E}=await e.evaluate(x=>{let T=window;if(!T.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return T.performTargetRedirection(x)},void 0,{timeout:Q}),b=Date.now()-o;if(p){t.warn({error:p,serializedElement:g,duration:b,force:f,logs:E},"Got error from target redirection with bounding box");return}else{if(d)return t.info({newDataMomenticId:d,serializedElement:g,duration:b,force:f,logs:E},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(br(d)),hints:{relativeXYToLocator:h,force:f}};if(m)return t.info({newMPathSelector:m,serializedElement:g,duration:b,force:f,logs:E},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(m),hints:{relativeXYToLocator:h,force:f}};if(h)return t.info({foundElementRelativePoint:h,serializedElement:g,duration:b,force:f,logs:E},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:h,force:f}};if(f)return t.info({serializedElement:g,duration:b,force:f,logs:E},"Forcing click on original element"),{locator:e,hints:{force:f}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,s=await e.evaluate((c,l)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:Se});if("error"in s&&s.error)throw s.error.startsWith(jA)?new Fs(s.error):s.error.startsWith($A)?new Bs(s.error):new Error(s.error);return s.warnings.length&&t.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:Q})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),s=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:n,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!gi}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Vp(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!$c(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||uR(e),o=WF(e),i=XF(e),a=Jd[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!$c(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:KF.getType(e)||"application/octet-stream"},{timeout:Ip})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=l;let m=atob(l),p=new Array(m.length);for(let h=0;h<m.length;h++)p[h]=m.charCodeAt(h);let g=new Uint8Array(p);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([g],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:s,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[]},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t,n){this.requestRecorders[e]={onRequestStart:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestStart(o,i)},onRequestComplete:(o,i)=>{t.matches({url:i.request.url,method:i.request.method})&&n.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??dg();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??YA}get userBrowserSettings(){return Si(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??mi}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=Bc();for(let t of e)if(!(!$c(t)||!lR(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=JF(t,o);return $c(i)&&lR(i).isDirectory()&&jF(i).length>0})))return t}};import CB from"fetch-cookie";import{cloneDeep as NR}from"lodash-es";import{CookieJar as xB}from"tough-cookie";async function ur({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var QF=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function mR({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(QF.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await X(250),l++;let u=(await t.getOpenPages()).map(m=>m.url),d=t.url();if(u.length!==e.length)for(let m=u.length-1;m>=e.length;m--){let p=u[m];if(lo(p,o)&&p!==r&&p!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(m)});break}}}}async function Hr(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}import{randomUUID as iB}from"crypto";var gR={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},hR={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},pR=/<(\S+) id="(\d+)".*?>/g,eB=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,fR=["h1","h2","section","footer","nav","aside","form","label","dialog"],tB=[...fR,"span","div","h3"],rB=["table","select","form","ul","ol","menu","pre","code","dialog"],nB=["table","form","dialog","nav","section","ul","select"];function qc(r){return oB(r)}function oB({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,s=[],c=e.split(`
|
|
4150
|
-
`),l=0,u=[],d=0,
|
|
4151
|
-
`),tokenLength:d}),u=[],d=0,
|
|
4152
|
-
`),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
|
|
4153
|
-
${r}`;case"ELEMENT_CHECK":return`${
|
|
4154
|
-
${r}`;default:return r}}var pB=15;async function Yc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=pB}){if(!r.assertion.trim())throw new C("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Ic(c),u=0,d=Date.now(),m,p,g;try{await ur({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 X(l,n.abortSignal),h=Date.now();let f=!1;try{if(m=await ur({action:async()=>{let b=await vR(s,t,n.abortSignal);return p&&p.serializedTree===b.serializedTree&&p.screenshotBuff.equals(b.screenshotBuff)?(f=!0,m):(p=b,AR({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?.updatedMemory&&xc(r,m.updatedMemory,t),m?.success)break;throw m?.thoughts?new C("AssertionFailureError",m.thoughts):new C("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),g=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 ur({action:async()=>AR({command:r,state:await vR(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(),g=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(!m?.success){let f=`AI check still failing after ${u} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new C("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function vR(r,e,t){let[n,o]=await Promise.all([Hr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function AR({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,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),x=r.contextChoice??"MULTIMODAL",T=g;x!=="VISION_ONLY"&&(T=await po({type:"assertion",serializedTree:g,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:m,logger:l,orgId:t.orgId}}),T!==g&&(p.ragUsed=!0),p.pageState=T);let v={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:T,screenshot:E,contextChoice:x,source:c},w=await(x==="VISION_ONLY"?(D,j)=>d.getVisualAssertionResult(D,j):(D,j)=>d.getAssertionResult(D,j))(v,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:m,logger:l,loggerTags:he(l)});return(w.result||i)&&w.relevantElements&&(p.relevantElementsSerialized=w.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await gB(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function gB(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 hB=75e4,Xc=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function wR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await fB(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Xc?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 X(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function fB(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await X(o.smartWaitingTimeout,n);return}if(!e.description)throw new C("UserConfigurationError","Cannot locate element with empty description");await k(SB(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function SB(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await ur({action:async()=>yB(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function yB(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 Ja({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:m}=await Hr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Er(m)>hB)throw new Xc;s.throwIfAborted();let g;try{g=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new C("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,${g.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:m,description:d,screenshot:f},{abortSignal:s,loggerTags:he(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as CR}from"lodash-es";async function xR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>Ch(e.cache)?e.cache:void 0,a=i(),s=CR(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=rA(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,p=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await X(m,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await RR({cacheToUse:a,params:r});if(d=h,p=f,h.success)break;c(),m=Math.min(m*2,1e4)}if(!d)throw new C("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&Cs(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await RR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let g=i();return d.success&&g?.target&&!p&&(g.target=Ap(g.target),g.updatedAt=new Date),d}async function RR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!an(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=EB(t.assertion),l,u=!1,d=CR(r);try{let{elementInteractedDisplayString:m,result:p,thoughts:g}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>bB(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:na(t),targetName:"target"}});return l={success:p.success,data:p.data,err:p.err,elementInteractedDisplayString:m,thoughts:g},u=!0,p.success||(s.warn({aiThoughts:g,elementString:m,err:p.err},"Element check found an element but failed"),l={...p,thoughts:g}),{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 C)||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 bB(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Nt(c,500,!0)},!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,i=new C("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Nt(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new C("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new C("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(p=>setTimeout(p,250));let m=l.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},wr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:wr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:wr*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?oA[n.condition]:iA[n.condition];i=new C("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,i=new C("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,n.operation==="EXISTS"?i=new C("AssertionFailureError",`The style property ${n.property} ${l}`):i=new C("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Jc(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function EB(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function MR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as TB}from"jimp";async function ns(r,e){let t=await r.screenshot(e),n=await TB.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as _R}from"jimp";import hg from"jpeg-js";import vB from"pixelmatch";async function PR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!an(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 ee=>ns(o,{locator:ee.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await ns(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 ie=`${l.width}x${l.height}`,ee=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ie}) does not match saved screenshot dimensions (${ee}) - 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 _R.fromBuffer(l.buffer),m={width:l.width,height:l.height},p=await _R.fromBuffer(u.buffer),g={width:u.width,height:u.height},h,f=m.width*m.height,E=g.width*g.height,b=Math.abs(m.height-g.height),x=Math.abs(m.width-g.width);if(f>E){let ie=d.cover({w:g.width,h:g.height});l.buffer=await ie.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(E>f){let ie=p.cover({w:m.width,h:m.height});u.buffer=await ie.getBuffer("image/jpeg"),h="saved"}let T={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},v=t.threshold??.1,w=vB(hg.decode(u.buffer).data,hg.decode(l.buffer).data,T.data,l.width,l.height,{threshold:v,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,D=w>v*100,j=`Visual diff of ${w.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${v*100}%.`;if(h&&(j+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${x} pixels.`),D)throw new C("ActionFailureError",j);return{fail:D,thoughts:j,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:hg.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var AB=3e4;async function Zc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??AB/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([p,g])=>p&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{a.append(p,g)});let s=a.toString(),c;if(ui(r.url)&&(c=r.url),t&&di(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new C("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 p=s?`${c}?${s}`:c;try{return await n(p,{headers:i,method:r.method,body:r.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new C("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let p;try{p=await u.text()}catch(g){p=`Failed to read response body: ${g}`}throw new C("ActionFailureError",`Fetch request failed with status ${u.status}: ${p}`)}let d={};u.headers.forEach((p,g)=>{d[g]=p});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 wB=5e3;async function OR({timeout:r=wr,...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 Qc(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 X(s,e.signal),s=Math.min(Math.floor(s*1.5),wB);else return i}return i=await Qc(e),i}async function Qc({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(IR,{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(IR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?wn.CONTAINS:Rn.CONTAINS;a=new C("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new C("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 IR({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 RB=3e4;async function LR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??RB/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,m])=>d&&m));a["Content-Type"]="application/json";let s;if(ui(r.url)&&(s=r.url),t&&di(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new C("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 C("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 C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw d?.errors?.length&&d?.errors[0]?.message?new C("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new C("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 eu=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([Hr(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 po({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:{...he(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([Hr(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 po({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}}),p={url:c,browserState:m,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...he(a)},langfuseSessionId:s})}catch(g){throw new C("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Hr(this.browser,e)}async locateElement(e){return await gg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return ur({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],p=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:m,cache:a[d],action:async g=>g,options:{...c,targetName:o[d]}});u.push(p)}try{let d=await s(...u.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=u.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(g=>g.elementInteractedDisplayString),thoughts:p}}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 C("ActionFailureError",d.message,{errOptions:{cause:d}})}}async wrapElementTargetingCommand(e){let t=this.logger.child({commandId:e.command.id}),n;for(let o=0;o<2;o++)try{return await ur({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&&ed(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(nd(i)||td(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(od(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof xr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof C?n:new C("ActionFailureError",n?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:t,action:n,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(t.type!=="description")throw new C("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 X(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:p}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=NR(e.cache);if((!b||l)&&!Uu(o))throw new C("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),E=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(E=!0,b=void 0),b?.inputDescription&&!TR(o.elementDescriptor,b.inputDescription)&&(g.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=v=>!!v&&Cs(v),T=!0;if(!x(b)){T=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await wR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:p,logger:g,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let v;try{v=await gg({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,logger:g},this.getControllerFixtures(t))}catch(D){if(D instanceof Oo&&D.updatedLocatorMemory){let j={id:-1,...i,memory:D.updatedLocatorMemory};Cc({cmd:c,key:d,newTarget:j,logger:g,updatedWithAI:!0})}throw new C("ActionFailureError",D.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let O=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),w=await a(O);return Cc({cmd:c,key:d,newTarget:v.target,logger:g,updatedWithAI:!0}),m&&(n.recordTargetAutoHeal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=he(g)),{result:w,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let O=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),w=await a(O);if(ft.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.7.2"]),Cc({cmd:c,key:d,newTarget:b,logger:g,updatedWithAI:!1}),T){let D=v.decisions.filter(j=>j.matched);if(D.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let j=D[0].type;n.recordTargetAutoHeal({healType:j})}}return{result:w,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let O="unknown";v instanceof Cr&&v.cacheMissReason&&(O=v.cacheMissReason),ft.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.7.2",`missReason:${O}`]);let w=!1;if((v instanceof xr||ed(v)||nd(v)||od(v)||wf(v)||td(v)||Rf(v))&&(w=!0),v instanceof C&&!w)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let D;return b.memory&&Eh(b.memory)&&(D=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:D,retriesWithAI:f,targetHealingInProgress:!0}})}throw new C("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return ns(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(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 C("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&&Gh(n)?await this.browser.waitForDOMStability({timeout:Se}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:Q}),this.options?.autoFollowNewTabs&&await mR({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{Rc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>zp(e)}}async resolveCommandTemplateStrings(e,t){return wc({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()?Yc({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 C("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new C("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Yc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new C("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=pb(n.schema);if(f)throw new C("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:g,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:he(a)});if(f.result==="NOT_FOUND")throw new C("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new C("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let E=f.message;throw E.includes("MaxGenerationLengthExceededError")?new C("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):E.includes("AIProviderError")&&E.includes("time")?new C("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!ui(n.url)&&!di(n.url,this.browser.baseUrl))throw new C("ActionFailureError",`Invalid URL provided to navigate command: ${n.url}`);await this.browser.navigate({url:n.url,loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(n.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...n,targetName:"target",disableCache:i}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(n.target&&Ar(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:T=>this.browser.hover(T),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});g=b,h=x}let f=this.browser.getViewport()?.height??un.height,E=this.browser.getViewport()?.width??un.width;switch(n.type){case"SCROLL_UP":await this.browser.scrollVertical(-(n.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(n.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(n.deltaX??E));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(n.deltaX??E);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new C("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new C("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await X(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action: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 Lc(g,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(Ar(n.fromTarget)&&Ar(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Ar(n.fromTarget)||Ar(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:t,command:n,targetNames:["fromTarget","toTarget"],descriptions:[n.fromTarget,n.toTarget],caches:[n.cache?.fromTarget,n.cache?.toTarget],action:(f,E)=>this.browser.dragAndDrop(f.locator,E.locator,{hoverSeconds:n.hoverSeconds,steps:n.steps}),options:{useSelector:!!n.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(g)||isNaN(h))throw new C("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ar(n.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,n.target.pixels,{force:n.force});break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:x,thoughts:T}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async v=>this.browser.mouseDrag(g,h,f,v.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=x,b=T}else await this.browser.mouseDrag(g,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!an(n.target))throw new Error("Select with x/y is not supported yet");let g=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:g},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:na(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let g={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,g);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let u=await this.browser.setCookie(n.value);a.debug({results:u},"Set cookies");break;case"LOCAL_STORAGE":if(!n.value||!n.key)break;await this.browser.setLocalStorage(n.key,n.value);break;case"JAVASCRIPT":{let g;try{n.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:g},"Executed JavaScript in browser")):g=await Ur({orgId:this.orgId,code:n.code,fragment:!!n.fragment,context:o,timeoutMs:n.timeout?n.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new C("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new C("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(n.target&&Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let g=this.browser.url(),h,f,E=NR(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:T,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:E,cache:n.cache?.target,action:O=>this.browser.typeIntoTarget(n.value,O,{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:na(n)}});h=T,f=v}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 Lc(g,x.urlAfterCommand)&&(x.succeedImmediately=!0,x.succeedImmediatelyReason="URL changed"),x}case"HOVER":{if(Ar(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.hover(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!an(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:f=>this.browser.focus(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(n.target&&!an(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,target:n.target,command:n,cache:n.cache?.target,action:f=>this.browser.blur(f),options:{...n,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Lc(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 g=new xB,h=CB(fetch,g),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Zc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:el(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await LR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return PR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,g=await tw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!g)throw new C("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!n.storageState.trim())g=void 0;else if(g=await Ur({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new C("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=NS.optional().parse(g)}catch(f){throw new C("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(n.timeout??wr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(MR(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 Yc({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&&xc(n,E.cache?.memory.traces,a)}}let f=await xR({command:n,tracer:t,timeoutMs:g,targetingWrapper:E=>this.wrapElementTargetingCommand(E),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await ur({action:async()=>OR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new _n(n.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[n.key]=h.then(async f=>await $p(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[n.key];if(!g)throw new C("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new _n(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Fc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Fc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[n.key];if(!g)throw new C("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return n.requestMatcher&&(g=new _n(n.requestMatcher)),this.browser.setHeader(n.name,n.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new _n(n.requestMatcher),async(h,f)=>{let E=await Ur({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=ZS.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(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:he(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 Wc({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:he(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:he(this.logger)})}};import{cloneDeep as MB}from"lodash-es";import BR from"truncate-json";var DR=1e3,kR=5e6,_B=5*1024*1024;function zR(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=BR(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":UR(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":UR(n),zR(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 UR(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function FR(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 tu(r,e){let t=MB(r);if(zR(t,e),t.length>DR)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,DR);let n=FR(t,e);if(n.length>kR)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>kR;)t.pop(),n=FR(t,e);let{jsonString:o}=BR(n,_B);try{return tr.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 PB}from"async_hooks";var os=new PB;function IB(r){os.enterWith({activeTracers:[r]})}function OB(r,e){let t=os.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function LB(r,e){let t=os.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return os.run({activeTracers:n},e)}var Qr={globalAls:os,initializeRootTracerContext:IB,withChildTracer:OB,withChildTracerAsync:LB};var go=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 Qr.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 Qr.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 Qr.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 ce(){let r=Qr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new go}async function HR(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=NB(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 NB(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 QB}from"fs";import{tmpdir as ez}from"os";import qR from"path";import{diff as JB}from"deep-object-diff";import{cloneDeep as ZB}from"lodash-es";import WR from"fontoxpath";import DB from"@prettier/plugin-xml";import kB from"prettier";import{DOMParser as UB,XMLSerializer as FB}from"slimdom";var BB=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 is(r){let e=r.toLowerCase();return e.endsWith("webview")||BB.has(e)}function zB(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 HB=new Set(["index","package","a11y-important","screen-reader-focusabl"]),GB=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"]),VB=new Set(["text","hint"]),WB=new Set(["live-region","drawing-order"]),jB=new Set(["displayed","enabled"]);function $B(r,e){let t={};for(let[n,o]of Object.entries(e))HB.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||GB.has(n)&&o==="false"||VB.has(n)&&o===""||jB.has(n)&&o==="true"||WB.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function GR(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 p=m.name,g=m.value;g!=null&&(l[p]=String(g))}let u=$B(e.tagName,l);for(let[m,p]of Object.entries(u))t.setAttribute(m,p);if(o.set(c,e),i.set(c,t),is(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(`
|
|
4155
|
-
${
|
|
4156
|
-
`));return}}let d=Array.from(e.childNodes??[]);for(let m of d){let p=m.nodeType;if(p===3){let g=m.nodeValue;g&&g.trim().length>0&&t.appendChild(n.createTextNode(g));continue}if(p===1){let g=m;if(!YB(g,s?.viewportBounds))continue;let h=n.createElement(zB(g.tagName));GR(r,g,h),t.appendChild(h)}}}function qB(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;GR(a,e,s);let c=new FB().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function VR(r,e){let t=new UB,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}=qB(t,i,o,e);return{xml:await kB.format(c,{parser:"xml",plugins:[DB],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function KB(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 ru(r,e){let t=r.idToElement.get(e);if(t)return KB(t)}function fg(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 ho(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 YB(r,e){if(!e)return!0;let t=ho(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 Sg(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function $R({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=ho(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=ru(t.graph,r.id)??"",a=fg(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Sg(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:p,requirements:g})=>{let h=t.graph.idToElement.get(p);if(!h)return;let f=ru(t.graph,p);return f?{xPath:f,requirements:{requiredText:g.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Sg(h,g.attributesRequired),requiredBounds:g.boundsRequired}}:void 0}).filter(p=>!!p));let m;return is(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},m}var jR=(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=ho(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 nu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ce();if(e.type==="WEBVIEW")return XB(e,r);let a=WR.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 p of m){let g=WR.evaluateXPathToFirstNode(p.xPath,o);if(!g)throw new Error(`ActionFailureError: Required related element not found for XPath: ${p.xPath}`);jR(g,p.requirements)}})}let s=ho(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");jR(a,e.requirements,e.bounds);let c;for(let[m,p]of n.idToElement.entries())if(p===a){c=m;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=fg(n,c)??l,u=ru(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function XB(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ce(),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 yi(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;il(e)&&(e[t]={...e[t],[n]:tl.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function ou(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var Ct=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}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),l=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:l}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:he(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`NoMatchingElementError: ${o.thoughts}`);let i=$R({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,m=ZB(l),p;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,m=void 0),s&&(d=!0,m=void 0),m&&m?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:m?.resolvedDescription},"Cache description mismatch, clearing it automatically"),d=!0,m=void 0),!m){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});p=h.thoughts;let f=await t(h.resolvedTarget);return yi({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:p}}let g;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),g=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,x)=>{let{resolvedTarget:T}=await nu({target:m,domState:g,stateManager:this.stateManager,logger:this.logger}),v=ou(T),O=JB(m,v);return O&&Object.keys(O).length>0&&this.logger.info({cacheDiffs:O},"Successfully resolved target with cache"),x.attributes.serializedElement=T.type==="WEBVIEW"?T.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":T.elementOnlySerializedXml,{resolvedTarget:T,updatedCache:v}}),E=await t(h);return yi({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),m.type!=="WEBVIEW"&&ft.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.7.2"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(m.type!=="WEBVIEW"&&ft.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!m.requirements}`,`hasAdditionalElements:${!!m.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.7.2"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}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}}}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==="down"?t-a:t+a:s=o==="right"?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 tz(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 bi=class extends Ct{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=qR.join(ez(),"momentic","downloads"),s=qR.join(a,this.orgId,i);return QB(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 ce().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=ce(),n=tz(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 Ln=class extends Ct{async doPress({keycode:e,longPress:t}){await ce().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var KR=25,iu=class extends Ct{async doType(e){let t=ce();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:void 0}}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 ce().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??KR};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 bi(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=ce(),n=e.keyPressDelayMs??KR;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=ce();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 Ln(this.constructPerformerParams()).doPress({keycode:67})}};import Vt from"zod";var yg=.8,Ei=.2,rz=Vt.object({navigationBar:Vt.object({visible:Vt.boolean(),x:Vt.number(),y:Vt.number(),width:Vt.number(),height:Vt.number()}),statusBar:Vt.object({visible:Vt.boolean(),x:Vt.number(),y:Vt.number(),width:Vt.number(),height:Vt.number()})}),Ti=class extends Ct{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=rz.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*Ei),n=Math.floor(e.height*Ei);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*Ei),l=Math.floor(s*Ei);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=ce();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:n,startY:o,deltaPixels:i}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{a.attributes.startX=n,a.attributes.startY=o,a.attributes.deltaPixels=i,a.attributes.direction=e.direction,await this.performRawSwipe({startX:n,startY:o,deltaPixels:i,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0}}if(e.scrollableElement.type!=="CUSTOM"){let n=await this.driver.getWindowRect(),o=await this.getHardcodedScrollableElementBounds(e.scrollableElement,n);return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>ce().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}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*Ei),s=Math.floor(i*Ei);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 scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??yg)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??yg)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=yg,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 JR}from"child_process";import iz from"pixelmatch";import{_android as az,chromium as sz}from"playwright";import{PNG as ZR}from"pngjs";import{z as $e}from"zod";var YR=$e.array($e.object({proc:$e.string(),webview:$e.string(),info:$e.object({"Android-Package":$e.string(),Browser:$e.string(),"Protocol-Version":$e.string(),"User-Agent":$e.string(),"V8-Version":$e.string(),"WebKit-Version":$e.string(),webSocketDebuggerUrl:$e.string()}),pages:$e.array($e.object({description:$e.string(),devtoolsFrontendUrl:$e.string(),id:$e.string(),title:$e.string(),type:$e.string(),url:$e.string(),webSocketDebuggerUrl:$e.string()})),webviewName:$e.string()}));function bg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=ZR.sync.read(n),a=ZR.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 iz(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var au=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 g=(await az.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(g.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(g.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=g[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=ce(),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 ce().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(bg(c,u)<=o){l=!0;break}c=u,await X(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");(is(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:ho(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ce().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 ce().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 o;if(e?.filterOffscreenElements??!0)try{let c=await this.driver.getWindowRect();o={left:c.x,top:c.y,right:c.x+c.width,bottom:c.y+c.height}}catch(c){this.logger.warn({err:c},"Could not get viewport bounds for off-screen filtering, continuing without filtering")}let a=await this.getPageSource();return{graph:await VR(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:o}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ce().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}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 ce().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=JR(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 ce().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=YR.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4168
|
+
${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:sg(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame,flagNotActionableNodes:this.flagNotActionableNodes});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=sg(this.properties),e}},cg=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 p=a(d);p&&(u.push(p),p.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 p of l){let g=n(p,s||u);g&&(d.push(g),g.parent=c,u=!0)}if(c.children=d,s||u)return c;if(ug.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 p=i(c,l).length;if(u<=p)return{clone:d,used:p};if(n(c)||c.children.length===0)return{clone:d,used:p};let g=p,m=u-g;for(let h of c.children){let f=l+2,E=i(h,f).length;if(m<E)break;let{clone:b,used:R}=a(h,f,m);if(R>m)break;d.children.push(b),b.parent=d,g+=R,m-=R}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 IF(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 OF(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?(yl({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?(yl({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 pR({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:p,allowedA11yIgnoreReasonsOverride:g,cdpClient:m,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,se={})=>{},b=r.backendDOMNodeId,R=CF.includes(r.role?.value?.toLowerCase()??"");if(!R&&b===void 0)return E("Filtering out node since it doesn't exist in the DOM"),[];let A=b?i.backendIdToNode[b]:void 0;if(!R&&!A)try{let j=await k(m.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:A,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(A&&e&&l&&u&&r.backendDOMNodeId&&!OF(A,u,h,f))return A.momenticIgnored=!0,[];if(A&&A.computedStyles.display==="none")return A.momenticIgnored=!0,[];if(A&&A.computedStyles.opacity==="0"&&c!==!0){if(c==="inputs-only"&&A.tagName.toLowerCase()!=="input")return A.momenticIgnored=!0,[];if(c===!1)return A.momenticIgnored=!0,[]}let T=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 lg({domNode:A,id:parseInt(r.nodeId),role:r.role?.value||"",name:T,nameSources:r.name?.sources,content:_,properties:r.properties,children:[],ignoredReasons:r.ignoredReasons?.filter(j=>(g??cR).includes(j.name)||uR.includes(j.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+IF(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:p,parentFrame:n.type==="root"?void 0:n,flagNotActionableNodes:s}),D=n,G=a[t],ee=t;if(A?.tagName.toLowerCase()==="iframe"&&A.ownedFrameId){let j=n.childFrames.find(Ye=>Ye.frameId===A.ownedFrameId),se=o[j?.frameId??""]?.root,J=a[j?.frameId??""];if(j&&se&&J){r.childIds&&r.childIds.length>0&&h.debug("Replacing existing node's children with children from the iframe");let Ye=se;r.childIds=Ye.childIds,D=j,G=J,ee=j.frameId}}let Te=A?.childrenBackendIds?.length??0,fe=(r.childIds??[]).filter(j=>!!G.get(parseInt(j))).length;if(Te>fe){let j=r.childIds?.map(J=>G.get(parseInt(J))).filter(Boolean).map(J=>J?.backendDOMNodeId).filter(J=>J!==void 0)??[],se=0;for(let J of A?.childrenBackendIds??[]){if(j.includes(J)){se=(r.childIds?.findIndex(De=>G.get(parseInt(De))?.backendDOMNodeId===J)??0)+1;continue}let Ye=i.backendIdToNode[J];if(!Ye||Ye?.tagName.toLowerCase()!=="svg")continue;let Ne=Math.floor(-1*Math.random()*1e7),kt={nodeId:Ne.toString(),parentId:r.nodeId,ignored:!1,backendDOMNodeId:J,frameId:ee,role:{type:"string",value:"graphics-symbol"}};G.set(Ne,kt),r.childIds||(r.childIds=[]),r.childIds.splice(se,0,Ne.toString()),se++}}if(r.childIds?.length===1&&A){let j=G.get(parseInt(r.childIds[0])),se=j?.role?.value,J=A.childrenBackendIds;if(j&&se==="StaticText"&&J.length===1){let Ye=i.backendIdToNode[J[0]];if(Ye?.tagName?.toLowerCase()==="span"){let Ne=Math.floor(-1*Math.random()*1e7).toString(),kt={nodeId:Ne,parentId:r.nodeId,ignored:!1,backendDOMNodeId:Ye.backendNodeId,frameId:ee,childIds:[j.nodeId]};j.parentId=Ne,G.set(parseInt(Ne),kt),r.childIds=[Ne]}}}for(let j of r.childIds??[]){if(!j)continue;let se=G.get(parseInt(j));if(!se)continue;let J=await pR({node:se,parent:w,domGraph:i,axGraph:o,frameId:ee,frameContext:D,inputNodeMap:a,cdpClient:m,logger:h,callId:f,filterByViewport:l,showZeroOpacityElements:c,importantProperties:p,viewportDetails:u,useMPaths:d,flagNotActionableNodes:s});J.length&&(w.children=w.children.concat(J))}if(w.role==="StaticText"&&(w.children=[]),w.children.length===1&&w.children[0].role==="StaticText"){let j=w.name,se=w.children[0]?.name;(j===se||!se)&&(w.children=[])}let ve=[];for(let j=w.children.length-1;j>=0;j--){let se=w.children[j];if(se.role!=="StaticText"){ve.push(se);continue}if(j===0||w.children[j-1].role!=="StaticText"){ve.push(se);continue}w.children[j-1].name+=se.name}if(w.children=ve.reverse(),!w.isInteresting(p)&&r.parentId)return A&&(A.momenticIgnored=!0),w.children;for(let j of w.children)j.parent=w;return DF(w),A&&d&&ag(A,i),[w]}function mR({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:ug.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 p=ig(d,i),g=p?c[p.hash]:void 0,m=g?g.description:void 0;g&&(r.properties["data-momentic-description"]=m)}for(let p of r.children)l=mR({node:p,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:l,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function gR({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:p,allowedA11yIgnoreReasonsOverride:g}){let m=t??"root",h=r[m]?.root;if(!h)throw new Error("A11y tree has no root");let f=bF(),E=w=>{let D=w.allNodes.filter(ee=>!ee.ignoredReasons?.find(fe=>(g??cR).includes(fe.name))),G=new Map;return D.forEach(ee=>{G.set(parseInt(ee.nodeId),ee)}),G},b={};Object.entries(r).forEach(([w,D])=>{b[w]=E(D)});let R=await pR({node:h,domGraph:e,parent:null,inputNodeMap:b,axGraph:r,frameId:m,frameContext:d,cdpClient:o,logger:n,callId:f,showZeroOpacityElements:a,importantProperties:c,filterByViewport:i,viewportDetails:l,useMPaths:u,flagNotActionableNodes:s,allowedA11yIgnoreReasonsOverride:g});if(R.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(R)}`);if(R.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let A={},T={},_={};return mR({node:R[0],a11yIdNodeMap:A,dataMomenticIdMap:T,selectorToNodeMap:_,domGraph:e,logger:n,callId:f,useMPaths:u,iconKnowledgeBase:p}),new cg(R[0],A,T,_)}function LF(r,e,t,n){if(r==="class"){if(t.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<dR&&!lr.bannedClassSubstrings.some(s=>a.includes(s))).slice(0,3).join(" ");let o=e.split(" "),i=[];for(let a of o)if(hR(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 NF(r,e,t){if(!e)return;Object.entries(e.attributes).forEach(([a,s])=>{let c=r[a]||a.startsWith("aria")||vF.includes(a);if((lr.relevantElementAttributes.includes(a)||fR(a,t))&&!c){let u=LF(a,s,e,t);u!==null&&(r[a]=u)}});let n,o=[];if(e.computedStyles.position&&aR.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of aR)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],p=`${c}: ${d}`;o.includes(p)||o.push(p)}}o.length>0&&(r.style=o.join("; "))}function DF(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(Nt(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(m=>m.tagName==="th");if(g.length){if(i=g.map(m=>Nt(m.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"),p=d.length===i?.length;d.forEach((g,m)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=m+1),p&&(g.properties.col||(g.properties.col=i[m])))})}}}function kF(r){let e=r.properties.class,t=typeof e=="string"&&e.includes("cm-content");r.internalProperties.inCodeMirrorEditor=r.internalProperties?.inCodeMirrorEditor||t}function hR(r,e){if(e&&SR(r,e))return!0;if(lr.bannedClassSubstrings.some(t=>r.includes(t)))return!1;if(lr.alwaysInterestingClassNames.includes(r))return!0;for(let t of lr.alwaysInterestingClassPrefixes)if(r.startsWith(t))return!0;return!1}function fR(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 SR(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 Gc=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 x("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(d){await X(lt),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 x("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 x("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 x("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 yi="<empty>";function UF(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 ER(r){let e=r.adFrameStatus?.adFrameType;return e==="child"||e==="root"||UF(r.url)}async function FF(r,e){let t=await r.send({timeout:Q,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await r.send({timeout:Q,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[t.backendNodeId]}})).nodeIds[0],a=(await r.send({timeout:Q,method:"DOM.describeNode",params:{backendNodeId:t.backendNodeId}})).node;return a.nodeId=o,a}async function bi({cdpClient:r,page:e,logger:t}){let n={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([r.send({timeout:hi,method:"Page.getFrameTree",params:{}}),r.send({timeout:hi,method:"DOM.getDocument",params:{depth:0}})]),l=(i.frameTree.childFrames??[]).map(async(d,p)=>{if(ER(d.frame))return null;try{return await TR({cdpClient:r,rawFrameTree:d,indices:[p],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 TR({cdpClient:r,rawFrameTree:e,indices:t,parent:n,warnings:o,logger:i}){let a=e.frame.id,s=await FF(r,a),c=s.attributes??[],l=null,u=[];for(let m of["src","name","id","title","srcdoc","sandbox"]){let h=In(c,m);h&&(u.push(`${m}=${JSON.stringify(h)}`),m==="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(m,h)=>{if(ER(m.frame))return null;try{return await TR({cdpClient:r,rawFrameTree:m,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(m=>m!==null),d}async function BF(r){try{return await r.owner().count()===1}catch{return!1}}async function zF(r){try{return await r.count()===1}catch{return!1}}async function Br(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,yi]){let p=o.frameLocator(d===yi?"iframe":`iframe[${d}]`);if(await BF(p)){u=!0,o=p,i.push(d);break}}if(!u)throw new x("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,yi]){let u=o.locator(l===yi?"iframe":`iframe[${l}]`);if(await zF(u)){a=u,i.push(l);break}}if(!a)throw new x("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 x("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${r.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:i}}function yR(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 vR({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===yi?s=s.length===1?s[0].childFrames:[]:s=s.filter(p=>p.locationData.attributeSelectors.includes(d)).map(p=>p.childFrames).flat()}let c=[],l=t.mPathSelectorTokens[t.mPathSelectorTokens.length-1];if(l===yi?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 Br(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=yR(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 Br(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=yR(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 Br(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 Br(n,r)).frame,handle:n,mPathSelectorTokens:t.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${t.indices}`),new Cr("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}],"could-not-find-iframe")}function Vc(r){return r.type==="auto"?JSON.stringify({type:"auto",frameId:r.handle.frameId}):JSON.stringify(r)}function dg(r){for(;r.parent.type==="frame";)r=r.parent;return r.parent}function AR(r){let e=dg(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 wR(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 RR({frame:r,logger:e,signal:t}){let n;try{n=await r.frameElement(),await HF({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 HF({frameElementHandle:r,logger:e,signal:t}){let n=await r.boundingBox();await Qa({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:he,codePath:"scrollIframeIntoView",signal:t}),e.info({oldBb:n,newBb:await r.boundingBox()},"Successfully scrolled iframe into view")}import{create as GF,windowedFiniteBatchScheduler as VF}from"@yornaath/batshit";import{reduce as jF}from"lodash-es";var WF=100,$F=2e3;function CR(r){return GF({fetcher:async t=>{r(jF(t,(n,o)=>({...n,...o}),{}))},resolver:()=>{},scheduler:VF({windowMs:$F,maxBatchSize:WF})})}async function xR({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(m=>m.url());i.debug({frameUrl:l,...r},"Passive click event captured on element");let p,g;if(l)try{let m=await n.frameElement();p=await k(m?.boundingBox(),{milliseconds:Q})??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(m){i.warn({err:m},"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:p})}catch(m){i.error({err:m},"Failed to transform passive click action")}})()}import{randomUUID as zr}from"crypto";import qF from"js-beautify";var KF=["Dead"],jc=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:zr(),type:"PRESET_ACTION",command:Wr(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=Wr(i);a={id:zr(),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=Wr(i);a={id:zr(),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=Wr(i);a={id:zr(),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:ge(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=qF.html(d,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),d=gw(d,"data-momentic-interacted",4e4)}catch{}let p;try{p=(await this.generator.getReverseMappedDescription({target:d,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:n.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...ge(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),p=s}let g=this.recordedSteps.get(u)?.step??a,m=g?.command;m&&"target"in m&&m.target?(m.target={type:"description",elementDescriptor:p},this.callbacks.onStepRecorded({...g,command:m},u)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,combinable:n}=e;if(KF.includes(t)||this.signal.aborted)return;let o="normal";t.length>1&&(o="special");let i;if(o==="normal"){let d=Wr("TYPE");i={id:zr(),type:"PRESET_ACTION",command:{...d,target:void 0,value:t,clearContent:!1}}}else{let d=Wr("PRESS");i={id:zr(),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,p=i.command.value;i={id:zr(),type:"PRESET_ACTION",command:{...u,value:i.command.type==="PRESS"?`${d}+${p}`:`${d}${p}`}},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:zr(),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=Wr(l);u.deltaY=Math.abs(i);let d={id:zr(),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=Wr(l);u.deltaX=Math.abs(i);let d={id:zr(),type:"PRESET_ACTION",command:u};this.callbacks.onStepRecorded(d,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(n(),e.deltaY>=20&&t()):(t(),e.deltaX>=20&&n())}};import{z as pg}from"zod";var _Ee=pg.object({type:pg.literal("url"),url:pg.string()});var Wc=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userControlledBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];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 p of this.userControlledBrowserSettings.importantStyles){let g=p.split(":");if(g.length!==2){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}let m=g[0]?.trim(),h=g[1]?.trim();if(m===void 0||h===void 0){this.logger.warn({style:p},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(m)||this.computedStylesToFetch.push(m)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.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=dg(e),{frame:o,mPathSelectorTokens:i}=await Br(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 bi({cdpClient:this.cdpClient,page:t,logger:this.logger}),{resolution:o,logs:i}=await vR({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(Vc(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:Vc(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await RR({frame:n.frame,logger:e,signal:t}),this.activeFrameCache=n,n}async executeFunctionInAllFrames(e,t){let n=this.pageGetter(),o=await bi({cdpClient:this.cdpClient,page:n,logger:this.logger}),i=[k(n.evaluate(e,t),{milliseconds:he})],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(Br(c,n).then(({frame:u})=>k(u.evaluate(e,t),{milliseconds:he})).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 bi({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 cr({fn:()=>this.resolveActiveFrameConfig({logger:n,signal:o}),codePath:"getActiveFrameDetails",logObject:t,signal:o,logger:n})??void 0,!a)throw new x("ActionFailureError","Got null frame details despite active frame config");s=a.handle,c=s.frameId}else this.userControlledBrowserSettings.autoExpandIframes?(s=await cr({fn:()=>bi({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 cr({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 cr({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:n}),codePath:"domFetch",logObject:t,signal:o,logger:n}),u=await cr({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 cr({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(p=>p>750)&&n.warn({logTimings:t},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=d.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=d.dataMomenticIdMap,this.lastA11yTreeRoot=d.root,this.lastDomGraph=l,this.lastSelectorToNodeMap=d.selectorToNodeMap,d}async fetchA11yTreeForRecording(e,t){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:t,logger:fn,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=nR({node:o,domGraph:this.domGraph});return oR(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:he});if(!n||!n.object.objectId)throw new Error(`Could not resolve backend node ${t}`);let o;try{o=await iR(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(yr(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 bi({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 x&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await X(lt,t)}finally{c++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:Vc(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=In(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 Br(s,o)});break}}else if(n.trim()===d.trim()){a.push({handle:s,matchType:"url",...await Br(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 x("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 gR({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 Br(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 nt({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:t,timeout:he,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(In(t,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let n=In(t,"style");if(n?.includes("display: none")||n?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:Q,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:Q,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:Q,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 cr({fn:()=>this.getRawA11yTreeForFrame({frameId:t,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,logger:i});break}catch(m){c=m,i.warn({err:m},"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),p=[];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 m=async()=>{try{let h=await cr({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...`)}};p.push(m())}return await Promise.all(p),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 cr({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 cr({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:he}),codePath:"cdp-get-root-ax-node",logObject:n,logger:this.logger})).node.backendDOMNodeId;o=(await cr({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:Q}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await X(lt,t),i++,a=s}if(!o||!o.documents.length)throw n.error({err:a},"Fatal error fetching DOM tree"),new x("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 rR({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:n})}constructIframeRegexAsync(e,t){if(t.frameSrcRegex||t.frameUrlRegex)return;let n=AR(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 ns=class r{static USER_AGENT=Dc;abortSignal=void 0;contextInitialized=!1;cleanedUp=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;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:p,onVideoPageChange:g}){kb(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=p,this.onVideoPageChange=g}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:t,timingRecorder:n}){if(this.contextInitialized)return;let o={[Nc]: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"];Pr||u.push("local-network-access"),i.push(this.context.grantPermissions(u))}i.push(this.context.addInitScript({content:Im.htmlUtilsLibJs}),this.context.addInitScript({content:eg(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:Im.htmlUtilsLibJs}),this.page.addScriptTag({content:eg(o,this.userBrowserSettings.disableFullStory)})])}catch(p){if(p instanceof Error&&p.message.includes("Content Security Policy"))this.logger.warn({err:p},"Content Security Policy error from adding Momentic scripts, reloading page instead"),s=!0;else throw p}(n??{})["add-init-scripts"]=Date.now()-d};i.push(u())}if(!this.properties.systemDevicePixelRatio)if(process.env.MOMENTIC_LOCAL_DEV==="1"&&tB()==="darwin"&&YF("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 Gc.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 Wc({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 jw(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 p=Date.now();l=await c.evaluate(()=>({width:window.innerWidth,height:window.innerHeight})),s["eval-viewport"]=Date.now()-p}let u=c?.url(),d=new 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 og(this.context,{getTitles:!0}),t=this.page.url();this.clientCallbacks?.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,t){let n=gg(),o=`${e}-${n}`,i=Date.now(),a=!1,s=async()=>{try{await k(t(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&!this.closed&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=s().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()||!co(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=gg(),n="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);this.userBrowserSettings.disableBrowserMonitoring||e.on("console",a=>{xw(e,o,this.debugData,a,this.logger)});let i=async()=>{this.userBrowserSettings.disableBrowserMonitoring||(Pw(this.logger,t,this.clientCallbacks?.onNetworkPage,e),!this.harBatcher&&this.clientCallbacks?.onNetworkLogs&&(this.harBatcher=CR(this.clientCallbacks.onNetworkLogs)),await e.route("**/*",async(a,s)=>{await qm({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("**/*",Dw(this.customHeaders,this.logger))),Pr&&await e.route("**/*",ts),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"||!co(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(tg(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.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<hi;){a++,n?.throwIfAborted();try{if(await nt({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 X(lt),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),nt({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:Q,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 X(fi),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??he}),c=Buffer.from(s.data,"base64"),l=await _R.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&&ZF(n,c),this.lastScreenshotForRecording=c,!e)return c;let p=await e.boundingBox({timeout:Q});if(!p)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:g,y:m,width:h,height:f}=p;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");g=Math.floor(g),m=Math.floor(m),h=Math.floor(h),f=Math.floor(f);try{let E=await _R.fromBuffer(c),b=E.bitmap.width,R=E.bitmap.height;g=Math.max(0,Math.min(g,b-1)),m=Math.max(0,Math.min(m,R-1)),h=Math.max(1,Math.min(h,b-g)),f=Math.max(1,Math.min(f,R-m)),c=await E.crop({x:g,y:m,w:h,h:f}).getBuffer("image/jpeg")}catch(E){throw new Error(`Failed taking element screenshot at coordinates (${g}, ${m}) 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}){uw(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 X(lt),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:te})}if(!i)throw new x("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(Ew.has(s))throw new x("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 nt({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 Kw({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 X(fi),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??Vh}),t.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:he})}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:he})}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 zc({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 Cw(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 Rw(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 ww(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 x("ActionFailureError",`Failed to save auth state: ${n?.message}`)}async getOpenPages(e){return og(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 xr)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(!Dm.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(t),o||(o=await t.boundingBox({timeout:Q})),!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:Q});if(!s||!s.width||!s.height)throw new x("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:Q});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||lr.bannedAiRequiredCacheAttributes.includes(l)))try{let u=await t.getAttribute(l,{timeout:Q});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 x("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let c=this.stateManager.a11yIdToNodeMap[e];if(!c)throw new x("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let l=this.stateManager.frameConfig,u,d,p,g;if(this.userBrowserSettings.autoExpandIframes&&!l&&c.parentFrame){let b=c.parentFrame,{cache:R,config:A}=await this.stateManager.getAutoFrameDetailsFromHandle(b);d=R,p=A,u=A.frame,g="auto iframe"}else c.parentFrame&&l?(p=l,u=await this.getActivePageOrFrame(),g="hardcoded url already on the state manager"):(u=await this.getActivePageOrFrame(),g="should not be possible");let m=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:ge(i),frameCache:d},f,E=!1;o||(p&&(i.info({frameConfigSource:g,frameConfig:wR(p)},"A11y node was resolved to a target within an iframe"),f=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(p),E=!0),await this.updateCacheWithNewNodeDetails({node:c,target:h,locator:m,logger:i,allowNotActionableNodesOverride:!0}),await this.updateCacheWithAdditionalRequirements({mainElementId:e,requirements:a,additionalElements:s,target:h,root:u,locator:m,logger:i}));try{return{resolution:{locator:m,a11yNode:c,displayString:c.getNodeOnlySerializedForm(),decisions:[]},target:h,frameConfig:p,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,m=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(t.frameCache);this.setActiveFrameConfig(f),m=!0;break}catch(f){g=f,await X(lt,a)}if(!m)throw g}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,i,a);let l=Date.now(),u=0,d=0,p;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),u++;let g=u===2||Date.now()-l>this.smartWaitingTimeout-2e3&&u%2===0;try{p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!0,shouldLogOnFailure:g,logger:i,allowNotActionableNodesOverride:s,signal:a});break}catch(m){if(m instanceof ea)break;if(m instanceof xr){if(d++,d>2)throw i.error({err:m},"Got multiple cache disqualification errors, giving up"),m;i.warn({err:m},"Got cache disqualification error, waiting and retrying resolution"),await X(lt,a)}a?.throwIfAborted(),g&&i.warn({err:m},`Could not resolve target using primary cache only (x${u})`),await X(lt,a)}}return p||(p=await this.resolveTargetHelper({root:c,target:t,primaryOnly:!1,logger:i,signal:a,allowNotActionableNodesOverride:s}),i.info({decisions:p.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:p?.decisions??[],pageState:void 0,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),p}async resolveTargetHelper({root:e,target:t,primaryOnly:n,logger:o,signal:i,allowNotActionableNodesOverride:a,shouldLogOnFailure:s}){let c=Ei(t),l=[],u,d=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowNotActionableNodesOverride:a})).serialize(),p;if(t.generatedSelectors||t.hybridSelector){let g;try{g=await this.resolveTargetWithPrimaryMethods({root:e,target:t,logger:o,allowNotActionableNodesOverride:a,shouldLogOnFailure:s})}catch(m){p=m,m instanceof Cr&&(l.push(...m.decisions),u=m.cacheMissReason)}if(g)return{...g,pageState:void 0,decisions:[...l,...g.decisions]};n||(l.push({type:"CSS_SELECTOR",matched:!1,reason:p?.message,selectors:Ei(t.generatedSelectors??[])}),t.generatedSelectors=void 0,t.hybridSelector=void 0)}if(n)throw p;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=ge(o),g;u=u??"secondary-resolution-failed"}throw new Cr(`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 ea("Insufficient data to resolve target using primary methods (missing node HTML)");let a=i?n:fn,s=this.userControlledBrowserSettings.hybridSelectorMode,c={ldistThreshold:Nm,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 nt({fn:T=>window.evaluatePrimaryCaches(T),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:Q,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),d,p,g=[];if(s==="prefer"&&u?.result){d=u.result;let T={type:"HYBRID_SELECTOR",matched:!0,logs:u.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};g.push(T),p="HYBRID_SELECTOR"}else if(l?.result){d=l.result;let T=`${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:T,selectors:_}),n.debug({reason:T,workingSelectors:_},"Resolved with CSS selectors"),p="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 Cr("Cache evaluation failed",g,l.cacheMissReason);let m,h,f;if(this.userBrowserSettings.visualActions){let T=d.mPath;if(!T)throw new Error("Found element did not have an mPath despite using visual actions");let _=T.join(" > ");m=e.locator(_),h=this.stateManager.getNodeUsingMPathSelector(_)}else if(d.dataMomenticId!==void 0)f=parseInt(d.dataMomenticId),h=this.stateManager.dataMomenticIdToNodeMap[f],"workingSelectors"in d?m=e.locator(d.workingSelectors[0]):m=e.locator(yr(f));else throw new x("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([m.textContent(),m.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||b.height!==d.boundingBox.height||b.width!==d.boundingBox.width||b.x!==d.boundingBox.x||b.y!==d.boundingBox.y)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 R=Ei(t);await this.updateCacheWithNewNodeDetails({node:h,target:t,locator:m,logger:n,startingBoundingBox:d.boundingBox,allowNotActionableNodesOverride:o});let A=hg(R,t);return A&&Object.keys(A).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ge(n),t.cacheResolutionUpdateSource=p),{a11yNode:h,displayString:d.serializedElement,locator:m,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 p=s.locator(n),g;try{return await p.waitFor({state:"attached",timeout:te}),g=await br(p,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:p,displayString:g,decisions:d}}catch(m){let h=m.message;u=new x("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 X(lt,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:Q});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<yw){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 nt({fn:d=>window.findClosestElementByLDist?.(d),arg:{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml},timeout:he,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),u=Math.floor(Nm*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,p,g;if(d)p=this.stateManager.dataMomenticIdToNodeMap[d],g=e.locator(yr(d));else if(l.mPathSelector)p=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 m=l.closestNodeSerialized??await br(g,o,500)??"unknown element";o.warn({result:l,originalTarget:t,displayString:m},"Resolved cached target to new node with pure html levenshtein distance");let h=Ei(t);await this.updateCacheWithNewNodeDetails({node:p,target:t,locator:g,logger:o,startingBoundingBox:l.boundingBox,allowNotActionableNodesOverride:a});let f=hg(h,t);return f&&Object.keys(f).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ge(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:m,savedElement:t.nodeOnlySerializedHtml}),{locator:g,a11yNode:p,displayString:m,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&&Dm.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=oB(),u=await this.enricher.runTemplateMatching({id:l,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:a.toString("base64")},{signal:n}),{target:d,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowNotActionableNodesOverride:o}),g=d.boundingBox?.width,m=d.boundingBox?.height;if(!g||!m)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let h=d.id,f=this.stateManager.a11yIdToNodeMap[h],E=Ei(t);await this.updateCacheWithNewNodeDetails({target:t,node:f,locator:p,allowNotActionableNodesOverride:o});let b=hg(E,t);return b&&Object.keys(b).length>0&&(t.cacheResolutionUpdateTime=new Date().toISOString(),t.cacheResolutionUpdateLoggerTags=ge(this.logger),t.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:l,diffs:b,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:f,displayString:d.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async typeIntoTarget(e,t,n={}){await this.highlight(t.locator);let o=await t.locator.getAttribute("type",{timeout:te})??"",i=qw.some(a=>a===o.toLowerCase());return await rg({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()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,n)}async click(e,t,n={}){return rg({targetingResult:e,options:n,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:t,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:t},n){let o=n?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Ic(s,t,n)){a=!0;break}await X(lt,this.abortSignal)}if(!a)throw new x("ActionFailureError",`The active page URL ${n?.negated?"still does":"does not"} ${MA(t)} in ${o}ms.
|
|
4169
|
+
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:Q});if(!o)throw new x("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 X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,he):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:Q});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 X(fi),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await po({func:async t=>{await this.scrollIntoViewIfNeeded(t.locator);let n=await t.locator.boundingBox({timeout:Q});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 po({func:t=>t.locator.focus({timeout:he}),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 nt({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 po({func:t=>t.locator.blur({timeout:he}),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 po({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 x("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:Q})},targetingResult:e})}async press(e,t){let n=t.repeat??1;if(t.convertMeta){let o=Hc(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=Hc(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=Hc(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:fn;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:n,signal:s});let d=0,p;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(),p=g instanceof Error?g.message:`${g}`,d>=t)throw g;u.warn({err:g,url:this.url()},"Error getting a11y tree, retrying...")}}throw new x("ActionFailureError",`Getting page content failed after ${t} attempts. Error: ${p}`)}async getViewportOffsetDetails(e){let[t,n,o,i,a]=await nt({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:Q,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:t,lowerBound:t+i,leftBound:n,rightBound:n+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:t=this.logger,timeout:n=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=p=>{i.value=Date.now()},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 X(fi,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<Sw)){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 this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(t.x,t.y,{steps:3}),await X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,Lm):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,t,n,o){await this.hoverUsingVisualCoordinates(o),await this.page.mouse.down(),await this.page.mouse.move(e+o.x,t+o.y,{steps:n}),await X(fi),await this.page.mouse.up()}async getElementLocation(e){let t=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:Q}),n=await k(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:he});process.platform==="darwin"&&n===1&&(n=hw);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[p=0,g=0,m=0,h=0]=u[d];p/=n,g/=n,m/=n,h/=n;let f=p+m/2,E=g+h/2;return{centerX:f,centerY:E}}async scrollVertical(e){return ng({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 ng({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=PR(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 X(lt)}}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 x("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)}.
|
|
4170
|
+
Available pages:${JSON.stringify(n.map(i=>i.url))}`);if(!co(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,t?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let t;return typeof e=="string"?t=Qs(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){let n;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,t],`setting local storage key ${e}`);return}catch(i){n=i}if(n)throw n}async solveCaptcha(){await this.getBrowserState({allowNotActionableNodesOverride:!0});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:Q}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Si,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let s=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},s),new Error(s)}let{taskId:o}=await n.json(),i=Date.now(),a="";for(;Date.now()-i<bw;){await X(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Si,taskId:o})});if(!s.ok){let l=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},l),new Error(l)}let c=await s.json();if(c.errorId){let l=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(l),new Error(l)}if(c.status==="ready"){a=c.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){try{await k(this.exposeRecordingBindingsHelper(),{milliseconds:this.pageLoadTimeout})}catch(e){e instanceof Error&&e.message.includes("already registered")||this.logger.error({err:e},"Failed to install Momentic libraries for action recording")}}async exposeRecordingBindingsHelper(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},t)=>{this.transformer&&xR({event:t,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async startRecordingCrons(e){if(e.aborted)return;let t,n=(await this.getOpenPages()).map(c=>c.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(t);return}i=!0;let c;try{c=(await this.getOpenPages()).map(u=>u.url),o=0}catch(u){this.logger.debug({err:u},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let u=c.length-1;u>=n.length;u--){let d=c[u];co(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:n,currentUrl:l,newOpenPages:c},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(u)});break}n=c};t=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(c){this.logger.error({err:c},"Error while checking pages during recording")}finally{i=!1}}},lt);let s=async()=>{clearInterval(t)};e.addEventListener("abort",s,{once:!0})}async startRecording(e,t,n){this.logger.debug({isClickToRecord:n},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(i=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=i},n),this.transformer=t,await this.injectKnowledgeBaseIntoBrowser(this.page);let o=async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!1,i._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}};e.addEventListener("abort",o,{once:!0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:te})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:t,codePath:n}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Qa({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlDomContentLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new x("UserInfrastructureError",`The page with URL ${Nt(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await Qa({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:t,codePath:`loadFrameAndRecordUrlPageLoad-${n}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:n,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:t=!1}=e??{};return t||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return QF.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:t,error:n}=await nt({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:he,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new x("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return t}registerDialogHandler(e){let t=async n=>{try{e==="ACCEPT"?await n.accept():await n.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",t)}async evaluateFunctionInAllFrames(e,t){return this.stateManager.executeFunctionInAllFrames(e,t)}async evaluateFunctionInPage(e,t,n,o=he){let i=await this.getActivePageOrFrame();return nt({root:i,fn:e,arg:t,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:n})}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=mn}){let i=Nw(),a={code:e,fragment:t,context:n},{result:s}=await k(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new x("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,t){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:he});let n;try{n=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:t},timeout:te})}catch(o){throw this.logger.error({err:o,x:e,y:t},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return n}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new x("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(a),l=Math.round(s),u=Math.ceil(o*t),d=Math.ceil(i*n),p=u+l,g=d+c;return this.getDomNodeFromPixelPosition(p,g)}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:te,params:{highlightConfig:tR,backendNodeId:n.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:te,method:"Overlay.hideHighlight",params:{backendNodeId:n?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:te})}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e);return this.getTargetFromBackendNodeId({root:t,backendNodeId:n.backendNodeId,allowNotActionableNodesOverride:e.allowNotActionableNodesOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:t,allowNotActionableNodesOverride:n}){let o=this.stateManager.domGraph?.backendIdToNode[t];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[Zr],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(yr(a)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowNotActionableNodesOverride:n}),u={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:u},"Tied backend ID to HTML node"),{target:u,locator:s}}async performTargetRedirection(e,t,n){try{return await this.scrollIntoViewIfNeeded(e),await k(this.performTargetRedirectionHelper(e,t,n),{milliseconds:Q})??{locator:e}}catch(o){return t.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,t,n){let o=Date.now();if(n===void 0&&(n=await e.boundingBox({timeout:Q})??void 0),!n){let R=await br(e,t,500);t.error(`Attempted to click on element with no bounding box: ${R}`);return}let{x:i,y:a,width:s,height:c}=n,l=this.getViewport();if(i<0||a<0||!l||i+s>l.width||a+c>l.height){t.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:d,mPathSelector:p,error:g,serializedElement:m,foundElementRelativePoint:h,force:f,logs:E}=await e.evaluate(R=>{let A=window;if(!A.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return A.performTargetRedirection(R)},void 0,{timeout:te}),b=Date.now()-o;if(g){t.warn({error:g,serializedElement:m,duration:b,force:f,logs:E},"Got error from target redirection with bounding box");return}else{if(d)return t.info({newDataMomenticId:d,serializedElement:m,duration:b,force:f,logs:E},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(yr(d)),hints:{relativeXYToLocator:h,force:f}};if(p)return t.info({newMPathSelector:p,serializedElement:m,duration:b,force:f,logs:E},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(p),hints:{relativeXYToLocator:h,force:f}};if(h)return t.info({foundElementRelativePoint:h,serializedElement:m,duration:b,force:f,logs:E},"Chose specific visible point on original element"),{locator:e,hints:{relativeXYToLocator:h,force:f}};if(f)return t.info({serializedElement:m,duration:b,force:f,logs:E},"Forcing click on original element"),{locator:e,hints:{force:f}}}}async fetchHtmlAttributes({locator:e,logger:t=this.logger,startingBoundingBox:n,allowNotActionableNodesOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,s=await e.evaluate((c,l)=>{let u=window;return u.generateHtmlCacheAttributes?u.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:n,showZeroOpacityElements:o?!0:a},{timeout:he});if("error"in s&&s.error)throw s.error.startsWith(pw)?new Fs(s.error):s.error.startsWith(mw)?new Bs(s.error):new Error(s.error);return s.warnings.length&&t.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,t){let n=this.getViewport();if(!n)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(n.width*e),i=Math.ceil(n.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,t,n){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*t),a=Math.ceil(o.height*n);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:te})}async scrollFromPositionPercentages(e,t,n,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),s=Math.ceil(i.height*t);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:n,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!Si}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,t,n,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,Wm(e,this.debugData,i,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:t}){if(!$c(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let n=t?.trim()||PR(e),o=XF(e),i=rB(e),a=Zd[i];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:n},"File chooser triggered");try{if(!$c(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:n,buffer:o,mimeType:eB.getType(e)||"application/octet-stream"},{timeout:Lm})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:u})=>{let d=window;d.momenticFileName=c,d.momenticFileBase64=l;let p=atob(l),g=new Array(p.length);for(let h=0;h<p.length;h++)g[h]=p.charCodeAt(h);let m=new Uint8Array(g);d.MomenticFile=class extends Blob{kind="file";name=d.momenticFileName;constructor(){super([m],{type:u})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([m]);return new File([h],d.momenticFileName,{type:u})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},d.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new d.MomenticFile])},{fileName:n,base64Data:s,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let t={...this.debugData};return this.debugData={logsPerPage:[]},t}async copy(e){try{await this.evaluateFunctionInPage(t=>navigator.clipboard.writeText(t),e,"copying text to clipboard")}catch(t){if(t instanceof Error&&t.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard");return}throw t}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(t=>{let n=t.request();return e.matches({url:n.url(),method:n.method()})})}registerRequestRecorder(e,t){this.requestRecorders[e]=t}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,t,n){this.customHeaders.push({key:e.toLowerCase(),value:t,matcher:n})}registerMock(e,t,n,o){let i=e??gg();return this.mocks[i]={matcher:t,generateResponse:n,fetchOriginalResponse:o},i}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??fw}get userBrowserSettings(){return Ei(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??hi}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}get browserCrashDumpDir(){let e=Bc();for(let t of e)if(!(!$c(t)||!MR(t).isDirectory()||!["new","pending","completed"].some(o=>{let i=nB(t,o);return $c(i)&&MR(i).isDirectory()&&JF(i).length>0})))return t}};import OB from"fetch-cookie";import{cloneDeep as eC}from"lodash-es";import{CookieJar as LB}from"tough-cookie";async function ur({frameConfig:r,action:e,browser:t}){let n=t.getActiveFrameConfig();r?t.setActiveFrameConfig(r):n?.type==="auto"&&t.setActiveFrameConfig(void 0);try{return await e()}finally{t.setActiveFrameConfig(n)}}var iB=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function OR({beforeUrl:r,beforePages:e,browser:t,command:n,logger:o}){if(iB.includes(n.type))return;let s=("cache"in n&&n.cache&&"target"in n.cache?n.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await X(250),l++;let u=(await t.getOpenPages()).map(p=>p.url),d=t.url();if(u.length!==e.length)for(let p=u.length-1;p>=e.length;p--){let g=u[p];if(co(g,o)&&g!==r&&g!==d){o.info({beforePages:e,afterPages:u,beforeUrl:r},"Auto-following new tab after preset action"),await t.switchToPage({type:"INDEX",index:String(p)});break}}}}async function Hr(r,e={}){let t=await r.getBrowserState(e);return{serializedTree:t.serialize(e.serializationOpts),tree:t}}import{randomUUID as dB}from"crypto";var NR={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},DR={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:3e4,maxLineLength:500},LR=/<(\S+) id="(\d+)".*?>/g,aB=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,kR=["h1","h2","section","footer","nav","aside","form","label","dialog"],sB=[...kR,"span","div","h3"],lB=["table","select","form","ul","ol","menu","pre","code","dialog"],cB=["table","form","dialog","nav","section","ul","select"];function qc(r){return uB(r)}function uB({logger:r,serializedTree:e,options:t}){let{minChunkTokenCount:n,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=t,s=[],c=e.split(`
|
|
4171
|
+
`),l=0,u=[],d=0,p=[],g=[],m=!1;for(;l<c.length;){m&&(s.push({ids:p,content:u.join(`
|
|
4172
|
+
`),tokenLength:d}),u=[],d=0,p=g.length?[g[g.length-1].id]:[],m=!1);let h=c[l],f=Er(h);d+=f,h.length>a&&(h=h.slice(0,a));let R=Array.from(h.matchAll(LR)).map($=>$&&$.length>=3?{tagName:$[1],id:$[2]}:void 0).filter($=>!!$),T=Array.from(h.matchAll(aB)).map($=>$&&($[2]||$[4])).filter($=>!!$);T.reverse();let _=h.replace(/ id="[0-9]+"/g,"");u.push(_);for(let $ of R)p.push($.id),g.push($);for(let $ of T){let j=g[g.length-1];j&&j.tagName===$&&g.pop()}let w=g.some($=>lB.includes($.tagName)),D=c[l+1]??"",G=Er(D),Te=Array.from(D.matchAll(LR)).map($=>$&&$.length>2?$[1]:void 0).filter($=>!!$),fe=Te.some($=>kR.includes($)),ve=Te.some($=>sB.includes($));d+G>=i&&(m=!0),d>=n&&(fe&&!w||T.some($=>cB.includes($)))&&(m=!0),d>=o&&ve&&!w&&(m=!0),l++}return u.length&&s.push({ids:p,content:u.join(`
|
|
4173
|
+
`),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 pB=75e4,Kc=3e5;async function go(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=Er(u);if(d>pB)try{let p=qc({serializedTree:u,options:{minChunkTokenCount:1e4,maxChunkTokenCount:1e5,acceptableChunkTokenCount:5e4,maxLineLength:4e3},logger:i});l=await gB({...r,tokenLimit:Kc-1e4,chunks:p.chunks}),u=l.serialize();let g=Er(u);i.info({oldTokens:d,newTokens:g},"Filtered page using keywords"),d=g}catch(p){i.warn({err:p},"Error filtering page using keyword matching, using naive truncation"),l=l.pruneToSerializedCharLimit(Kc*Mn),u=l.serialize();let g=Er(u);i.info({oldTokens:d,newTokens:g},"Filtered page using naive truncation"),d=g}if(d>Kc)try{if(o){let p=qc({serializedTree:u,options:DR,logger:i}),g=dB();l=await k(mB({...r,chunks:p.chunks,callId:g}),{milliseconds:12e3,signal:c}),u=l.serialize();let m=Er(u);i.info({oldTokens:d,newTokens:m,langfuseCallId:g},"Filtered page using AI chunk ranking"),d=m}else{let p=qc({serializedTree:u,options:NR,logger:i});l=await k(hB({...r,chunkResult:p,tokenLimit:4e4}),{milliseconds:12e3,signal:c}),u=l.serialize();let g=Er(u);i.info({oldTokens:d,newTokens:g},"Filtered page using RAG"),d=g}}catch(p){i.warn({err:p},"Error filtering page using RAG/AI, using naive truncation"),l=l.pruneToSerializedCharLimit(Kc*Mn),u=l.serialize(),i.info("Filtered page using naive truncation")}return u}async function mB({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:ge(c)}),u=[];return t.forEach((p,g)=>{l.indices.includes(g)&&(u=u.concat(p.ids))}),i.pruneUsingRelevantIds(new Set(u))}async function gB(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:ge(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,m)=>g+m.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 hB(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:ge(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 Sg(r,e){if(!r.description)throw new x("UserConfigurationError","Cannot locate element with empty description");return ur({action:async()=>fB(r,e),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:e.browser,logger:r.logger})}async function fB(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:p,browser:g,localCodeEvalTools:m,generator:h,abortSignal:f}=e,E=r.description,b=r.useMemory&&!t;n&&(E=await Ja({orgId:p,s:E,context:n,localTools:m,signal:f,logger:l})),a&&(E=yB(E,a));let{serializedTree:R,tree:A}=await Hr(g,{allowNotActionableNodesOverride:u,filterByViewport:o,abortSignal:f,skipWait:i,logger:l}),T,_=Date.now(),w;for(;!T&&Date.now()-_<3e3;){f.throwIfAborted();try{T=await g.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(J){w=J}}if(!T)throw new x("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 D=R,G=!1,Te=`data:image/jpeg;base64,${T.toString("base64")}`;D=await go({type:"locator",description:E,screenshot:Te,serializedTree:R,options:{aiPageFiltering:c},tree:A,fixtures:{generator:h,signal:f,logger:l,orgId:p}}),D!==R&&(G=!0);let fe=await h.getElementLocation({browserState:D,goal:E,screenshot:Te,source:a,memory:b?s:void 0},{disableCache:t,abortSignal:f,loggerTags:ge(l),useMemory:b});l.debug({usedRag:G,result:fe},"Got locator result");let ve=fe.id>0;if(d?.details?.push({type:"AI_LOCATION",matched:ve,pageState:D,ragUsed:G,thoughts:fe.thoughts}),!ve)throw new Do(`Could not find any relevant element: ${fe.thoughts}`,fe.updatedMemory?{type:"GCS_TRACES",traces:fe.updatedMemory}:void 0);let{resolution:$,target:j,frameConfig:se}=await g.createTargetFromA11yId({id:fe.id,requirements:fe.requirements,additionalElements:fe.additionalElements,description:E,targetSource:"AI",logger:l});if($.a11yNode?.properties?.hidden&&$.a11yNode?.properties?.hidden!=="false")throw new x("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: ${$.displayString}`);return b&&(fe.updatedMemory?j.memory={type:"GCS_TRACES",traces:fe.updatedMemory}:s&&(j.memory=s)),{thoughts:fe.thoughts,target:j,resolution:$,frameConfig:se,screenshot:Te}}var SB=["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:"],UR="<select> element:",FR="text input or contenteditable element:",BR="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:",zR="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:",fg=[UR,FR,BR,zR,...SB];function HR(r,e){if(r===e)return!0;for(let t of fg){if(!r.startsWith(t))continue;let n=r.slice(t.length).trim();if(fg.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===n)||n===e.trim())return!0}return!!fg.some(t=>e.startsWith(t)&&e.slice(t.length).trim()===r.trim())}function yB(r,e){if(!r||!e)return r;switch(e){case"SELECT_OPTION":return`${UR} ${r}`;case"TYPE":return`${FR} ${r}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${BR}
|
|
4174
|
+
${r}`;case"ELEMENT_CHECK":return`${zR}
|
|
4175
|
+
${r}`;default:return r}}var bB=15;async function Yc({command:r,aiPageFiltering:e,logger:t,fixtures:n,source:o,useMemory:i,maxRetries:a=bB}){if(!r.assertion.trim())throw new x("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=n,c=r.timeout?r.timeout*1e3:s.smartWaitingTimeout,l=Pc(c),u=0,d=Date.now(),p,g,m;try{await ur({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 X(l,n.abortSignal),h=Date.now();let f=!1;try{if(p=await ur({action:async()=>{let b=await GR(s,t,n.abortSignal);return g&&g.serializedTree===b.serializedTree&&g.screenshotBuff.equals(b.screenshotBuff)?(f=!0,p):(g=b,VR({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}),p?.success){p?.updatedMemory&&Za(r,p.updatedMemory,t);break}else throw p?.thoughts?new x("AssertionFailureError",p.thoughts):new x("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(E){n.abortSignal.throwIfAborted(),m=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(!p?.success)try{p=await ur({action:async()=>VR({command:r,state:await GR(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(),m=f instanceof Error?f:new Error(`${f}`)}finally{u++}if(p?.updatedMemory&&Za(r,p.updatedMemory,t),!p?.success){let f=`AI check still failing after ${u} attempts.`;throw m&&(f+=` Latest result: ${m.message}`),new x("AssertionFailureError",f)}return{...p,succeedImmediately:!1,urlAfterCommand:s.url()}}async function GR(r,e,t){let[n,o]=await Promise.all([Hr(r,{abortSignal:t,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),r.screenshot({retries:1,respectActiveFrame:!0})]);return{...n,screenshotBuff:o}}async function VR({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:p}=t,g={type:"ASSERTION"},{serializedTree:m,tree:h}=e,f=e.screenshotBuff,E=f.toString("base64"),b=u.url(),R=r.contextChoice??"MULTIMODAL",A=m;R!=="VISION_ONLY"&&(A=await go({type:"assertion",serializedTree:m,tree:h,description:r.assertion,screenshot:E,options:{aiPageFiltering:a},fixtures:{generator:d,signal:p,logger:l,orgId:t.orgId}}),A!==m&&(g.ragUsed=!0),g.pageState=A);let T={goal:r.assertion,url:b,memory:o?r.cache?.memory:void 0,browserState:A,screenshot:E,contextChoice:R,source:c},w=await(R==="VISION_ONLY"?(D,G)=>d.getVisualAssertionResult(D,G):(D,G)=>d.getAssertionResult(D,G))(T,{useConsensus:n,attemptNumber:s,useMemory:o,disableCache:!!r.disableCache,abortSignal:p,logger:l,loggerTags:ge(l)});return(w.result||i)&&w.relevantElements&&(g.relevantElementsSerialized=w.relevantElements.map(D=>u.getSerializedFormFromA11yId(D)).filter(D=>!!D),await EB(w.relevantElements,u,l)),{success:w.result,thoughts:w.thoughts,afterScreenshotOverride:f,updatedMemory:o?w.updatedMemory:void 0}}async function EB(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 TB=75e4,Xc=class extends Error{constructor(){super("The page content exceeds the maximum token limit for AI smart waiting."),this.name="ExceededMaxAISmartWaitingTokensError"}};async function jR(r,e){let{logger:t}=r,{abortSignal:n,browser:o}=e,i=Date.now();try{await vB(i,r,e)}catch(a){if(a instanceof Error&&(a.name==="AbortError"||a.name==="TimeoutError")||n.aborted)return;a instanceof Xc?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 X(s,n)}finally{t.debug({durationMs:Date.now()-i},"AI smart waiting complete")}}async function vB(r,e,t){let{abortSignal:n,browser:o}=t;if(o.smartWaitingTimeout<3e3){await X(o.smartWaitingTimeout,n);return}if(!e.description)throw new x("UserConfigurationError","Cannot locate element with empty description");await k(AB(r,e,t),{milliseconds:o.smartWaitingTimeout})}async function AB(r,e,t){let{logger:n,iframeUrl:o}=e,{browser:i}=t;for(;Date.now()-r<i.smartWaitingTimeout;)if(await ur({action:async()=>wB(e,t),frameConfig:o?{type:"url",url:o}:void 0,browser:i,logger:n}))return}async function wB(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 Ja({orgId:l,s:d,context:t,localTools:c,signal:s,logger:n}));let{serializedTree:p}=await Hr(a,{allowNotActionableNodesOverride:i,filterByViewport:o,abortSignal:s,logger:n});if(Er(p)>TB)throw new Xc;s.throwIfAborted();let m;try{m=await a.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(b){throw new x("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,${m.toString("base64")}`;s.throwIfAborted();let E=await u.getSmartWaitingDecision({browserState:p,description:d,screenshot:f},{abortSignal:s,loggerTags:ge(n)});return n.debug({result:E},"Got smart waiting result"),E.isPageReady}import{cloneDeep as $R}from"lodash-es";async function qR(r){let{command:e,timeoutMs:t,fixtures:n}=r,{abortSignal:o}=n,i=()=>_h(e.cache)?e.cache:void 0,a=i(),s=$R(a),c=(h=!1)=>{if(a=i(),!!a)if(h){let f=wA(s,a);a.target=f.target,a.updatedAt=f.updatedAt}else{if(!s){a=void 0;return}a.target=s.target,a.updatedAt=s.updatedAt}},l=Date.now(),u=0,d,p=500,g=!1;for(;u<2||Date.now()-l<t;){u++,u>1&&await X(p,o),o?.throwIfAborted(),a=i();let{result:h,elementWasFound:f}=await WR({cacheToUse:a,params:r});if(d=h,g=f,h.success)break;c(),p=Math.min(p*2,1e4)}if(!d)throw new x("InternalPlatformError",`Failed to evaluate manual element assertion in ${t}ms.`);if(o?.throwIfAborted(),!d.success&&a?.target&&xs(a.target)){let h=a?.target?.memory?{target:{id:-1,memory:a.target.memory}}:void 0,{result:f}=await WR({cacheToUse:h,params:r});d=f,d.success||c(!0)}let m=i();return d.success&&m?.target&&!g&&(m.target=wm(m.target),m.updatedAt=new Date),d}async function WR({cacheToUse:r,params:e}){let{command:t,disableCache:n,fixtures:o,tracer:i,targetingWrapper:a}=e,{logger:s}=o;if(t.target&&!an(t.target))throw new Error("Element assertion with x/y is not supported yet");let c=CB(t.assertion),l,u=!1,d=$R(r);try{let{elementInteractedDisplayString:p,result:g,thoughts:m}=await a({ctx:o.ctx,tracer:i,command:t,target:t.target,cache:d?.target,action:async h=>RB(h.locator,e),options:{...t,allowNotActionableNodesOverride:!0,disableCache:n,memory:d?.target?.memory,disableGlobalLocatorRedirect:!0,source:na(t),targetName:"target"}});return l={success:g.success,data:g.data,err:g.err,elementInteractedDisplayString:p,thoughts:m},u=!0,g.success||(s.warn({aiThoughts:m,elementString:p,err:g.err},"Element check found an element but failed"),l={...g,thoughts:m}),{result:l,elementWasFound:u}}catch(p){if(c)return l={success:!0,thoughts:`The element described does not exist on the page: ${p.message}`,err:void 0,data:void 0},{result:l,elementWasFound:u};if(!(p instanceof x)||p.reason!="ActionFailureError")throw p;return l={success:!1,err:p,data:void 0,thoughts:void 0},s.warn({err:p},"Element check did not find an element and failed"),{result:l,elementWasFound:u}}}async function RB(r,{command:e,fixtures:t}){let n=e.assertion;await t.browser.highlight(r);let o=!0,i,a;switch(n.type){case"ELEMENT_CONTENT":{let c=await r.textContent()??"";if(a={elementTextContent:Nt(c,500,!0)},!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,i=new x("AssertionFailureError",`The content ${l} '${n.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Nt(await r.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await r.getAttribute(n.attr,{timeout:3e3})??""}catch(l){i=new x("AssertionFailureError",`The element does not have an attribute named ${n.attr}: ${l}`),o=!1;break}if(!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,n.operation==="EXISTS"?i=new x("AssertionFailureError",`The attribute ${n.attr} ${l}`):i=new x("AssertionFailureError",`The attribute ${n.attr} ${l} '${n.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(n.condition){case"VISIBLE":{o=await r.evaluate(async(l,u)=>{let d=Date.now();for(;Date.now()-d<u;){await new Promise(g=>setTimeout(g,250));let p=l.getBoundingClientRect();if(!(p.width===0||p.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},wr*1e3);break}case"EDITABLE":{o=await r.isEditable({timeout:wr*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await r.isEnabled({timeout:wr*1e3});break}case"FOCUSED":{o=await r.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.condition)}if(o=n.negated?!o:o,!o){let c=n.negated?CA[n.condition]:xA[n.condition];i=new x("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await r.evaluate(l=>l.tagName);if(!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,i=new x("AssertionFailureError",`The element tag name ${l} '${n.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await r.evaluate((l,u)=>window.getComputedStyle(l).getPropertyValue(u),n.property);if(!Jc(c,n.value,n.operation,!!n.negated)){let l=n.negated?wn[n.operation]:Rn[n.operation];o=!1,n.operation==="EXISTS"?i=new x("AssertionFailureError",`The style property ${n.property} ${l}`):i=new x("AssertionFailureError",`The style property ${n.property} ${l} '${n.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{success:o,data:a,err:i}}function Jc(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r.trim()===e.trim();break}case"STARTS_WITH":{o=r.trim().startsWith(e);break}case"EXISTS":{o=r.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}function CB(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&(r.condition==="EXISTS"||r.condition==="VISIBLE")}function KR(r){return r.type==="ELEMENT_EXISTENCE"&&r.negated&&r.condition==="EXISTS"}import{Jimp as xB}from"jimp";async function os(r,e){let t=await r.screenshot(e),n=await xB.fromBuffer(t);return{buffer:t,width:Math.ceil(n.bitmap.width??0),height:Math.ceil(n.bitmap.height??0)}}import{Jimp as YR}from"jimp";import yg from"jpeg-js";import MB from"pixelmatch";async function XR({ctx:r,tracer:e,command:t,disableCache:n,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!an(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 Te=>os(o,{locator:Te.locator,...c}),options:{...t,disableCache:n,disableGlobalLocatorRedirect:!0,memory:t.cache?.target?.memory,targetName:"target"}})).result:l=await os(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 ee=`${l.width}x${l.height}`,Te=`${u.width}x${u.height}`;return{fail:!0,thoughts:`Current screenshot (${ee}) does not match saved screenshot dimensions (${Te}) - 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 YR.fromBuffer(l.buffer),p={width:l.width,height:l.height},g=await YR.fromBuffer(u.buffer),m={width:u.width,height:u.height},h,f=p.width*p.height,E=m.width*m.height,b=Math.abs(p.height-m.height),R=Math.abs(p.width-m.width);if(f>E){let ee=d.cover({w:m.width,h:m.height});l.buffer=await ee.getBuffer("image/jpeg"),h="current",l.width=m.width,l.height=m.height}else if(E>f){let ee=g.cover({w:p.width,h:p.height});u.buffer=await ee.getBuffer("image/jpeg"),h="saved"}let A={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},T=t.threshold??.1,w=MB(yg.decode(u.buffer).data,yg.decode(l.buffer).data,A.data,l.width,l.height,{threshold:T,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,D=w>T*100,G=`Visual diff of ${w.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${T*100}%.`;if(h&&(G+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${R} pixels.`),D)throw new x("ActionFailureError",G);return{fail:D,thoughts:G,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:yg.encode(A,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var _B=3e4;async function Zc({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??_B/1e3,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,m])=>g&&m)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([g,m])=>g&&m).forEach(([g,m])=>{a.append(g,m)});let s=a.toString(),c;if(mi(r.url)&&(c=r.url),t&&gi(r.url,t)&&(c=new URL(r.url,t).toString()),!c)throw new x("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{return await n(g,{headers:i,method:r.method,body:r.body})}catch(m){throw e.error({err:m},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${m}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new x("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!u.ok){let g;try{g=await u.text()}catch(m){g=`Failed to read response body: ${m}`}throw new x("ActionFailureError",`Fetch request failed with status ${u.status}: ${g}`)}let d={};u.headers.forEach((g,m)=>{d[m]=g});let p={status:u.status,headers:d};if(u.headers.get("content-type")?.includes("json"))try{p.json=await u.json()}catch{}else u.headers.get("content-type")?.includes("text")&&(p.text=await u.text());return p}var PB=5e3;async function ZR({timeout:r=wr,...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 Qc(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 X(s,e.signal),s=Math.min(Math.floor(s*1.5),PB);else return i}return i=await Qc(e),i}async function Qc({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(JR,{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(JR,{value:r.value,negated:!!r.negated,returnHtml:!0},"checking page content"));if(!i){let c=r.negated?wn.CONTAINS:Rn.CONTAINS;a=new x("AssertionFailureError",`The page ${c} '${r.value}'.`),o=s}}catch(s){a=new x("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 JR({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 IB=3e4;async function QR({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??IB/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([d,p])=>d&&p));a["Content-Type"]="application/json";let s;if(mi(r.url)&&(s=r.url),t&&gi(r.url,t)&&(s=new URL(r.url,t).toString()),!s)throw new x("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 x("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let d,p=await l.text();try{d=JSON.parse(p)}catch{throw new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}throw d?.errors?.length&&d?.errors[0]?.message?new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${d.errors[0].message}`):new x("ActionFailureError",`GraphQL request failed with status ${l.status}: ${p}`)}let u={};return l.headers.forEach((d,p)=>{u[p]=d}),{status:l.status,headers:u,json:await l.json()}}var eu=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([Hr(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 go({type:"ai-action",description:e,screenshot:u,serializedTree:c.serializedTree,tree:c.tree,options:{aiPageFiltering:!!this.options?.aiPageFiltering},fixtures:{generator:this.generator,signal:this.executeAbortController.signal,logger:s,orgId:this.orgId}}),p={url:this.browser.url(),browserState:d,startingScreenshot:t,history:n,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(p,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(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([Hr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=`data:image/jpeg;base64,${u.toString("base64")}`,p=await go({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:p,startingScreenshot:t,history:n,goal:e,actionHint:o,screenshot:d};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...ge(a)},langfuseSessionId:s})}catch(m){throw new x("InternalWebAgentError",`Error generating command: ${m instanceof Error?m.message:m}`,{errOptions:{cause:m}})}}async getBrowserState(e){return Hr(this.browser,e)}async locateElement(e){return await Sg({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,t){return ur({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 p=i[d],g=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:p,cache:a[d],action:async m=>m,options:{...c,targetName:o[d]}});u.push(g)}try{let d=await s(...u.map(m=>m.result)),p=m=>m==="fromTarget"?"From Target":m==="toTarget"?"To Target":"Target",g=u.map((m,h)=>m.thoughts?`${p(o[h])}: ${m.thoughts}`:void 0).filter(m=>!!m).join(" -------------- ")||void 0;return{result:d,elementInteractedDisplayStrings:u.map(m=>m.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 x("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 ur({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&&ed(i)){t.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&(nd(i)||td(i))){t.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(od(i)){t.warn({err:i},"Invalid backend node id error, retrying element targeting command");continue}if(i instanceof xr&&i.retryableWithAI){t.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw n instanceof x?n:new x("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 x("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 X(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:p,source:g}=s,m=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,E=!1,b=eC(e.cache);if((!b||l)&&!Fu(o))throw new x("ActionFailureError","Cannot target element with no cached data or element descriptor");if(u)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(m.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&&!HR(o.elementDescriptor,b.inputDescription)&&(m.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),E=!0,b=void 0);let R=T=>!!T&&xs(T),A=!0;if(!R(b)){A=!1,m.info({description:o.elementDescriptor,targetHealingInProgress:p,cacheBustedBeforeAction:E,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),(E||!i)&&await jR({description:o.elementDescriptor,iframeUrl:s.iframeUrl,source:g,logger:m,allowNotActionableNodesOverride:s.allowNotActionableNodesOverride},this.getControllerFixtures(t)),f--;let T;try{T=await Sg({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:m},this.getControllerFixtures(t))}catch(D){if(D instanceof Do&&D.updatedLocatorMemory){let G={id:-1,...i,memory:D.updatedLocatorMemory};Cc({cmd:c,key:d,newTarget:G,logger:m,updatedWithAI:!0})}throw new x("ActionFailureError",D.message)}T.frameConfig&&this.browser.setActiveFrameConfig(T.frameConfig);let _=s.disableGlobalLocatorRedirect?{locator:T.resolution.locator}:await this.attemptLocatorRedirect(T.resolution.locator,m),w=await a(_);return Cc({cmd:c,key:d,newTarget:T.target,logger:m,updatedWithAI:!0}),p&&(n.recordTargetAutoHeal({healType:"AI"}),T.target.targetSource="AI_HEALED",T.target.targetUpdateTime=new Date().toUTCString(),T.target.targetUpdateLoggerTags=ge(m)),{result:w,elementInteractedDisplayString:T.resolution.displayString,thoughts:T.thoughts}}try{let T=await this.browser.resolveTarget(t,b,{allowNotActionableNodesOverride:s.allowNotActionableNodesOverride,targetName:d,logger:m,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect!==!1)&&await this.browser.scrollIntoViewIfNeeded(T.locator);let _=s.disableGlobalLocatorRedirect?{locator:T.locator}:await this.attemptLocatorRedirect(T.locator,m),w=await a(_);if(yt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.8.0"]),Cc({cmd:c,key:d,newTarget:b,logger:m,updatedWithAI:!1}),A){let D=T.decisions.filter(G=>G.matched);if(D.length!==1)m.warn({decisions:T.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let G=D[0].type;n.recordTargetAutoHeal({healType:G})}}return{result:w,elementInteractedDisplayString:T.displayString}}catch(T){this.throwIfClosed();let _="unknown";T instanceof Cr&&T.cacheMissReason&&(_=T.cacheMissReason),yt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:web",`hasRequirements:${!!b.requirements}`,`hasAdditionalElements:${!!b.additionalElements}`,`orgId:${this.orgId}`,"cliVersion:0.8.0",`missReason:${_}`]);let w=!1;if((T instanceof xr||ed(T)||nd(T)||od(T)||Df(T)||td(T)||kf(T))&&(w=!0),T instanceof x&&!w)throw m.error({err:T},"Failed to execute action with cached target (fatal)"),T;if(f>0&&o){m.info({err:T},"Failed to execute action with cached target, retrying with AI");let D;return b.memory&&Ah(b.memory)&&(D=b.memory),this.wrapElementTargetingCommand({ctx:t,tracer:n,command:c,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:D,retriesWithAI:f,targetHealingInProgress:!0}})}throw new x("ActionFailureError",T.message,{errOptions:{cause:T}})}}async attemptLocatorRedirect(e,t){return this.browser.userBrowserSettings.globalLocatorRedirect!==!1?this.browser.performTargetRedirection(e,t):{locator:e}}async screenshotWithDimensions(e){return os(this.browser,e)}async executePresetCommand(e,t,n,o,i){this.options?.slowMoMs&&await X(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 x("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&&Qh(n)?await this.browser.waitForDOMStability({timeout:he}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(n.type)&&await this.browser.waitForDOMStability({timeout:te}),this.options?.autoFollowNewTabs&&await OR({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{Rc(n,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>Gm(e)}}async resolveCommandTemplateStrings(e,t){return wc({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()?Yc({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 x("ActionFailureError","Missing assertion");if(n.timeout&&n.timeout>1800)throw new x("AssertionFailureError",`AI check timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);return Yc({command:n,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!n.goal.trim())throw new x("ActionFailureError","Cannot perform AI extraction without goal");if(n.schema){let f=Db(n.schema);if(f)throw new x("UserConfigurationError",f)}let m=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:n.goal,browserState:m,returnSchema:n.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:ge(a)});if(f.result==="NOT_FOUND")throw new x("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new x("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 x("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 x("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(!mi(n.url)&&!gi(n.url,this.browser.baseUrl))throw new x("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:m=>this.browser.click(m,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 m,h;if(n.target&&Ar(n.target))await this.browser.hoverUsingVisualCoordinates(n.target.pixels);else if(n.target&&n.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:A=>this.browser.hover(A),options:{...n,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});m=b,h=R}let f=this.browser.getViewport()?.height??un.height,E=this.browser.getViewport()?.width??un.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:m,thoughts:h}}case"WAIT_FOR_URL":{if(n.timeout&&n.timeout>1800)throw new x("UserConfigurationError",`Wait for URL timeout of ${n.timeout} exceeds the maximum allowed value of 30 minutes.`);let m=n.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:m},{timeout:n.timeout?n.timeout*1e3:void 0,negated:n.negated,caseInsensitive:n.caseInsensitive});break}case"WAIT":if(n.delay>1800)throw new x("UserConfigurationError",`Wait timeout of ${n.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=n.delay*1e3;await X(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"CLICK":{if(Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n);break}let m=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:R=>this.browser.click(R,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 Oc(m,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(Ar(n.fromTarget)&&Ar(n.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(n.fromTarget.pixels,n.toTarget.pixels,{hoverSeconds:n.hoverSeconds});break}if(Ar(n.fromTarget)||Ar(n.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:m,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:m[0],thoughts:h}}case"MOUSE_DRAG":{let m=parseInt(n.deltaX),h=parseInt(n.deltaY),f=n.steps??5;if(isNaN(m)||isNaN(h))throw new x("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${n.deltaX}, ${n.deltaY})`);if(n.target&&Ar(n.target)){await this.browser.mouseDragUsingVisualCoordinates(m,h,f,n.target.pixels,{force:n.force});break}let E,b;if(n.target?.elementDescriptor){let{elementInteractedDisplayString:R,thoughts:A}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:n.target,cache:n.cache?.target,action:async T=>this.browser.mouseDrag(m,h,f,T.locator,{force:n.force}),options:{disableCache:i,targetName:"target",...n}});E=R,b=A}else await this.browser.mouseDrag(m,h,f,void 0,{force:n.force});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}case"SELECT_OPTION":{if(!an(n.target))throw new Error("Select with x/y is not supported yet");let m=n.target.elementDescriptor,h=n.choice,{elementInteractedDisplayString:f,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:t,command:n,target:{type:"description",elementDescriptor:m},cache:n.cache?.target,action:b=>this.browser.selectOption(b,h,n.force),options:{...n,targetName:"target",disableCache:i,source:na(n)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:E}}case"TAB":{let m={loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(n.action,m);break}case"NEW_TAB":await this.browser.createNewTab(n.url,{loadTimeoutMs:n.loadTimeout?n.loadTimeout*1e3:void 0});break;case"COOKIE":if(!n.value)break;let 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 m;try{n.environment==="BROWSER"?(m=await this.browser.evaluateCodeInPage({code:n.code,fragment:n.fragment??!1,context:o.toObjectCopy(),timeoutMs:n.timeout?n.timeout*1e3:void 0}),a.info({result:m},"Executed JavaScript in browser")):m=await Ur({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 x("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(m)}catch(h){throw new x("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{if(n.target&&Ar(n.target)){await this.browser.clickUsingVisualCoordinates(n.target.pixels,n),await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);break}let m=this.browser.url(),h,f,E=eC(n.target),b=this.browser.userBrowserSettings.globalLocatorRedirect===void 0||this.browser.userBrowserSettings.globalLocatorRedirect==="always";if(E){let{elementInteractedDisplayString:A,thoughts:T}=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:na(n)}});h=A,f=T}else await this.browser.type(n.value,{force:n.force,clearContent:n.clearContent,forceClearContent:n.forceClearContent,delay:n.delay,pressEnter:n.pressEnter},!0);let R={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Oc(m,R.urlAfterCommand)&&(R.succeedImmediately=!0,R.succeedImmediatelyReason="URL changed"),R}case"HOVER":{if(Ar(n.target)){await this.browser.hoverUsingVisualCoordinates(n.target.pixels);break}let{elementInteractedDisplayString:m,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:m,thoughts:h}}case"FOCUS":{if(!an(n.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,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:m,thoughts:h}}case"BLUR":{if(n.target&&!an(n.target))throw new Error("Blur with x/y is not supported yet");if(!n.target||!n.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:m,thoughts: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:m,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(n.value,{repeat:n.repeat,convertMeta:n.convertMeta??!0,delayMs:n.delayMs});let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Oc(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"KEY_DOWN":return await this.browser.keyDown(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(n.value,{convertMeta:n.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let m=new LB,h=OB(fetch,m),f;try{f=new URL(n.url).hostname}catch{}return{data:{...await Zc({command:n,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:el(m,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await QR({command:n,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return XR({ctx:e,tracer:t,command:n,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m,h;if(n.fileSource.type==="URL"?(h=n.fileSource.url,m=await vw({uri:n.fileSource.url,logger:a,orgId:this.orgId})):n.fileSource.type==="USER_FILE"&&(h=n.fileSource.name,m=await this.uploadedFileStorage?.getFileForUpload(n.fileSource.name,this.orgId)),!m)throw new x("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...m,filename:n.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m;if(!n.storageState.trim())m=void 0;else if(m=await Ur({orgId:this.orgId,code:n.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof m!="object")throw new x("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=ry.optional().parse(m)}catch(f){throw new x("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let m=(n.timeout??wr)*1e3,h=this.generator.getAgentConfig()?.assertion;if(KR(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 Yc({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&&Za(n,E.cache?.memory.traces,a)}}let f=await qR({command:n,tracer:t,timeoutMs:m,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 m=await ur({action:async()=>ZR({assertion:n.assertion,browser:this.browser,logger:a,timeout:n.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:n.iframeUrl?{type:"url",url:n.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!m.success,data:m.data,thoughts:m.success?"Page assertion passed.":m.err?.message??`Page assertion still failing after ${n.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let m=new _n(n.requestMatcher),h=this.browser.registerRequestListener(m);return this.registeredListeners[n.key]=h.then(async f=>await Km(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let m=this.registeredListeners[n.key];if(!m)throw new x("ActionFailureError",`No listener registered with key: ${n.key}`);let h=n.timeout??10;return{data:await k(m,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let m=new _n(n.requestMatcher);return this.recordedRequests[n.key]={},this.browser.registerRequestRecorder(n.key,{matches:h=>m.matches({url:h.request.url,method:h.request.method}),onRequestStart:(h,f)=>{this.recordedRequests[n.key][h]=Fc(f)},onRequestComplete:(h,f)=>{this.recordedRequests[n.key][h]=Fc(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let m=this.recordedRequests[n.key];if(!m)throw new x("ActionFailureError",`No recorder registered with key: ${n.key}`);return delete this.recordedRequests[n.key],{data:Object.values(m),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let m;return n.requestMatcher&&(m=new _n(n.requestMatcher)),this.browser.setHeader(n.name,n.value,m),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(n.key,new _n(n.requestMatcher),async(h,f)=>{let E=await Ur({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=Ey.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(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:t,disableCache:n,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:t,screenshot:o},{disableCache:n,abortSignal:this.executeAbortController.signal,loggerTags:ge(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 jc({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:ge(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:ge(this.logger)})}};import{cloneDeep as NB}from"lodash-es";import iC from"truncate-json";var tC=1e3,rC=5e6,DB=5*1024*1024;function aC(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=iC(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":nC(n);break;case"MOBILE_AI_ACTION_STEP":case"MOBILE_MODULE_STEP":nC(n),aC(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 nC(r){if(r.type==="MOBILE_PRESET_STEP"){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}}function oC(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 tu(r,e){let t=NB(r);if(aC(t,e),t.length>tC)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,tC);let n=oC(t,e);if(n.length>rC)for(e.error({serializedLength:n.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");n.length>rC;)t.pop(),n=oC(t,e);let{jsonString:o}=iC(n,DB);try{return rr.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 kB}from"async_hooks";var is=new kB;function UB(r){is.enterWith({activeTracers:[r]})}function FB(r,e){let t=is.getStore()?.activeTracers;if(!t)return e();t.push(r);try{return e()}finally{t.pop()}}async function BB(r,e){let t=is.getStore()?.activeTracers;if(!t)return e();let n=[...t,r];return is.run({activeTracers:n},e)}var Qr={globalAls:is,initializeRootTracerContext:UB,withChildTracer:FB,withChildTracerAsync:BB};var ho=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 Qr.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 Qr.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 Qr.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 ce(){let r=Qr.globalAls.getStore()?.activeTracers,e;return!r||r.length===0?e=void 0:e=r[r.length-1],e||new ho}async function sC(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=zB(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 zB(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 iz}from"fs";import{tmpdir as az}from"os";import mC from"path";import{diff as nz}from"deep-object-diff";import{cloneDeep as oz}from"lodash-es";import uC from"fontoxpath";import HB from"@prettier/plugin-xml";import GB from"prettier";import{DOMParser as VB,XMLSerializer as jB}from"slimdom";var WB=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 as(r){let e=r.toLowerCase();return e.endsWith("webview")||WB.has(e)}function $B(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 qB=new Set(["index","package","a11y-important","screen-reader-focusabl"]),KB=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"]),YB=new Set(["text","hint"]),XB=new Set(["live-region","drawing-order"]),JB=new Set(["displayed","enabled"]);function ZB(r,e){let t={};for(let[n,o]of Object.entries(e))qB.has(n)||n==="class"&&r===o||n==="focusable"&&o==="true"&&e.clickable==="true"||KB.has(n)&&o==="false"||YB.has(n)&&o===""||JB.has(n)&&o==="true"||XB.has(n)&&o==="0"||n!=="id"&&(t[n]=o);return t}function lC(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 p of e.attributes){let g=p.name,m=p.value;m!=null&&(l[g]=String(m))}let u=ZB(e.tagName,l);for(let[p,g]of Object.entries(u))t.setAttribute(p,g);if(o.set(c,e),i.set(c,t),as(e.tagName)){let p=s?.injectedWebviewContent??"";if(s?.removeWebviewContent){for(;t.firstChild;)t.removeChild(t.firstChild);return}else if(!s?.disableMomenticAccessibilityTree&&p.trim().length>0){for(;t.firstChild;)t.removeChild(t.firstChild);p.trim().length>0&&t.appendChild(n.createCDATASection(`
|
|
4176
|
+
${p}
|
|
4177
|
+
`));return}}let d=Array.from(e.childNodes??[]);for(let p of d){let g=p.nodeType;if(g===3){let m=p.nodeValue;m&&m.trim().length>0&&t.appendChild(n.createTextNode(m));continue}if(g===1){let m=p;if(!tz(m,s?.viewportBounds))continue;let h=n.createElement($B(m.tagName));lC(r,m,h),t.appendChild(h)}}}function QB(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;lC(a,e,s);let c=new jB().serializeToString(o);return{prunedDocument:o,prunedIdToElement:i,xml:c}}async function cC(r,e){let t=new VB,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}=QB(t,i,o,e);return{xml:await GB.format(c,{parser:"xml",plugins:[HB],printWidth:120,tabWidth:1,singleAttributePerLine:!1}),originalXml:r,document:n,idToElement:o,prunedDocument:a,prunedIdToElement:s}}function ez(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 ru(r,e){let t=r.idToElement.get(e);if(t)return ez(t)}function bg(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 fo(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 tz(r,e){if(!e)return!0;let t=fo(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 Eg(r,e){if(r&&!(!e||e.length===0))return Object.fromEntries(e.map(t=>[t,r.getAttribute(t)]).filter(([,t])=>t!==null))}function pC({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=fo(n);if(!o)throw new Error(`Node ${r.id} has no bounding box: ${n.outerHTML}`);let i=ru(t.graph,r.id)??"",a=bg(t.graph,r.id)??"",s=t.graph.idToElement.get(r.id),c=Eg(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:m})=>{let h=t.graph.idToElement.get(g);if(!h)return;let f=ru(t.graph,g);return f?{xPath:f,requirements:{requiredText:m.textRequired?h.getAttribute("text")??void 0:void 0,requiredAttributes:Eg(h,m.attributesRequired),requiredBounds:m.boundsRequired}}:void 0}).filter(g=>!!g));let p;return as(n.tagName)&&r.inWebview!==!1?p={type:"WEBVIEW",resolvedDescription:e,xPath:i}:p={type:"NATIVE",bounds:o,resolvedDescription:e,xPath:i,elementOnlySerializedXml:a,requirements:u,requiredRelatedElements:d},p}var dC=(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=fo(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 nu(r){let{target:e,domState:t}=r,{graph:n}=t,{document:o}=n,i=ce();if(e.type==="WEBVIEW")return rz(e,r);let a=uC.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 p=e.requiredRelatedElements;i.startSection("Validate related elements are similar enough to past runs",()=>{for(let g of p){let m=uC.evaluateXPathToFirstNode(g.xPath,o);if(!m)throw new Error(`ActionFailureError: Required related element not found for XPath: ${g.xPath}`);dC(m,g.requirements)}})}let s=fo(a);if(!s)throw new Error("ActionFailureError: Resolved native element has no bounding box");dC(a,e.requirements,e.bounds);let c;for(let[p,g]of n.idToElement.entries())if(g===a){c=p;break}let l=e.elementOnlySerializedXml,u=e.xPath;return c!==void 0&&(l=bg(n,c)??l,u=ru(n,c)??u),{resolvedTarget:{...e,bounds:s,elementOnlySerializedXml:l,xPath:u}}}async function rz(r,e){let{stateManager:t,logger:n,signal:o}=e,i=ce(),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 Ti(r){let{command:e,cacheKey:t="cache",targetName:n="target",updatedCache:o}=r;il(e)&&(e[t]={...e[t],[n]:tl.parse(o)},r.updatedWithAI&&(e[t].updatedAt=new Date))}function ou(r){return r.type==="WEBVIEW"?{type:"WEBVIEW",resolvedDescription:r.resolvedDescription,xPath:r.xPath,browserCache:r.browserCache}:r}var pt=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}){await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before locating an element with AI"});let n=await t.startAsyncSection("Get emulator state",async()=>{let c=await this.stateManager.getDomState(),l=await this.stateManager.getCurrentScreenshotPngString();return{emulatorState:c,screenshot:l}}),o;try{o=await t.startAsyncSpan("AI_LOCATOR_CALL",async c=>{let l=await this.generator.getElementLocation({description:e,screenXml:n.emulatorState.graph.xml,screenshot:n.screenshot},{logger:this.logger,loggerTags:ge(this.logger),abortSignal:this.aborter.controller?.signal});return c.result=l,l})}catch(c){throw this.throwIfAborted(),this.logger.error({err:c},"Failed to locate element"),new Error(`ActionFailureError: Failed to locate element: ${c instanceof Error?c.message:c}`)}if(o.id===-1)throw new Error(`NoMatchingElementError: ${o.thoughts}`);let i=pC({aiResponse:o,description:e,emulatorState:n.emulatorState});if(i.type==="NATIVE")return t.addSpan({type:"TARGET_RESOLUTION",startTime:Date.now(),endTime:Date.now(),result:{serializedElement:i.elementOnlySerializedXml},attributes:{}}),{resolvedTarget:i,thoughts:o.thoughts};let{browserLocateResult:a,browserController:s}=await t.startAsyncSpan("TARGET_RESOLUTION",async c=>{let l=await this.stateManager.getActiveWebview();if(!l||!l.browserController)throw new Error("No browser controller is attached to the requested webview");let u=await l.browserController.locateElement({description:e,disableCache:!1,logger:this.logger});return c.result={serializedElement:u.target.nodeOnlySerializedHtml??"Unknown HTML element in webview"},{browserLocateResult:u,browserController:l.browserController}});return{resolvedTarget:{...i,controller:s,resolution:a.resolution,browserCache:a.target},thoughts:a.thoughts}}async wrapTargetingAction(e){let{action:t,description:n,command:o,cacheKey:i="cache",targetName:a="target",cacheIsInvalidAfterResolution:s,tracer:c}=e,l=i in o&&o[i]&&a in o[i]?o[i][a]:void 0,u=e.retriesWithAI??1,d=!1,p=oz(l),g;if(o.disableCache&&(this.logger.debug({command:o},"Cache explicitly disabled for command"),d=!0,p=void 0),s&&(d=!0,p=void 0),p&&p?.resolvedDescription!==n&&(this.logger.info({description:n,cacheDescription:p?.resolvedDescription},"Cache description mismatch, clearing it automatically"),d=!0,p=void 0),!p){u--,this.logger.info({description:n,cacheBustedBeforeAction:d},"Prompting AI for a new element location");let h=await this.findElement({description:n,tracer:c});g=h.thoughts;let f=await t(h.resolvedTarget);return Ti({command:o,cacheKey:i,targetName:a,updatedCache:h.resolvedTarget,updatedWithAI:!0}),{result:f,thoughts:g}}let m;try{await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.aborter.controller?.signal,reason:"Waiting for stability before cache resolution"}),m=await this.stateManager.getDomState();let{resolvedTarget:h,updatedCache:f}=await c.startAsyncSection("Resolve target cache",async(b,R)=>{let{resolvedTarget:A}=await nu({target:p,domState:m,stateManager:this.stateManager,logger:this.logger}),T=ou(A),_=nz(p,T);return _&&Object.keys(_).length>0&&this.logger.info({cacheDiffs:_},"Successfully resolved target with cache"),R.attributes.serializedElement=A.type==="WEBVIEW"?A.browserCache?.nodeOnlySerializedHtml??"Unknown HTML element in webview":A.elementOnlySerializedXml,{resolvedTarget:A,updatedCache:T}}),E=await t(h);return Ti({command:o,cacheKey:i,targetName:a,updatedCache:f,updatedWithAI:!1}),p.type!=="WEBVIEW"&&yt.increment("cache_target_resolution_v2",1,["outcome:hit","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.8.0"]),{result:E,thoughts:"Successfully executed preset action with cache."}}catch(h){if(p.type!=="WEBVIEW"&&yt.increment("cache_target_resolution_v2",1,["outcome:miss","platform:native",`hasRequirements:${!!p.requirements}`,`hasAdditionalElements:${!!p.requiredRelatedElements?.length}`,`orgId:${this.orgId}`,"cliVersion:0.8.0"]),this.throwIfAborted(),u>0)return this.logger.warn({err:h},"Failed to resolve target cache, retrying with AI"),this.wrapTargetingAction({...e,cacheIsInvalidAfterResolution:!0,retriesWithAI:u-1});throw new Error(`ActionFailureError: ${h instanceof Error?h.message:h}`,{cause:h})}}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}}}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==="down"?t-a:t+a:s=o==="right"?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 sz(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 vi=class extends pt{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,p=o+u;return await this.tapOnAbsoluteCoordinates({x:d,y:p,...t}),{x:d,y:p}}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=mC.join(az(),"momentic","downloads"),s=mC.join(a,this.orgId,i);return iz(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 ce().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=ce(),n=sz(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 Ln=class extends pt{async doPress({keycode:e,longPress:t}){await ce().startAsyncSpan("EMULATOR_INTERACTION",async()=>this.driver.executeScript("mobile: pressKey",[{keycode:e,isLongPress:t}]),{name:"Send key events to emulator"})}};var gC=25,iu=class extends pt{async doType(e){let t=ce();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:void 0}}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 ce().startAsyncSpan("EMULATOR_INTERACTION",async o=>{o.withinWebview=!0;let i={clearContent:e.clearContent,forceClearContent:e.forceClearContent,delay:e.keyPressDelayMs??gC};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 vi(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=ce(),n=e.keyPressDelayMs??gC;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=ce();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 Ln(this.constructPerformerParams()).doPress({keycode:67})}};import jt from"zod";var Tg=.8,Ai=.2,lz=jt.object({navigationBar:jt.object({visible:jt.boolean(),x:jt.number(),y:jt.number(),width:jt.number(),height:jt.number()}),statusBar:jt.object({visible:jt.boolean(),x:jt.number(),y:jt.number(),width:jt.number(),height:jt.number()})}),wi=class extends pt{async getHardcodedScrollableElementBounds(e,t){let n;switch(e.type){case"SCREEN":n=this.getInsetBoundsFromViewport(t);break;case"OPEN_APP":try{let o=lz.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*Ai),n=Math.floor(e.height*Ai);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*Ai),l=Math.floor(s*Ai);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=ce();if(e.scrollableElement.type==="CUSTOM_COORDINATES"){let{startX:n,startY:o,deltaPixels:i}=e.scrollableElement;return await t.startAsyncSpan("EMULATOR_INTERACTION",async a=>{a.attributes.startX=n,a.attributes.startY=o,a.attributes.deltaPixels=i,a.attributes.direction=e.direction,await this.performRawSwipe({startX:n,startY:o,deltaPixels:i,direction:e.direction,durationMs:e.durationMs})},{name:`Swipe ${e.direction} using raw coordinates`}),{success:!0}}if(e.scrollableElement.type!=="CUSTOM"){let n=await this.driver.getWindowRect(),o=await this.getHardcodedScrollableElementBounds(e.scrollableElement,n);return await t.startAsyncSpan("EMULATOR_INTERACTION",async i=>{await this.swipeByAbsoluteCoordinates({span:i,direction:e.direction,percent:e.viewportPercent,durationMs:e.durationMs,containerBounds:o})},{name:`Swipe ${e.direction} in the entire ${e.scrollableElement.type.toLowerCase()}`}),{success:!0}}return await this.wrapTargetingAction({command:e,description:e.scrollableElement.target.description,action:async n=>ce().startAsyncSpan("EMULATOR_INTERACTION",async i=>"type"in n&&n.type==="NATIVE"?this.scrollInNativeContainer({span:i,cmd:e,target:n}):(i.withinWebview=!0,this.scrollInWebview({cmd:e,target:n})),{name:`Swipe ${e.direction} in the specified container`}),tracer:t}),{success:!0}}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*Ai),s=Math.floor(i*Ai);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 scrollInWebview({cmd:e,target:t}){let{controller:n}=t,o=n.browser.getViewport();if(!o)throw new Error("Failed to get viewport size from webview");if(e.direction==="down"||e.direction==="up"){let i=o.height*(e.viewportPercent??Tg)*(e.direction==="down"?1:-1);await n.browser.scrollVertical(i)}else{let i=o.width*(e.viewportPercent??Tg)*(e.direction==="right"?1:-1);await n.browser.scrollHorizontal(i)}}async swipeByAbsoluteCoordinates({span:e,direction:t,percent:n=Tg,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 SC}from"child_process";import dz from"pixelmatch";import{_android as pz,chromium as mz}from"playwright";import{PNG as yC}from"pngjs";import{z as Ke}from"zod";var hC=Ke.array(Ke.object({proc:Ke.string(),webview:Ke.string(),info:Ke.object({"Android-Package":Ke.string(),Browser:Ke.string(),"Protocol-Version":Ke.string(),"User-Agent":Ke.string(),"V8-Version":Ke.string(),"WebKit-Version":Ke.string(),webSocketDebuggerUrl:Ke.string()}),pages:Ke.array(Ke.object({description:Ke.string(),devtoolsFrontendUrl:Ke.string(),id:Ke.string(),title:Ke.string(),type:Ke.string(),url:Ke.string(),webSocketDebuggerUrl:Ke.string()})),webviewName:Ke.string()}));function vg(r,e,t=.01){let n=Buffer.from(r,"base64"),o=Buffer.from(e,"base64"),i=yC.sync.read(n),a=yC.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 dz(i.data,a.data,l,s,c,{threshold:t})/(s*c)*100}var au=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,p;if(l)p=l;else{t.warn("No playwright device provided, using ADB to find device");let m=(await pz.devices()).filter(h=>h._initializer?.serial?.endsWith(a.toString())||h._initializer?.serial?.endsWith((a-1).toString()));if(m.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(m.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.`);p=m[0]}return new r({driver:e,context:d,logger:t,device:p,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=ce(),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 ce().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(vg(c,u)<=o){l=!0;break}c=u,await X(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");(as(a.tagName)||n==="com.android.chrome"&&s==="Web View"&&a.tagName.toLowerCase().startsWith("frame"))&&o.push({id:i,originalElement:a,bounds:fo(a)})}return o}async getActiveWebviewContent(){let e=await this.getActiveWebview();if(!e||!e.browserController)return;this.throwIfAborted();let t=e.browserController;return(await ce().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 ce().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 o;if(e?.filterOffscreenElements??!0)try{let c=await this.driver.getWindowRect();o={left:c.x,top:c.y,right:c.x+c.width,bottom:c.y+c.height}}catch(c){this.logger.warn({err:c},"Could not get viewport bounds for off-screen filtering, continuing without filtering")}let a=await this.getPageSource();return{graph:await cC(a,{injectedWebviewContent:n,disableMomenticAccessibilityTree:this.options.disableMomenticAccessibilityTree,removeWebviewContent:e?.removeWebviewContent,viewportBounds:o}),context:this.currentContext}},{timeoutMs:15e3})}async getPageSource(){return await ce().startAsyncSpan("EMULATOR_READ_STATE",()=>this.driver.getPageSource(),{name:"Get Android page source",signal:this.aborter.controller?.signal})}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 ce().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=SC(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 ce().startAsyncSpan("EMULATOR_READ_STATE",async()=>{let t=await this.driver.execute("mobile: getContexts");this.aborter.controller?.signal.throwIfAborted();let n;try{n=hC.parse(t)}catch(o){throw new Error(`Failed to parse contexts. Original error:
|
|
4157
4178
|
${o}
|
|
4158
|
-
Raw: ${JSON.stringify(t)}`)}return n.filter(o=>{if(!o.webviewName)return!0;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||this.logger.debug({context:o},"Webview has no qualified pages, skipping"),i})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await ce().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await rs.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new eu({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Tl})})}async connectPlaywrightToWebview(e,t){return ce().startAsyncSection("Connect headless browser client to webview",async()=>this.connectPlaywrightToWebviewHelper(e,t),{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){this.logger.warn({webviews:n.map(l=>({pkg:l.pkg,name:this.extractSocketNameFromWebview(l,this.logger)}))},`Could not find webview for ${e} with socket name ${t}`);return}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){this.logger.warn({pageUrl:a},`Webview ${e} with socket ${t} is not a valid webview`);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await ce().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 sz.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=JR(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 QR=5,eC=.8,lz=1,su=class extends Ti{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??eC,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=ce(),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=ce();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=ce(),a=e.scrollStepPercent??eC,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 nu({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 Error&&u.message.includes("NoMatchingElementError"))return null;throw u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),yi({command:e,updatedCache:ou(a),updatedWithAI:!0}),{success:!0,message:s}):(yi({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0}),{success:!0,message:s})}async searchForElement(e,t,n){let o=ce(),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<QR;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 p=cz(e.scrollableElement);l=await this.scrollByPage({direction:e.direction,containerBounds:s,scrollStepPercent:o,rawCoordinates:p}),a+=e.direction==="down"?c:-c}throw new Error(`ActionFailureError: Could not find element "${t}" after ${QR} 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 ce().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=ce(),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,p=m.height*i,g=this.calculateSwipeCoordinates({containerBounds:m,direction:o,desiredDelta:p});s=g.startX,c=g.startY,l=g.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 p=0;p<u;p++){this.throwIfAborted();let g=Math.abs(e)-m,h=Math.min(l,g);await this.performRawSwipe({startX:s,startY:c,deltaPixels:h,direction:o}),m+=h}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=lz,rawCoordinates:i}){let a=await this.stateManager.getRawScreenshotBase64(),s,c,l;if(i)s=i.startX,c=i.startY,l=i.deltaPixels;else{let p=t.height*n,g=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:p});s=g.startX,c=g.startY,l=g.actualDelta}await this.performRawSwipe({startX:s,startY:c,deltaPixels:l,direction:e});let u=await this.stateManager.getRawScreenshotBase64(),d=bg(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 cz(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as uz}from"crypto";import ss from"fs";import{tmpdir as dz}from"os";import vi from"path";var lu=class extends Ct{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 ${vi.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(ss.existsSync(n))o=n;else if(ss.existsSync(vi.join("/",n)))o=vi.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{ss.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=vi.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{ss.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=vi.extname(t)||".apk",o=vi.join(dz(),`momentic-apk-${uz()}${n}`);return ss.writeFileSync(o,e),o}};import{existsSync as mz,readFileSync as pz}from"fs";import gz from"zod";var hz=gz.string().url();async function tC(r){if(hz.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(!mz(r))throw new Error(`File does not exist at path: ${r}`);return pz(r).toString("base64")}var fz=5e3,cu=class extends Ct{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??wr)*1e3,i=o+1e4,a,s=0,c=500;for(;s-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}if(this.throwIfAborted(),a=await this.executeScreenCheckHelper(e),s=Date.now(),!a.success)await X(c,this.abortSignal),c=Math.min(Math.floor(c*1.5),fz);else return a}return a=await this.executeScreenCheckHelper(e),a}async executeScreenCheckHelper(e){return await ce().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":{let o=!1,i;try{let a=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!a)throw new Error("Failed to get screen HTML");o=a.includes(n.value)===!n.negated,a.length>1e4&&(a=a.slice(0,1e4)+"...TRUNCATED"),o||(i=new C("AssertionFailureError",`The screen ${wp(n)}.`),e.attributes.screenContent=a)}catch(a){i=new C("AssertionFailureError",`Failed to evaluate screen content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:o,err:i}}default:return n.type,{success:!1,err:new C("AssertionFailureError",`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 Qc({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};var Ai=class r extends Ct{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 au.init({driver:e,logger:n,fixtures:o,orgId:i,limbarClient:l,options:a?.emulator??{},aborter:d,adbPort:c,playwrightDevice:u}),p=new r({driver:e,generator:t,stateManager:m,logger:n,fixtures:o,options:a,aborter:d,orgId:i,adbPort:c});return await p.initializeSettings(),p}async installApp(e){await this.stateManager.executeRawADBCommand(`install ${yz.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await wc({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{Rc(e.command,n)}}async executeCommandHelper({command:e}){let t=ce();switch(e.type){case"TAP":return new bi(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new iu(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Ic(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 X(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 p=await t.startAsyncSpan("AI_ASSERTION_CALL",async g=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:m},{logger:this.logger,loggerTags:he(this.logger)});return g.result={thoughts:h.thoughts,result:h.result},h});if(p.result)return{success:p.result,message:p.thoughts};{let g=`AssertionFailureError: ${p.thoughts}`;u=new Error(g)}}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 Ti(this.constructPerformerParams()).executeSwipe(e);case"SCREEN_CHECK":return new cu(this.constructPerformerParams()).executeScreenCheck(e);case"SCROLL_TO":return new su(this.constructPerformerParams()).executeScrollTo(e);case"JAVASCRIPT":{let n=await Ur({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 bz,i=Sz(fetch,o),a=Date.now(),s=await Zc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=el(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 Ln(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(`
|
|
4159
|
-
`).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new Ln(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new Ln(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<5e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await X(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new lu(this.constructPerformerParams()).doInstallApk(e);case"ADD_FILE":{let n=await tC(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await HR({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){let{latitude:e,longitude:t}=this.options?.emulator?.geolocation??$s;await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_COARSE_LOCATION"]}),await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_FINE_LOCATION"]}),await this.driver.setGeoLocation({latitude:e,longitude:t})}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function rC({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:s,localToolsFactory:c,globalStateManager:l,settingsFactory:u}){let d=r.id,m=r.handshake.query?.testMetadata,p=r.handshake.query?.fileName,g=p?Ez.basename(p,".test.yaml"):"",h=Mr.parse(JSON.parse(m??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,x=h.settings?.defaultApkFilePath?.trim(),T=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:T});let O={...(await u(T,e)).emulator,...h.settings?.emulator},w;if(O.region==="local"){if(!O.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is local");w={avdId:O.localEmulatorSettings.avdId,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:x||void 0}}else w={region:O.region,apkToInstall:E?{channel:E,tag:b}:void 0,osVersion:O.remoteEmulatorSettings?.androidVersion};let D=Date.now(),{driver:j,cleanup:ie,emulatorName:ee,adbPort:fe,limbarClient:st,limbarToken:$,limbarUrl:B,playwrightDevice:ae}=await t({socket:r,logger:e,creationOpts:w}),ue=await Ac({driver:j,onLogs:To=>{r.emit("logcatLogs",To)}});e.info({adbPort:fe,apkChannel:E,apkTag:b,duration:Date.now()-D,emulatorName:ee},"Android emulator session initiated"),e=e.child({emulator:ee});let Ze=await o(T,e),Ce=await i(T,e),zt=await a(T,e),bt=await s(T),Ie=c?await c(T):void 0,qe={};h.settings?.defaultEnv&&(qe=(await bt.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let mr=new Ho({variablesFromEnvironment:qe,envName:h.settings?.defaultEnv,testName:g}),xt=await Ai.init({driver:j,generator:Ze,logger:e,limbarClient:st,playwrightDevice:ae,options:{emulator:O},fixtures:{storage:bt,browserEnricher:zt,browserGenerator:Ce,localCodeEvalTools:Ie,testContext:mr},orgId:T,adbPort:fe,abortController:new AbortController});if(!r.connected)throw await ue(),await ie(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Vr=Tz({socket:r,testContext:mr}),Eo=async()=>{clearInterval(Vr);try{await ue(),await ie(),await xt.cleanup()}catch(To){e.warn({err:To},"Failed to clean up emulator in socket server")}};return l.registerSession(d,{controller:xt,cleanup:Eo,emulatorName:ee,local:O.region==="local"}),r.emit("session",{testId:f,sessionId:d,limbarUrl:B,limbarToken:$}),{sessionId:d,testId:f,orgId:T,emulatorName:ee,logger:e,testName:g}}function Tz({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function nC({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var vz=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},oC={event:"cancel",createHandler:vz};var Az=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let s=await i.controller.getA11yTree();o({a11yTree:s})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},iC={event:"fetchA11yTree",createHandler:Az};import{diff as zz}from"deep-object-diff";import{cloneDeep as Hz}from"lodash-es";function aC(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let s=await k(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof s=="string"&&s.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${s}`)}catch(s){o++;let c=s instanceof Error?s.message:`${s}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function sC(r){let e=Date.now(),t=r.fixtures.controller;try{return await wz(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function wz({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await Rz({step:n,params:e}),s={};Object.entries(a).forEach(([m,p])=>{s[m]=JSON.stringify(p)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:s,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},l=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:l}});return c.steps=d,c.status=u,c.endTime=Date.now(),fA({result:c,...hA(d)}),c}async function Rz({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await Ur({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as lC}from"crypto";async function cC({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s;if(!t.interactive)try{s=await a.getScreenshotBase64()}catch(l){i.warn({err:l},"Failed to take before screenshot")}let c={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let l=await a.executeCommand({command:e.command});c={...e,status:l.success?"SUCCESS":"FAILED",message:l.message,startTime:o,endTime:Date.now(),data:l.output}}catch(l){l instanceof Error&&l.name==="AbortError"||a.isAborted()?c={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:l},"Failed to execute preset step"),c={...e,status:"FAILED",message:l instanceof Error?l.message:String(l),startTime:o,endTime:Date.now()})}finally{if(!t.interactive){try{let l=lC(),u=await a.getScreenshotBase64();c.afterSnapshot=l,n.attachAfterScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(u,"base64")})}catch(l){i.warn({err:l},"Failed to take after screenshot")}if(s){let l=lC();c.beforeSnapshot=l,n.attachBeforeScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(s,"base64")})}}}return c}import{streamText as kz}from"ai";import{randomUUID as Uz}from"crypto";var uu=class{controller;logger;callbacks;rootStep;subStepIndex=0;finalState=void 0;results=[];constructor(e){let{controller:t,logger:n,callbacks:o,rootStep:i}=e;this.controller=t,this.logger=n,this.callbacks=o,this.rootStep=i}async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let t=this.subStepIndex++,n=await this.callbacks.executeStep(e,t);return this.results.push(n),n}};import{hasToolCall as Nz,stepCountIs as Dz}from"ai";var uC="get_emulator_state",du="finish";import dC from"dedent";var xz=dC`
|
|
4179
|
+
Raw: ${JSON.stringify(t)}`)}return n.filter(o=>{if(!o.webviewName)return!0;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||this.logger.debug({context:o},"Webview has no qualified pages, skipping"),i})},{name:"Get available contexts",signal:this.aborter.controller?.signal})}async createBrowserController({context:e}){return await ce().startSection("Run remote Chrome initialization",async(n,o)=>{let i={};o.attributes.timings=i;let a=await ns.fromExistingContext({context:e,logger:this.logger,timingRecorder:i,userBrowserSettings:{visualActions:!0,disableBrowserMonitoring:!0},properties:{isNewHeadless:!0,allowedA11yIgnoreReasonsOverride:[],isAndroid:!0},storage:this.fixtures.storage,enricher:this.fixtures.browserEnricher});return new eu({browser:a,generator:this.fixtures.browserGenerator,logger:this.logger,orgId:this.orgId,storage:this.fixtures.storage,localCodeEvalTools:this.fixtures.localCodeEvalTools,visualDiffScreenshotStorage:new Tl})})}async connectPlaywrightToWebview(e,t){return ce().startAsyncSection("Connect headless browser client to webview",async()=>this.connectPlaywrightToWebviewHelper(e,t),{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){this.logger.warn({webviews:n.map(l=>({pkg:l.pkg,name:this.extractSocketNameFromWebview(l,this.logger)}))},`Could not find webview for ${e} with socket name ${t}`);return}let i=await o.page(),a=i.url();if(a===""||a.startsWith("about:blank")||a.startsWith("chrome-error:")){this.logger.warn({pageUrl:a},`Webview ${e} with socket ${t} is not a valid webview`);return}let s=i.context();return await this.createBrowserController({context:s})}async connectPlaywrightToChrome(e){return await ce().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 mz.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=SC(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 bC=5,EC=.8,gz=1,su=class extends wi{async executeScrollTo(e){let t=e.target.description,n=e.scrollStepPercent??EC,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=ce(),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=ce();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=ce(),a=e.scrollStepPercent??EC,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 nu({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 Error&&u.message.includes("NoMatchingElementError"))return null;throw u}return a.type==="WEBVIEW"?(await this.scrollWebviewTargetIntoView(a),Ti({command:e,updatedCache:ou(a),updatedWithAI:!0}),{success:!0,message:s}):(Ti({command:e,updatedCache:{...a,scrollDetails:o},updatedWithAI:!0}),{success:!0,message:s})}async searchForElement(e,t,n){let o=ce(),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<bC;u++){this.throwIfAborted();let d=this.buildScrollDetails(e,a,i.cache),p=await this.tryFindElement({cmd:e,description:t,tracer:n,scrollDetails:d});if(p)return p;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=hz(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 ${bC} 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 ce().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=ce(),s,c,l;if(t.type==="CUSTOM_COORDINATES")s=t.startX,c=t.startY,l=t.deltaPixels;else{let p=(await this.resolveContainer(t,n)).bounds,g=p.height*i,m=this.calculateSwipeCoordinates({containerBounds:p,direction:o,desiredDelta:g});s=m.startX,c=m.startY,l=m.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 p=0;for(let g=0;g<u;g++){this.throwIfAborted();let m=Math.abs(e)-p,h=Math.min(l,m);await this.performRawSwipe({startX:s,startY:c,deltaPixels:h,direction:o}),p+=h}},{name:`Scroll ${o} by ${e}px`})}async executeScrollGesture({direction:e,containerBounds:t,scrollStepPercent:n,diffThresholdPercent:o=gz,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,m=this.calculateSwipeCoordinates({containerBounds:t,direction:e,desiredDelta:g});s=m.startX,c=m.startY,l=m.actualDelta}await this.performRawSwipe({startX:s,startY:c,deltaPixels:l,direction:e});let u=await this.stateManager.getRawScreenshotBase64(),d=vg(a,u),p=d>o;return this.logger.debug({diffPercent:d,diffThresholdPercent:o,canScrollMore:p,direction:e,actualDelta:l,rawCoordinates:i},"Scroll gesture visual diff result"),p}};function hz(r){if(r.type==="CUSTOM_COORDINATES")return r}import{randomUUID as fz}from"crypto";import ls from"fs";import{tmpdir as Sz}from"os";import Ri from"path";var lu=class extends pt{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 ${Ri.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(ls.existsSync(n))o=n;else if(ls.existsSync(Ri.join("/",n)))o=Ri.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{ls.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=Ri.resolve(e);return this.assertFileExists(n),{localPath:n,cleanup:()=>{}}}throw t}}assertFileExists(e){try{ls.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=Ri.extname(t)||".apk",o=Ri.join(Sz(),`momentic-apk-${fz()}${n}`);return ls.writeFileSync(o,e),o}};import{existsSync as yz,readFileSync as bz}from"fs";import Ez from"zod";var Tz=Ez.string().url();async function TC(r){if(Tz.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(!yz(r))throw new Error(`File does not exist at path: ${r}`);return bz(r).toString("base64")}var vz=5e3,cu=class extends pt{async executeScreenCheck(e){let{timeout:t}=e,n=Date.now(),o=(t??wr)*1e3,i=o+1e4,a,s=0,c=500;for(;s-n<o;){if(Date.now()-n>i){this.logger.warn("Exceeded max system timeout for screen check, exiting...");break}if(this.throwIfAborted(),a=await this.executeScreenCheckHelper(e),s=Date.now(),!a.success)await X(c,this.abortSignal),c=Math.min(Math.floor(c*1.5),vz);else return a}return a=await this.executeScreenCheckHelper(e),a}async executeScreenCheckHelper(e){return await ce().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":{let o=!1,i;try{let a=(await this.stateManager.getDomState({skipFetchingFullWebviewContent:!0,removeWebviewContent:!0})).graph.document.documentElement?.outerHTML;if(!a)throw new Error("Failed to get screen HTML");o=a.includes(n.value)===!n.negated,a.length>1e4&&(a=a.slice(0,1e4)+"...TRUNCATED"),o||(i=new x("AssertionFailureError",`The screen ${Rm(n)}.`),e.attributes.screenContent=a)}catch(a){i=new x("AssertionFailureError",`Failed to evaluate screen content assertion: ${a instanceof Error?a.message:`${a}`}`)}return{success:o,err:i}}default:return n.type,{success:!1,err:new x("AssertionFailureError",`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 Qc({assertion:e.assertion,logger:this.logger,browser:n,autoExpandIframes:!!n.userBrowserSettings.autoExpandIframes})}};var uu=class extends pt{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(`
|
|
4180
|
+
`).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 Ci=class r extends pt{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},p=await au.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:p,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 ${wz.resolve(e)}`)}async executeCommand(e){let t=["type","a11yData","thoughts","cache","code"],n;try{n=await wc({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{Rc(e.command,n)}}async executeCommandHelper({command:e}){let t=ce();switch(e.type){case"TAP":return new vi(this.constructPerformerParams()).executeTap({command:e});case"TYPE":return await new iu(this.constructPerformerParams()).doType(e);case"AI_CHECK":{let o=e.timeoutSecs?e.timeoutSecs*1e3:5e3,i=Pc(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 X(i,this.abortSignal),c=Date.now();try{let d="",p="";await t.startAsyncSpan("EMULATOR_READ_STATE",async()=>{d=(await this.stateManager.getDomState({})).graph.xml,p=await this.stateManager.getCurrentScreenshotPngString()},{name:"Get emulator state"});let g=await t.startAsyncSpan("AI_ASSERTION_CALL",async m=>{let h=await this.generator.evaluateAssertion({assertion:e.assertion,screenXml:d,screenshot:p},{logger:this.logger,loggerTags:ge(this.logger)});return m.result={thoughts:h.thoughts,result:h.result},h});if(g.result)return{success:g.result,message:g.thoughts};{let m=`AssertionFailureError: ${g.thoughts}`;u=new Error(m)}}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 wi(this.constructPerformerParams()).executeSwipe(e);case"SCREEN_CHECK":return new cu(this.constructPerformerParams()).executeScreenCheck(e);case"SCROLL_TO":return new su(this.constructPerformerParams()).executeScrollTo(e);case"JAVASCRIPT":{let n=await Ur({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 Rz,i=Az(fetch,o),a=Date.now(),s=await Zc({command:e,baseUrl:void 0,logger:this.logger,fetchImplementation:i}),c=el(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 Ln(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(`
|
|
4181
|
+
`).pop()?.replace(/^.*\//,""),!n)throw new Error(`Could not parse main activity name for package ${e.packageName}. Raw output: ${a}`)}if(this.options.emulator?.autoGrantPermissions&&!this.appsWithGrantedPermissions.has(e.packageName)){let i={permissions:"all",appPackage:e.packageName,action:"grant"};await this.driver.executeScript("mobile: changePermissions",[i]),this.appsWithGrantedPermissions.add(e.packageName)}let o=["start"];if(e.intentExtras)try{let i=JSON.parse(e.intentExtras);for(let[a,s]of Object.entries(i))o.push("-e",a,typeof s=="string"?s:JSON.stringify(s))}catch(i){throw new Error(`UserConfigurationError: Invalid intent extras does not parse as valid JSON: ${i instanceof Error?i.message:`${i}`}`)}return o.push("-n",`${e.packageName}/${n}`),await this.driver.execute("mobile: shell",{command:"am",args:o}),await this.stateManager.waitForScreenshotStability({timeoutMs:5e3,signal:this.abortSignal,reason:"Waiting for stability after app launch"}),{success:!0}}case"PRESS":{let n=new Ln(this.constructPerformerParams());switch(e.key){case"HOME":await n.doPress({keycode:3});break;case"BACK":await n.doPress({keycode:4});break;case"APP_SWITCHER":await n.doPress({keycode:187});break;case"POWER":await n.doPress({keycode:26});break;case"SEARCH":await n.doPress({keycode:84});break;case"VOLUME_UP":await n.doPress({keycode:24});break;case"VOLUME_DOWN":await n.doPress({keycode:25});break;case"VOLUME_MUTE":await n.doPress({keycode:164});break}return{success:!0}}case"PRESS_KEYBOARD":{let n=new Ln(this.constructPerformerParams()),o=i=>n.doPress({keycode:i});switch(e.key){case"CLOSE_KEYBOARD":{let i=Date.now();for(;Date.now()-i<5e3&&(await this.driver.hideKeyboard(),!!await this.driver.isKeyboardShown()););break}case"ENTER":await o(66);break;case"BACKSPACE":await o(67);break;default:{let i=e}}return{success:!0}}case"WAIT":return await X(e.timeoutSecs*1e3,this.aborter.controller?.signal),{success:!0};case"INSTALL_APP":return new lu(this.constructPerformerParams()).doInstallApk(e);case"UNINSTALL_APP":return new uu(this.constructPerformerParams()).doUninstallApk(e);case"ADD_FILE":{let n=await TC(e.file);return await this.driver.pushFile(e.storageLocation,n),await this.driver.execute("mobile: shell",{command:"am",args:["broadcast","-a","android.intent.action.MEDIA_SCANNER_SCAN_FILE","-d",`file://${e.storageLocation}`]}),{success:!0}}case"ADB":{let n=await this.driver.execute(e.command,JSON.parse(e.jsonArgs??"{}"));return this.logger.info({output:n},"ADB command executed successfully"),{success:!0,output:n,message:"ADB command executed successfully"}}case"KILL_APP":{let n=await this.stateManager.getCurrentPackage();if(!n)throw new Error("No package is currently active");await this.driver.execute("mobile: shell",{command:"input",args:["keyevent","KEYCODE_HOME"]}),await this.driver.terminateApp(n);try{await sC({packageName:n,driver:this.driver,abortSignal:this.abortSignal,logger:this.logger})}catch(o){this.throwIfAborted(),this.logger.warn({err:o,packageName:n},"Failed to remove package from recents, continuing...")}return{success:!0}}case"STATE":{await this.stateManager.refreshWebviews();let n=await this.stateManager.getDomState(),o=await this.stateManager.getContexts(),i={xml:n.graph.xml,contexts:o};return this.logger.info({result:i},"State debug command output"),{output:i,success:!0}}default:{let n=e;return{success:!0}}}}async initializeSettings(){let{latitude:e,longitude:t}=this.options?.emulator?.geolocation??$s;await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_COARSE_LOCATION"]}),await this.driver.execute("mobile: shell",{command:"pm",args:["grant","io.appium.settings","android.permission.ACCESS_FINE_LOCATION"]}),await this.driver.setGeoLocation({latitude:e,longitude:t})}async getScreenshotBase64(){return this.stateManager.getRawScreenshotBase64()}async getScreenshotPngString(){return this.stateManager.getCurrentScreenshotPngString()}async getA11yTree(){return(await this.stateManager.getDomState({})).graph.xml}async waitForScreenshotStability(e){return this.stateManager.waitForScreenshotStability({timeoutMs:e.timeoutMs??5e3,reason:e.reason,signal:this.aborter.controller?.signal})}resetAbortController(e){this.aborter.controller=e??new AbortController}isAborted(){return this.aborter.controller?.signal.aborted}abort(){this.aborter.controller?.abort()}async cleanup(){await this.stateManager.cleanupWebviews()}get abortSignal(){return this.aborter.controller?.signal}get context(){return this.fixtures.testContext}get localCodeEvalTools(){return this.fixtures.localCodeEvalTools}};async function vC({socket:r,logger:e,androidDriverFactory:t,getOrgId:n,mobileGeneratorFactory:o,browserGeneratorFactory:i,browserEnricherFactory:a,storageFactory:s,localToolsFactory:c,globalStateManager:l,settingsFactory:u}){let d=r.id,p=r.handshake.query?.testMetadata,g=r.handshake.query?.fileName,m=g?Cz.basename(g,".test.yaml"):"",h=Mr.parse(JSON.parse(p??"")),f=h.id,E=h.settings?.defaultChannel,b=h.settings?.defaultTag,R=h.settings?.defaultApkFilePath?.trim(),A=await n({testId:f});e=e.child({sessionId:d,testId:f,orgId:A});let _={...(await u(A,e)).emulator,...h.settings?.emulator},w;if(_.region==="local"){if(!_.localEmulatorSettings?.avdId)throw new Error("AVD name is required when region is local");w={avdId:_.localEmulatorSettings.avdId,apkToInstall:E?{channel:E,tag:b}:void 0,apkFilePath:R||void 0}}else w={region:_.region,apkToInstall:E?{channel:E,tag:b}:void 0,osVersion:_.remoteEmulatorSettings?.androidVersion};let D=Date.now(),{driver:G,cleanup:ee,emulatorName:Te,adbPort:fe,limbarClient:ve,limbarToken:$,limbarUrl:j,playwrightDevice:se}=await t({socket:r,logger:e,creationOpts:w}),J=await Ac({driver:G,onLogs:vo=>{r.emit("logcatLogs",vo)}});e.info({adbPort:fe,apkChannel:E,apkTag:b,duration:Date.now()-D,emulatorName:Te},"Android emulator session initiated"),e=e.child({emulator:Te});let Ye=await o(A,e),Ne=await i(A,e),kt=await a(A,e),Ht=await s(A),De=c?await c(A):void 0,Ie={};h.settings?.defaultEnv&&(Ie=(await Ht.fetchEnvironment(h.settings?.defaultEnv,e))?.variables??{});let xt=new jo({variablesFromEnvironment:Ie,envName:h.settings?.defaultEnv,testName:m}),gt=await Ci.init({driver:G,generator:Ye,logger:e,limbarClient:ve,playwrightDevice:se,options:{emulator:_},fixtures:{storage:Ht,browserEnricher:kt,browserGenerator:Ne,localCodeEvalTools:De,testContext:xt},orgId:A,adbPort:fe,abortController:new AbortController});if(!r.connected)throw await J(),await ee(),new Error("Socket not connected anymore, not proceeding with Android session setup");let Vr=xz({socket:r,testContext:xt}),To=async()=>{clearInterval(Vr);try{await J(),await ee(),await gt.cleanup()}catch(vo){e.warn({err:vo},"Failed to clean up emulator in socket server")}};return l.registerSession(d,{controller:gt,cleanup:To,emulatorName:Te,local:_.region==="local"}),r.emit("session",{testId:f,sessionId:d,limbarUrl:j,limbarToken:$}),{sessionId:d,testId:f,orgId:A,emulatorName:Te,logger:e,testName:m}}function xz({socket:r,testContext:e}){return setInterval(()=>{let t=e.toEditorDisplayCopy();r.emit("emulatorState",{context:t})},3e3)}async function AC({socket:r,logger:e,globalStateManager:t}){await t.removeSession(r.id,e)}var Mz=({socket:r,globalStateManager:e})=>async()=>{let t=e.getSession(r.id);if(!t)throw new Error("No active Android session found");t.controller.abort()},wC={event:"cancel",createHandler:Mz};var _z=({logger:r,globalStateManager:e,socket:t})=>async(n,o)=>{let i=e.getSession(t.id);if(!i){o({err:"No active Android session found"});return}try{let s=await i.controller.getA11yTree();o({a11yTree:s})}catch(a){r.error({err:a},"Error fetching a11y tree from the session controller"),o({err:a.message})}},RC={event:"fetchA11yTree",createHandler:_z};import{diff as $z}from"deep-object-diff";import{cloneDeep as qz}from"lodash-es";function CC(r,e,t=1e4,n=5e3){let o=0;async function i(){try{let s=await k(r.driver.execute("mobile: shell",{command:"echo",args:["ping"]}).catch(c=>{throw c}),{milliseconds:n});if(typeof s=="string"&&s.trim()==="ping")o>0&&e.info("Driver heartbeat restored"),o=0;else throw new Error(`Unexpected heartbeat output: ${s}`)}catch(s){o++;let c=s instanceof Error?s.message:`${s}`;e.error({attempt:o,error:c},"Driver heartbeat failed"),o>=3&&e.error("Driver appears unresponsive \u2014 possible ADB tunnel/emulator failure")}}let a=setInterval(()=>{i()},t);return i(),a}async function xC(r){let e=Date.now(),t=r.fixtures.controller;try{return await Pz(r)}catch(n){let o=t.isAborted()||n instanceof DOMException&&n.name==="AbortError";return{...r.moduleParams.step,steps:[],type:"MOBILE_MODULE_STEP",startTime:e,endTime:Date.now(),status:o?"CANCELLED":"FAILED",message:o?"Step cancelled.":`${n}`}}}async function Pz({moduleParams:r,...e}){let t=Date.now(),{step:n,stepTracer:o,executeMobileStepList:i}=r,a=await Iz({step:n,params:e}),s={};Object.entries(a).forEach(([p,g])=>{s[p]=JSON.stringify(g)});let c={...n,type:"MOBILE_MODULE_STEP",inputs:s,startTime:t,steps:[],endTime:Date.now(),status:"SUCCESS"},l=await o.startSubSteps(),{status:u,results:d}=await i({...e,listParams:{steps:n.steps,containerName:`module ('${n.name}')`,tracer:l}});return c.steps=d,c.status=u,c.endTime=Date.now(),FA({result:c,...UA(d)}),c}async function Iz({step:r,params:e}){let t={},{logger:n,controller:o}=e.fixtures;for(let i of r.parameters?.parameterNames??[]){let a=r.inputs?.[i]??r.parameters?.defaultParameters?.[i];if(!a){n.warn({k:i},"No value found for parameter in module");continue}t[i]=await Ur({orgId:e.inputs.orgId,code:a,fragment:!0,logger:n,context:o.context,localTools:o.localCodeEvalTools})}return t}import{randomUUID as MC}from"crypto";async function _C({fixtures:r,step:e,inputs:t,stepTracer:n}){let o=Date.now(),{logger:i,controller:a}=r,s;if(!t.interactive)try{s=await a.getScreenshotBase64()}catch(l){i.warn({err:l},"Failed to take before screenshot")}let c={...e,status:"SUCCESS",startTime:o,endTime:Date.now()};try{let l=await a.executeCommand({command:e.command});c={...e,status:l.success?"SUCCESS":"FAILED",message:l.message,startTime:o,endTime:Date.now(),data:l.output}}catch(l){l instanceof Error&&l.name==="AbortError"||a.isAborted()?c={...e,status:"CANCELLED",message:"Step cancelled.",startTime:o,endTime:Date.now()}:(i.error({err:l},"Failed to execute preset step"),c={...e,status:"FAILED",message:l instanceof Error?l.message:String(l),startTime:o,endTime:Date.now()})}finally{if(!t.interactive){try{let l=MC(),u=await a.getScreenshotBase64();c.afterSnapshot=l,n.attachAfterScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(u,"base64")})}catch(l){i.warn({err:l},"Failed to take after screenshot")}if(s){let l=MC();c.beforeSnapshot=l,n.attachBeforeScreenshot({logger:i,snapshotId:l,screenshot:Buffer.from(s,"base64")})}}}return c}import{streamText as Gz}from"ai";import{randomUUID as Vz}from"crypto";var du=class{controller;logger;callbacks;rootStep;subStepIndex=0;finalState=void 0;results=[];constructor(e){let{controller:t,logger:n,callbacks:o,rootStep:i}=e;this.controller=t,this.logger=n,this.callbacks=o,this.rootStep=i}async createAndExecuteStep(e){this.callbacks.onAiActionEvent?.({type:"SUBSTEP_CREATED",rootStep:this.rootStep,step:e});let t=this.subStepIndex++,n=await this.callbacks.executeStep(e,t);return this.results.push(n),n}};import{hasToolCall as zz,stepCountIs as Hz}from"ai";var PC="get_emulator_state",pu="finish";import IC from"dedent";var Lz=IC`
|
|
4160
4182
|
You cannot interact with the user directly. If you feel like you need to ask the user for clarification, or you are stuck, call the "finish" tool with success=false. Never output text without calling a tool.
|
|
4161
|
-
`,
|
|
4183
|
+
`,OC=r=>IC`
|
|
4162
4184
|
<background>
|
|
4163
4185
|
You are an advanced, AI agent part of an end-to-end testing platform called Momentic.
|
|
4164
4186
|
Momentic uses AI agents to translate high-level natural language descriptions of user flows into browser automation for the purpose of validating application correctness.
|
|
@@ -4171,7 +4193,7 @@ The steps you generate will be fed to downstream Momentic agents that are respon
|
|
|
4171
4193
|
The user will provide you with a high-level goal to achieve. Your task is to use the tools at your disposal to make as much progress as you can towards accomplishing the goal until one of the following is true:
|
|
4172
4194
|
- You have successfully accomplished the goal, fulfilling all criteria specified by the user. In this case, end the generation cycle by calling the "finish" tool with success=true.
|
|
4173
4195
|
- You have determined that the goal is impossible to accomplish or too vague to interpret confidently. In this case, end the generation cycle by calling the "finish" tool with success=false. Some examples of why a goal could be impossible: a) the goal requires a step type or capability that is not available to you; b) the user's app crashes or displays a 500 internal server error page; c) Momentic's AI agents repeatedly fail to perform the correct interaction, which could indicate an accessibility issue with the app.
|
|
4174
|
-
${r?"":
|
|
4196
|
+
${r?"":Lz}
|
|
4175
4197
|
</task>
|
|
4176
4198
|
|
|
4177
4199
|
<values>
|
|
@@ -4189,22 +4211,22 @@ Momentic users value the following:
|
|
|
4189
4211
|
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.
|
|
4190
4212
|
If the max. allowed retries is exceeded, fail the generation cycle by calling "finish".
|
|
4191
4213
|
</rules>
|
|
4192
|
-
`;import{tool as Pz}from"ai";import{randomUUID as Iz}from"crypto";import Oz from"zod";import{tool as Mz}from"ai";import _z from"zod";var pC=r=>{let e=Mz({description:"Get the current state of the emulator (XML + screenshot)",inputSchema:_z.object({}),toModelOutput:t=>t,execute:async()=>{let{controller:t,logger:n}=r;return n.info("AI action tool called (get_emulator_state)"),Eg(t)}});return{name:uC,tool:e}};async function Eg(r){let e=await r.getA11yTree(),t=await r.getScreenshotBase64();return{type:"content",value:[{type:"text",text:e},{type:"text",text:"</emulatorXml>"},{type:"text",text:"<screenshot>"},{type:"media",data:t,mediaType:"image/png"},{type:"text",text:"</screenshot>"}]}}var gC=r=>({name:"create_execute_step",tool:Pz({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:Oz.object({step:Gd}),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=HS(t),s={id:Iz(),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 Eg(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 Lz}from"ai";import Tg from"zod";var hC=r=>{let e=Lz({description:"Signal that the AI action has reached a terminal state (either success or failure).",inputSchema:Tg.object({message:Tg.string(),success:Tg.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:du,tool:e}};var fC=[gC,pC,hC];function SC(r){let{logger:e,controller:t,contextManager:n,aiActionSessionId:o}=r,i={};for(let c of fC){let l=c({contextManager:n,logger:e,controller:t});i[l.name]=l.tool}let a=t.generator.getVercelAnthropicModelFactory({loggerTags:he(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 p of m.content)if(!(typeof p!="object"||!("type"in p))&&!(p.type!=="tool-result"||p.output.type!=="content")&&!(p.output.value.length<3))for(let g=0;g<p.output.value.length;g++){let h=p.output.value[g];if(h.type==="text"&&h.text.includes("<emulatorXml>"))if(u){let f=p.output.value[g+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:[Dz(15),Nz(du)],system:mC(!1)}}async function yC(r){let e=Date.now(),{controller:t,logger:n}=r.fixtures;try{return await Fz(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 Fz(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=Uz(),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()},p=new uu({controller:o,callbacks:{onAiActionEvent:a?.onAiActionEvent,executeStep:d},logger:l,rootStep:m}),g=SC({controller:o,logger:l,contextManager:p,aiActionSessionId:c}),h=kz({...g,messages:[{role:"user",content:e.text}]});for await(let f of h.fullStream)switch(f.type){case"text-delta":a?.onAiActionEvent?.({type:"LLM_TEXT_OUTPUT",text:f.text,rootStep:m})}if(await h.response,o.throwIfAborted(),!p.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:p.finalState.status,startTime:u,endTime:Date.now(),message:p.finalState.message,steps:p.results}}async function mu(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=[],p,g="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 O=JSON.stringify(d);if(b.id===h.fromStepId&&O===JSON.stringify(h.parentStepIdChain))o.fastForwardingToStep=!1;else if(!gA({currentStep:b,currentParentChain:d,desiredStepId:h.fromStepId,desiredStepParentChain:h.parentStepIdChain}))continue}c.info({step:b},`Executing step ${E+1}/${a.length} in ${i} - ${lA(b)}`);let x=await s.startStep({logger:c,step:b,attempt:1,parentStepIdChain:d});u.trackStepExecution(b);let T=await Bz({step:b,stepTracer:x,params:r}),{trace:v}=await x.finish({parentStepIdChain:d,result:T});if(T.trace=v,c.info({step:{id:b.id},trace:T.trace,status:T.status},`Finished step ${E+1}/${a.length} (${b.type==="MOBILE_PRESET_STEP"?b.command.type:b.type})`),m.push(T),T.status!=="SUCCESS"){g=T.status,p=T;break}if(b.envKey&&l.context.setVariable(b.envKey,T.data),f){let O=JSON.stringify(d);if(b.id===f.toStepId&&O===JSON.stringify(f.parentStepIdChain)){o.shouldStopExecuting=!0;break}}if(o.shouldStopExecuting)break}return{results:m,status:g,terminalResult:p}}async function Bz({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 cC({fixtures:n,inputs:o,step:r,stepTracer:e,callbacks:i,work:a});break}case"RESOLVED_MOBILE_MODULE":{s=await sC({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:mu}});break}case"MOBILE_AI_ACTION_STEP":{s=await yC({...t,aiActionParams:{step:r,stepTracer:e,executeMobileStepList:mu}});break}}return s}async function pu(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=Hz(n);c.info({testMetadata:Mr.parse(o)},"Starting mobile test");let u=await e.startMainStepList(),d=Db(c),m=aC(s,c);c.info({cpu:d?.cpuMetadata,platform:d?.platform},`Starting execution of ${t}`);let{status:p,results:g}=await mu({...r,listParams:{containerName:t,tracer:u,steps:l}});if(clearInterval(d?.interval),clearInterval(m),p==="SUCCESS"){let h=zz(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 Cn({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:g}}return p==="CANCELLED"?{status:"CANCELLED",results:g}:{status:"FAILED",results:g}}var vg=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 go,Qr.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...hb.parse(e),trace:$d.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 Ri({parentStep:this.step,socket:this.socket,parentTracer:this})}},Ri=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 vg({step:e.step,parentTracer:this,socket:this.socket})}},gu=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Ri({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Ri({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Ri({parentStep:null,parentTracer:null,socket:this.socket})}};var Gz=({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 gu(n),m=await pu({work:{fastForwardingToStep:!!i.fromStep},fixtures:{controller:u,logger:c,cacheStorage:l,usageTracker:new Zs},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:g=>{n.emit("aiActionEvent",g)}}}});await d.finish();let p={results:tr.array().parse(m.results),status:m.status};a?.(p)},bC={event:"execute",createHandler:Gz};import{debounce as Vz}from"ts-debounce";var Wz=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=Vz(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))}},EC={event:"keepalive",createHandler:Wz};var TC=[bC,oC,EC,iC];function vC(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new jz(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 nC({socket:s,globalStateManager:n,logger:l})});let u;try{u=await rC({...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}TC.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=p=>{c.logger.error({event:s.event,err:p instanceof Error?p:new Error(`${p}`)},"Unhandled exception in socket handler"),c.socket.emit("error",{message:p instanceof Error?p.message:`${p}`})};try{let p=l.apply(this,d);p&&typeof p.catch=="function"&&p.catch(m)}catch(p){m(p)}};c.socket.on(s.event,u)};return{server:o,dispose:i}}import{randomUUID as XH}from"crypto";import{diff as gOe}from"deep-object-diff";import ROe from"yaml";import{z as xOe}from"zod";import{execSync as $z}from"child_process";function Nn(r,e){let t=e.hooks?.postSave;if(!t)return;let n;t.includes("$1")?n=t.replaceAll("$1",r):n=`${t} ${r}`,R.debug({postSaveCommand:n},"Executing post-save hook command");try{$z(n,{encoding:"utf-8"})}catch(o){R.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as jIe}from"deep-object-diff";import{cloneDeep as qIe}from"lodash-es";import{v4 as iOe}from"uuid";import sOe from"yaml";import qz from"@dotenvx/dotenvx";import Kz from"fs";import AC from"path";function wC(r,e){return(r.config.environments??[]).map(t=>ls(t.name,r,e))}function Yz(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 Xz(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=Yz(i);s&&(n[o]=s);continue}let a;try{a=Kz.readFileSync(AC.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&&R.debug(n,"Set environment variables with interpolation from project configuration"),n}function Jz(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=qz.config({path:AC.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 ls(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=Xz({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=Jz({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 u1,readFileSync as d1,readdirSync as m1,writeFileSync as p1}from"fs";import{glob as g1}from"glob";import fo,{dirname as xC}from"path";import{cwd as xg}from"process";import MC from"yaml";import{z as Pe}from"zod";import RC from"fs";import{glob as Zz}from"glob";import cs from"path";import Qz from"yaml";import{z as Ag}from"zod";var CC=!1,wg=["**/*.test.yaml","**/*.module.yaml"],Rg=Ag.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Cg=15,e1=Ag.object({fileType:Ag.nativeEnum(xe)});async function dr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??wg,o=Array.from(r.config.exclude??[]).concat(hl),i=AbortSignal.timeout(5e3),a;try{a=await Zz(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Cg,nodir:!0,signal:i})}catch(s){throw R.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=t1(r.rootDir,s,t,e?fn:R);c&&(t.duplicateEntities[c.id]=c.paths)}return CC=!0,t}function t1(r,e,t,n){let o=cs.join(r,e),i=r1(o,n);if(!i)return;let a=n1(i,o,n);if(!a)return;let s=e1.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=o1(o,n);if(!l)return;let u=i1(e,o,l);switch(c){case xe.TEST:try{return a1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case xe.MODULE:try{return s1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case xe.MOBILE_TEST:try{return c1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case xe.MOBILE_MODULE:try{return l1(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 r1(r,e){try{return RC.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function n1(r,e,t){try{let n=Qz.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 o1(r,e){try{return RC.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function i1(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:cs.sep,fullPathSegments:e.split(cs.sep),relativePathSegments:r.split(cs.sep),fileName:cs.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function a1(r,e,t,n,o){let i=Go.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:xe.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function s1(r,e,t,n,o){let i=Yt.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:xe.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!CC&&qr(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 l1(r,e,t,n,o){let i=ha.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:xe.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function c1(r,e,t,n,o){let i=Mr.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:xe.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}var Ci="momentic.config.yaml",Mg="momentic.workspace.yaml",h1=Pe.object({projects:Pe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),f1=Pe.union([Pe.string(),Pe.object({fromFile:Pe.string(),json:Pe.boolean().optional()})]),S1=Pe.object({name:Rg,baseUrl:Pe.string().optional().describe("Optional for mobile tests"),envFile:Pe.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Pe.record(Pe.string(),f1).optional(),inheritFromShell:Pe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:jn.optional().describe("NB: most things should use project-level configuration only")}),y1=Pe.object({postSave:Pe.string().optional()}),b1=Pe.object({name:Rg,include:Pe.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Pe.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Pe.string().optional(),reporterDir:Pe.string().optional(),outputDir:Pe.string().optional(),recordVideo:Pe.boolean().optional(),retries:Pe.number().optional().describe("number of retries per test"),parallel:Pe.number().optional().describe("degree of parallelism"),environments:Pe.array(S1).optional(),gitMainBranch:Pe.string().optional(),gitProtectedBranches:Pe.string().array().optional(),ai:tm.optional(),browser:jn.optional(),emulator:jd.optional(),advanced:rm.optional(),hooks:y1.optional()});function _C(r,e){let t;try{t=d1(r,"utf-8")}catch(o){R.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=MC.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){R.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function _g(r){let e=_C(r,"project configuration");if(e!==void 0)try{return b1.parse(e)}catch(t){R.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function E1(r){let e=_C(r,"workspace configuration");if(e!==void 0)try{return h1.parse(e)}catch(t){R.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function T1(){let r=[],e=xg(),t=fo.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=fo.basename(e);if(gl.includes(i))return R.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),r;for(let a of m1(e))if(a.endsWith(Ci)){let s=fo.join(e,a),c=_g(s);c&&r.push({configFilePath:s,config:c,rootDir:xC(s)})}if(r.length)return r;if(e=fo.dirname(e),e===t)break}return r}async function us(r={}){let{configFilePath:e,nameFilter:t}=r,n=await A1(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:
|
|
4193
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return
|
|
4194
|
-
`)){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 M1(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 OC("ssh",["-T","-o","BatchMode=yes",`git@${n}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=n&&n!=="github.com"?["api","--hostname",n,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await OC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function _1(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return M1(r,e,t);if(o)return}catch{}}function hu(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 Le(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function P1(){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 I1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.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 O1(r){let[e,t,n]=await Promise.all([Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.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 L1(r){let[e,t,n,o]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?hu(t):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:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function N1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?hu(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 D1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?hu(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 k1(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Le(r,Oe.revparse(["HEAD"])),Le(r,Oe.revparse(["--short","HEAD"])),Le(r,Oe.revparse(["--abbrev-ref","HEAD"])),Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"])),e?Le(r,Oe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),x1(r)]),d=l?await Le(r,Oe.show(["--no-patch","--format=%ci",l])):void 0,m=i?.includes("github.com"),p=i?.includes("gitlab.com"),g=i?hu(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await _1(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?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function U1(){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 F1(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function ds(r,e){let t=P1();if(!t)return k1(r,e);switch(t){case"GithubActions":return I1(r);case"GitlabCI":return O1(r);case"CircleCI":return L1(r);case"Buildkite":return N1(r);case"AzureDevOps":return D1(r);case"GCPCloudBuild":return U1()}}async function B1(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 z1(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 H1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await z1(r,e,n,o,t)}else if(t.gitlabProjectPath)return await B1(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function xi(r,e,t){let n=await F1(t),o=await ds(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 H1(r,e,i);return{...n,...o,...a}}import{diff as LC}from"deep-object-diff";import Dn from"fs";import{cloneDeep as G1}from"lodash-es";import fu from"path";import{v4 as V1}from"uuid";import ms from"yaml";function NC({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!Dn.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=Dn.readFileSync(i,"utf-8"),s=ms.parse(a),c={...s,...r,schemaVersion:e},l=so({fileType:xe.MOBILE_MODULE,...ha.parse(c),steps:Sr.array().parse(r.steps)}),u=LC(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=ms.stringify(l);Dn.writeFileSync(i,d,"utf-8"),Nn(i,n.config)}function DC({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=ps(i,o),s={...a,...e},c=so({fileType:xe.MOBILE_MODULE,...cl.parse(s)}),l=LC(c,a);if(l&&Object.keys(l).length===0)return;let u=ms.stringify(c);Dn.writeFileSync(i,u,"utf-8");let d;if(e.name){let m=`${qr(e.name)}.module.yaml`;if(d=fu.join(fu.dirname(i),m),Dn.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);Dn.renameSync(i,d)}Nn(d||i,n.config)}async function kC({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=qr(r),s=fu.join(o,`${a}.module.yaml`),c=V1(),{stepsToSave:l}=await Cn({steps:n}),u={schemaVersion:ln,moduleId:c,description:e,enabled:t},d={fileType:xe.MOBILE_MODULE,...u,steps:l},m=ms.stringify(XS.parse(d));return Dn.writeFileSync(s,m,"utf-8"),Nn(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function ps(r,e){let t=Dn.readFileSync(r,"utf-8"),n=ms.parse(t);try{return{...cl.parse(n),name:fu.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 Ig(r,e,t,n){let o=ps(r.fullFilePath,t),{resolvedSteps:i}=await Mc({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 ps(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]=G1(a)),a}async function UC(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Ig(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as W1}from"crypto";import So from"fs";import Og from"path";import Su from"yaml";function FC({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${qr(r)}.test.yaml`,s=Og.join(o,a);if(So.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:xe.MOBILE_TEST,id:W1(),description:e,schemaVersion:md,settings:n,steps:t},l=Su.stringify(c);return So.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function j1(r){if(!So.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=So.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4195
|
-
`),t=
|
|
4196
|
-
`),c=Su.parse(s),l=ul.parse(c);if(l.fileType!==xe.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await Cn({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},m=Su.stringify(ul.parse(d));for(let p of u?.moduleUpdates??[])NC({content:p,schemaVersion:md,momenticFiles:i,project:o});So.writeFileSync(a,m,"utf-8"),Nn(a,o.config)}import{randomUUID as $1}from"crypto";import kn from"fs";import Mi from"path";var zC=new Set([".DS_Store","__MACOSX"]),HC={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 q1(r,e,t){if(HC[t]){let i=HC[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 Lg=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 GC(r,e){try{let t=Mi.join(e,"metadata.json");return Al.parse(JSON.parse(kn.readFileSync(t,"utf-8")))}catch{throw new Lg(r,e)}}function VC(r,e,t){let n=$1(),o=r.child({runGroupId:n});kn.rmSync(e,{recursive:!0,force:!0});let i=kn.readdirSync(t).filter(c=>!zC.has(c)).map(c=>Mi.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);kn.mkdirSync(e,{recursive:!0});let a={...GC(t,i[0]),id:n};for(let c of i){let l=Mi.join(c,"runs");if(!kn.existsSync(l))continue;let u=GC(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let m in u){if(m==="id")continue;let p=m;a[p]=q1(a,u,p)}let d=kn.readdirSync(l);for(let m of d){if(zC.has(m))continue;let p=Mi.join(l,m),g=Mi.join(e,"runs",m);kn.cpSync(p,g,{recursive:!0})}}let s=Mi.join(e,"metadata.json");kn.writeFileSync(s,JSON.stringify(a,null,2))}import jC from"adm-zip";import Bg from"fs";import{z as eH}from"zod";var U="v1",Ng="mobile-cli",yo="0.7.2";var K1=9e4,Y1=3,X1=1500,J1=15e3,Tr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function Z1(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Dg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return yo&&(e[El]=yo),Ng&&(e[Ay]=Ng),e}async sendRequest(e,t){let{retries:n=Y1,requestTimeoutMs:o=K1,initialRetryDelayMs:i=X1,maxRetryDelayMs:a=J1,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 Tr&&m.status>=400&&m.status<500)throw m;if(m instanceof Error&&m.name==="AbortError"&&(u=new Sn),c===0)throw u;let p=l-c,g=Math.min(i*Math.pow(2,p-1),a);await new Promise(h=>setTimeout(h,g))}throw this.logger.warn({...d,err:u},"Got fatal error response from Momentic server"),u}async sendSingleRequestHelper(e,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 Z1(u);throw new Tr(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)}}},Gr=class extends Dg{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[vy]:this.mode??""}}};import{createAnthropic as Q1}from"@ai-sdk/anthropic";var bu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[El]:yo??"",...t&&{[Ry]:t},...n||{}};return o&&(a[wy]=JSON.stringify(o)),Q1({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var bo=class extends Gr{agentConfig;constructor(e,t){let n={...AS,...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 uS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:yo,...e},signal:t.abortSignal});return cS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return eH.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 _y.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 om.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 My.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 xy.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 om.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 Cy.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 hd.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 Py.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 pd.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 Gf.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 Vf.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 Qu.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return vS.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 Uf.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 zf.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 Bf.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Sh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return bu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as kg}from"zod";var vr=class extends Gr{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=>{R.warn(`API key check failed: ${t.message}`)}});return Vy.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return By.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Oy.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 Ny.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 Dy.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Iy.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Gy.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Wy.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 ib.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 jy.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 iS.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 $y.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 qy.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Ky.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 Yy.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return lb.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 Aa.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 Aa.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 lm.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 Aa.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 Aa.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 lm.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return kg.record(kg.string(),kg.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return Xy.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 Jy.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 Zy.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 Qy.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function Ug(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(R.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),R.debug(`Identified node version ${e}`);let n=await r.client.getAuthInfo();return R.debug("Got auth info from API"),n}var Eu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var _i=class extends Gr{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 yh.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Pi=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 tH,en as rH}from"@faker-js/faker";var Ii="v1",Oi=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 tH({locale:rH}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ii}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Tr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ii}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ii}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ii}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ii}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ii}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function WC(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Tu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await WC(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 Li=class extends Gr{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 RS.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 MS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return bu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function vu({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new vl:new Fg(r,e,t,o)}var Fg=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=im(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;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){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&&Tp({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Cn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import Au from"path";function nH(r){let e=new jC,t=Au.join(r,"metadata.json"),n=Al.parse(JSON.parse(Bg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Bg.readdirSync(Au.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new jC(Au.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Au.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function wu(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Bg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new Tu(e);try{let{runGroupId:i,buffer:a}=nH(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 oH from"adm-zip";import St from"fs";import Wt from"path";var gs=class r{constructor(e){this.filePath=e;St.rmSync(this.filePath,{recursive:!0,force:!0}),St.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Wt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){St.mkdirSync(Wt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Wt.join(this.filePath,e);if(St.existsSync(t))return St.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Wt.join(this.filePath,t);try{St.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Wt.join(this.filePath,e);return St.createWriteStream(t)}createRunArchive(e){return new zg(Wt.join(this.filePath,"runs"),e)}},zg=class{constructor(e,t){this.filePath=e;this.tempPath=Wt.join(e,`.${t}`),this.finalPath=Wt.join(e,`${t}.zip`),St.rmSync(this.tempPath,{recursive:!0,force:!0}),St.rmSync(this.finalPath,{recursive:!0,force:!0}),St.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Wt.join(this.tempPath,e);if(St.existsSync(t))return St.readFileSync(t)}mkdir(e){St.mkdirSync(Wt.join(this.tempPath,e),{recursive:!0})}cd(e){return new gs(Wt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Wt.join(this.tempPath,t);St.writeFileSync(o,n)}createFileStream(e){let t=Wt.join(this.tempPath,e);return St.createWriteStream(t)}close(){let e=new oH;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();St.writeFileSync(this.finalPath,t),St.rmSync(this.tempPath,{recursive:!0,force:!0})}};import Ou from"fs";import sx from"body-parser";import RH from"cors";import CH from"dedent";import{Router as lH}from"express";import Dt from"fs";import{globSync as cH}from"glob";import dt from"path";import Ru from"fs";import iH from"path";var aH=new Uc(30,60*1e3),Wg="https://api.momentic.ai",Gg,qC=r=>{Wg=r},jg=()=>Wg,hs=()=>Gg;var Ni,Vg,$C,KC=async r=>{if(Gg&&Ni&&$C)return Ni;let e=new vr({baseUrl:Wg,apiKey:r,logger:R});Gg=e;try{let t=await e.getAuthInfo();return Ni=t.orgId,Vg=t.userId,$C=r,Ni}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Di=()=>{if(!Ni)throw new Error("Your organization ID is invalid.");return Ni},Cu=()=>{if(!Vg)throw new Error("Your user ID is invalid.");return Vg};var $g,Hg,YC=(r,e)=>{$g=r,Hg?.abort(),Hg=new AbortController;let t=Hg.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=iH.resolve(r.rootDir,o.envFile);try{if(Ru.lstatSync(i).isSymbolicLink())return;Ru.existsSync(i)&&n.push(i)}catch(a){R.warn({err:a},`Failed to check if env file ${i} exists`)}});try{sH({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){R.error({err:o},"Failed to start config file watchers")}},ze=()=>$g;function sH({filesToWatch:r,revalidator:e,signal:t,project:n}){R.debug("Starting watch on the following files:"),r.forEach(o=>{R.debug(`- ${o}`)}),r.forEach(o=>{let i=async(s,c)=>{s.mtime.getTime()!==c.mtime.getTime()&&(aH.increment("setLocalProject")&&R.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.`),$g=await Promise.resolve(e(n.configFilePath)))};Ru.watchFile(o,{persistent:!1},i);let a=()=>{Ru.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function Ve(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Ss=lH();function fs(r){let e=ze(),t=dt.dirname(e.configFilePath);return dt.join(t,...r)}function uH(r){let e=ze(),t=dt.dirname(e.configFilePath),n=dt.relative(t,r);return n?n.split(dt.sep):[]}function dH(r,e){let t=Dt.statSync(r),n=uH(r);return Zd.parse({name:e,absolutePath:r,relativePath:n.join(dt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}Ss.post("/",Ve(async(r,e,t)=>{let n;try{n=ly.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=fs(n);if(!Dt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(dt.sep)}`});return}if(!Dt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(dt.sep)}`});return}let a=ze(),s=Array.from(a.config.exclude??[]).concat(hl),l=cH("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let m=dt.join(o,d);return dH(m,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));Ss.put("/",Ve(async(r,e,t)=>{let n;try{n=cy.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=fs(n);if(Dt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(dt.sep)}`,pathSegments:n});return}Dt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(dt.sep)}`,pathSegments:n};e.status(201).json(i)}));Ss.patch("/",Ve(async(r,e,t)=>{let n,o;try{let l=uy.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=fs(n),a=fs(o);if(!Dt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(dt.sep)}`});return}if(Dt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(dt.sep)}`});return}let s=dt.dirname(a);Dt.existsSync(s)||Dt.mkdirSync(s,{recursive:!0}),Dt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(dt.sep)} to ${o.join(dt.sep)}`,pathSegments:o};e.status(200).json(c)}));Ss.delete("/",Ve(async(r,e,t)=>{let n,o=!0;try{let c=dy.parse(r.body);n=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let i=fs(n);if(!Dt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(dt.sep)}`,pathSegments:n});return}if(!Dt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(dt.sep)}`});return}if(o)Dt.rmSync(i,{recursive:!0,force:!0});else{if(Dt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Dt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var qg=Ss;import{Router as gH}from"express";import{hostname as mH}from"os";var pH="0.7.2",ys=qo({app:"desktop-server",hostname:mH(),disableConsoleLogs:!0}).child({cliVersion:pH});(async()=>{try{let r=await ds(ys);r.gitBranchName&&ys.addBinding("branch",r.gitBranchName)}catch{}})();var XC=gH();XC.get("/",async(r,e)=>{let t=ze(),n=hs();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await xi(ys,n,t);e.status(200).json(o)});var Kg=XC;import xH from"events";import lx,{Router as MH}from"express";import _H from"http";import PH from"path";var xu=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 JC=new xu;import{Router as fH}from"express";import{existsSync as SH}from"fs";import yH from"path";import{hostname as hH}from"os";var Yg="0.7.2",yt=qo({app:"mobile-desktop-server",hostname:hH(),disableConsoleLogs:!0}).child({cliVersion:Yg});(async()=>{try{let r=await ds(yt);r.gitBranchName&&yt.addBinding("branch",r.gitBranchName)}catch{}})();var Xg=fH();Xg.get("/",Ve(async(r,e)=>{let t=hs();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Xg.post("/upload-url",Ve(async(r,e)=>{let t;try{t=Sy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=hs();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=yH.resolve(t.filePath);if(!SH(o)){e.status(400).json({error:`File not found: ${o}`});return}await vc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:yt}),e.sendStatus(204)}));var ZC=Xg;import{Router as TH}from"express";import{Router as bH}from"express";import QC from"fs";import EH from"path";var bs=bH();async function Jg(r){return(await UC(r,yt)).map(n=>{let o=r.mobileModules[n.moduleId];if(!o){R.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)}bs.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await Jg(n);e.status(200).json(o)}));bs.get("/:moduleId",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await dr(ze()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Ig(n,t,R);e.json(o)}catch(o){e.status(400).json({err:o})}}));bs.patch("/:moduleId/metadata",Ve(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=yy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=ze(),o=await dr(n);DC({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:R,project:n}),e.status(201).json({message:"ok"})}));bs.post("/",Ve(async(r,e)=>{let t;try{t=by.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{ra(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=ze(),i=(await dr(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=EH.join(n.rootDir,t.folderPath??"");if(!QC.existsSync(a)||!QC.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await kC({...t,folder:a,project:n});e.status(201).json(s)}));var ex=bs;var tx=TH();tx.get("/",Ve(async(r,e)=>{let t=ze(),n=await dr(t),o=await Jg(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 rx=tx;import{Router as vH}from"express";var Zg=vH();Zg.get("/",Ve((r,e)=>{let t=wC(ze(),yt);e.status(200).json(t)}));Zg.get("/names",Ve((r,e)=>{let n=ze().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var nx=Zg;import{Router as AH}from"express";var ox=AH();ox.get("/",(r,e)=>{e.status(200).json({userId:Cu(),orgId:Di(),cliVersion:Yg??"0.0.0"})});var ix=ox;import{Router as wH}from"express";import Qg from"path";var Mu=wH();Mu.patch("/:testPath",Ve(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=fy.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=ze(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await dr(o);await BC({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));Mu.post("/",Ve((r,e)=>{let t;try{t=hy.parse(r.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});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{ra(n)}catch(g){e.status(400).json({error:g.message});return}let s=ze(),c=Qg.join(s.rootDir,...a),{fullPath:l,testId:u}=FC({name:n,description:o,steps:[],settings:i,folder:c}),d=Qg.basename(l),m=Qg.relative(s.rootDir,l),p={id:u,fileName:d,fullPath:l,relativeFilePath:m};e.status(201).json(p)}));Mu.get("/:fileName",Ve(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=ze(),i=await dr(o),s=await yu(n,yt,i);e.status(200).json(s)}));var ax=Mu;var _u=class extends Pi{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=ze();return ls(t,o,R)}};var cx="10mb";async function ux(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&qC(n),await KC(t);let u=Di(),d=Cu(),m=r.logger.child({orgId:u,userId:d});YC(i,w=>us({configFilePath:w}));let p=lx();p.use(RH()),p.use(sx.json({limit:cx})),p.use(sx.urlencoded({extended:!1,limit:cx}));let g=MH();if(g.use("/folders",qg),g.use("/entities",rx),g.use("/identify",ix),g.use("/mobile-tests",ax),g.use("/mobile-modules",ex),g.use("/assets",ZC),g.use("/git",Kg),g.use("/environments",nx),p.use("/api",g),p.use((w,D,j)=>{R.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"),D.on("close",()=>{D.statusCode>=400&&(R.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),yt.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),j()}),p.use((w,D,j,ie)=>{if(w instanceof Error&&w.message.includes("BadRequestError: request aborted")){j.status(400).send("Client disconnected");return}R.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),yt.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),j.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=lx.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});p.use(w),p.use("*",(D,j)=>{j.sendFile(PH.join(o,"index.html"))})}let h=_H.createServer(p),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{m.info(`Mobile desktop server is running at ${f}`),w()})}catch(D){D.message.includes("EADDRINUSE")?IH(e):R.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:jg(),apiKey:t,logger:m},x=new vr(b),T=ze(),v={...b,mode:"interactive"},{dispose:O}=vC({baseServer:h,logger:m,authorization:b,globalStateManager:JC,getOrgId:()=>Di(),androidDriverFactory:async({socket:w,logger:D,creationOpts:j})=>{let ie=Math.floor(Math.random()*1e4)+4e4,ee=await xl(ie,"appium");return Tc({logger:D,driverLogLevel:a,apiClient:x,creationOpts:j,socket:w,appiumPort:ee,sessionId:w.id,orgId:Di(),onStatusUpdate:fe=>{w.emit("connectionStatusUpdate",{message:fe})}})},mobileGeneratorFactory:async w=>new Li({baseUrl:jg(),apiKey:t,logger:m,mode:"interactive"}),browserGeneratorFactory:async w=>new bo(T.config.ai?.agentConfig,v),browserEnricherFactory:async w=>new _i(v,new bo(T.config.ai?.agentConfig,v)),storageFactory:async w=>new _u(x,w),cacheStorageFactory:async w=>{let D=await xi(m,x,T);return vu({orgId:w,client:x,gitMetadata:D,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Oi({httpClient:x,fakerSeed:void 0}),keepSessionAlive:w=>x.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:T.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await O(),await ft.flush()}catch(w){R.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()=>{R.info("SIGTERM in Momentic mobile app received");try{await O(),await ft.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{R.info("SIGINT in Momentic mobile app received");try{await O(),await ft.flush()}finally{h.close(()=>process.exit(0))}})}xH.setMaxListeners(25);process.on("warning",r=>{yt.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{yt.error({err:r},"Uncaught exception on mobile-desktop-server"),R.error(`Oh no! The Momentic mobile desktop app encountered a fatal error \u{1F61E}. Error logs: ${r.message}`)});process.on("unhandledRejection",r=>{yt.error({reason:`${r}`,stack:r?.stack},"Uncaught exception on mobile-desktop-server (promise rejection)"),R.error(`Oh no! The Momentic mobile desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${r}`)});function IH(r){R.error(CH`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4214
|
+
`;import{tool as kz}from"ai";import{randomUUID as Uz}from"crypto";import Fz from"zod";import{tool as Nz}from"ai";import Dz from"zod";var LC=r=>{let e=Nz({description:"Get the current state of the emulator (XML + screenshot)",inputSchema:Dz.object({}),toModelOutput:t=>t,execute:async()=>{let{controller:t,logger:n}=r;return n.info("AI action tool called (get_emulator_state)"),Ag(t)}});return{name:PC,tool:e}};async function Ag(r){let e=await r.getA11yTree(),t=await r.getScreenshotBase64();return{type:"content",value:[{type:"text",text:e},{type:"text",text:"</emulatorXml>"},{type:"text",text:"<screenshot>"},{type:"media",data:t,mediaType:"image/png"},{type:"text",text:"</screenshot>"}]}}var NC=r=>({name:"create_execute_step",tool:kz({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:Fz.object({step:Vd}),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=cy(t),s={id:Uz(),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 Ag(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 Bz}from"ai";import wg from"zod";var DC=r=>{let e=Bz({description:"Signal that the AI action has reached a terminal state (either success or failure).",inputSchema:wg.object({message:wg.string(),success:wg.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:pu,tool:e}};var kC=[NC,LC,DC];function UC(r){let{logger:e,controller:t,contextManager:n,aiActionSessionId:o}=r,i={};for(let c of kC){let l=c({contextManager:n,logger:e,controller:t});i[l.name]=l.tool}let a=t.generator.getVercelAnthropicModelFactory({loggerTags:ge(e),sessionId:o}),s=c=>{let{messages:l}=c,u=!1;for(let d=l.length-1;d>=0;d--){let p=l[d];for(let g of p.content)if(!(typeof g!="object"||!("type"in g))&&!(g.type!=="tool-result"||g.output.type!=="content")&&!(g.output.value.length<3))for(let m=0;m<g.output.value.length;m++){let h=g.output.value[m];if(h.type==="text"&&h.text.includes("<emulatorXml>"))if(u){let f=g.output.value[m+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:[Hz(15),zz(pu)],system:OC(!1)}}async function FC(r){let e=Date.now(),{controller:t,logger:n}=r.fixtures;try{return await jz(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 jz(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=Vz(),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]},p={stepId:e.id,parentStepIdChain:t.getParentStepIdChain()},g=new du({controller:o,callbacks:{onAiActionEvent:a?.onAiActionEvent,executeStep:d},logger:l,rootStep:p}),m=UC({controller:o,logger:l,contextManager:g,aiActionSessionId:c}),h=Gz({...m,messages:[{role:"user",content:e.text}]});for await(let f of h.fullStream)switch(f.type){case"text-delta":a?.onAiActionEvent?.({type:"LLM_TEXT_OUTPUT",text:f.text,rootStep:p})}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}}async function mu(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(),p=[],g,m="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 _=JSON.stringify(d);if(b.id===h.fromStepId&&_===JSON.stringify(h.parentStepIdChain))o.fastForwardingToStep=!1;else if(!kA({currentStep:b,currentParentChain:d,desiredStepId:h.fromStepId,desiredStepParentChain:h.parentStepIdChain}))continue}c.info({step:b},`Executing step ${E+1}/${a.length} in ${i} - ${PA(b)}`);let R=await s.startStep({logger:c,step:b,attempt:1,parentStepIdChain:d});u.trackStepExecution(b);let A=await Wz({step:b,stepTracer:R,params:r}),{trace:T}=await R.finish({parentStepIdChain:d,result:A});if(A.trace=T,c.info({step:{id:b.id},trace:A.trace,status:A.status},`Finished step ${E+1}/${a.length} (${b.type==="MOBILE_PRESET_STEP"?b.command.type:b.type})`),p.push(A),A.status!=="SUCCESS"){m=A.status,g=A;break}if(b.envKey&&l.context.setVariable(b.envKey,A.data),f){let _=JSON.stringify(d);if(b.id===f.toStepId&&_===JSON.stringify(f.parentStepIdChain)){o.shouldStopExecuting=!0;break}}if(o.shouldStopExecuting)break}return{results:p,status:m,terminalResult:g}}async function Wz({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 _C({fixtures:n,inputs:o,step:r,stepTracer:e,callbacks:i,work:a});break}case"RESOLVED_MOBILE_MODULE":{s=await xC({...t,moduleParams:{step:r,stepTracer:e,executeMobileStepList:mu}});break}case"MOBILE_AI_ACTION_STEP":{s=await FC({...t,aiActionParams:{step:r,stepTracer:e,executeMobileStepList:mu}});break}}return s}async function gu(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=qz(n);c.info({testMetadata:Mr.parse(o)},"Starting mobile test");let u=await e.startMainStepList(),d=nE(c),p=CC(s,c);c.info({cpu:d?.cpuMetadata,platform:d?.platform},`Starting execution of ${t}`);let{status:g,results:m}=await mu({...r,listParams:{containerName:t,tracer:u,steps:l}});if(clearInterval(d?.interval),clearInterval(p),g==="SUCCESS"){let h=$z(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 Cn({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:m}}return g==="CANCELLED"?{status:"CANCELLED",results:m}:{status:"FAILED",results:m}}var Rg=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 ho,Qr.initializeRootTracerContext(this.interactionTracer)}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}async finish(e){this.interactionTracer.finish();let t=this.interactionTracer.getRootSpan(),n={...Ub.parse(e),trace:qd.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 Mi({parentStep:this.step,socket:this.socket,parentTracer:this})}},Mi=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 Rg({step:e.step,parentTracer:this,socket:this.socket})}},hu=class{constructor(e){this.socket=e}appendLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Mi({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Mi({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Mi({parentStep:null,parentTracer:null,socket:this.socket})}};var Kz=({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 hu(n),p=await gu({work:{fastForwardingToStep:!!i.fromStep},fixtures:{controller:u,logger:c,cacheStorage:l,usageTracker:new Zs},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:m=>{n.emit("aiActionEvent",m)}}}});await d.finish();let g={results:rr.array().parse(p.results),status:p.status};a?.(g)},BC={event:"execute",createHandler:Kz};import{debounce as Yz}from"ts-debounce";var Xz=({socket:r,globalStateManager:e,keepSessionAlive:t})=>{let n=Yz(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))}},zC={event:"keepalive",createHandler:Xz};var HC=[BC,wC,zC,RC];function GC(r){let{logger:e,baseServer:t,globalStateManager:n}=r,o=new Jz(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 AC({socket:s,globalStateManager:n,logger:l})});let u;try{u=await vC({...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}HC.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 p=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:`${g}`})};try{let g=l.apply(this,d);g&&typeof g.catch=="function"&&g.catch(p)}catch(g){p(g)}};c.socket.on(s.event,u)};return{server:o,dispose:i}}import{randomUUID as tG}from"crypto";import{diff as _Oe}from"deep-object-diff";import zOe from"yaml";import{z as GOe}from"zod";import{execSync as Zz}from"child_process";function Nn(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{Zz(n,{encoding:"utf-8"})}catch(o){C.warn({err:o,postSaveCommand:n},"Failed to execute post-save hook command, continuing...")}}import{diff as aOe}from"deep-object-diff";import{cloneDeep as lOe}from"lodash-es";import{v4 as EOe}from"uuid";import vOe from"yaml";import Qz from"@dotenvx/dotenvx";import e1 from"fs";import VC from"path";function jC(r,e){return(r.config.environments??[]).map(t=>cs(t.name,r,e))}function t1(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 r1(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=t1(i);s&&(n[o]=s);continue}let a;try{a=e1.readFileSync(VC.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 n1(r){let{project:e,envFile:t,logger:n}=r,o={};if(!t)return o;let i=Qz.config({path:VC.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 cs(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=r1({envVariables:n.envVariables,project:e});Object.assign(o,i);let a=n1({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 f1,readFileSync as S1,readdirSync as y1,writeFileSync as b1}from"fs";import{glob as E1}from"glob";import So,{dirname as qC}from"path";import{cwd as Pg}from"process";import KC from"yaml";import{z as Pe}from"zod";import WC from"fs";import{glob as o1}from"glob";import us from"path";import i1 from"yaml";import{z as Cg}from"zod";var $C=!1,xg=["**/*.test.yaml","**/*.module.yaml"],Mg=Cg.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),_g=15,a1=Cg.object({fileType:Cg.nativeEnum(xe)});async function dr(r,e=!1){let t={project:r,tests:{},modules:{},mobileTests:{},mobileModules:{},duplicateEntities:{}},n=r.config.include??xg,o=Array.from(r.config.exclude??[]).concat(hl),i=AbortSignal.timeout(5e3),a;try{a=await o1(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:_g,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=s1(r.rootDir,s,t,e?fn:C);c&&(t.duplicateEntities[c.id]=c.paths)}return $C=!0,t}function s1(r,e,t,n){let o=us.join(r,e),i=l1(o,n);if(!i)return;let a=c1(i,o,n);if(!a)return;let s=a1.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=u1(o,n);if(!l)return;let u=d1(e,o,l);switch(c){case xe.TEST:try{return p1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case xe.MODULE:try{return m1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}case xe.MOBILE_TEST:try{return h1(a,t,u,o,n)}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${d}`);return}case xe.MOBILE_MODULE:try{return g1(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 l1(r,e){try{return WC.readFileSync(r,"utf-8")}catch(t){e.warn(`Could not read possible Momentic file at ${r}, skipping: ${t}`);return}}function c1(r,e,t){try{let n=i1.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 u1(r,e){try{return WC.statSync(r)}catch(t){e.warn(`Skipping path '${r}' because it could not be stat, skipping: ${t}`);return}}function d1(r,e,t){return{relativePath:r,fullFilePath:e,platformSep:us.sep,fullPathSegments:e.split(us.sep),relativePathSegments:r.split(us.sep),fileName:us.basename(e),lastModified:t.mtime,createdAt:t.birthtime}}function p1(r,e,t,n,o){let i=Wo.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:xe.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...t},a}function m1(r,e,t,n,o){let i=Xt.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:xe.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...t};let s=t.fileName.replace(".module.yaml","");return!$C&&qr(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 g1(r,e,t,n,o){let i=ha.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:xe.MOBILE_MODULE,name:s,id:i.moduleId,description:i.description??void 0,...t},a}function h1(r,e,t,n,o){let i=Mr.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:xe.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...t},a}var _i="momentic.config.yaml",Ig="momentic.workspace.yaml",T1=Pe.object({projects:Pe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),v1=Pe.union([Pe.string(),Pe.object({fromFile:Pe.string(),json:Pe.boolean().optional()})]),A1=Pe.object({name:Mg,baseUrl:Pe.string().optional().describe("Optional for mobile tests"),envFile:Pe.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Pe.record(Pe.string(),v1).optional(),inheritFromShell:Pe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:$n.optional().describe("NB: most things should use project-level configuration only")}),w1=Pe.object({postSave:Pe.string().optional()}),R1=Pe.object({name:Mg,include:Pe.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Pe.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Pe.string().optional(),reporterDir:Pe.string().optional(),outputDir:Pe.string().optional(),recordVideo:Pe.boolean().optional(),retries:Pe.number().optional().describe("number of retries per test"),parallel:Pe.number().optional().describe("degree of parallelism"),environments:Pe.array(A1).optional(),gitMainBranch:Pe.string().optional(),gitProtectedBranches:Pe.string().array().optional(),ai:rp.optional(),browser:$n.optional(),emulator:$d.optional(),advanced:np.optional(),hooks:w1.optional()});function YC(r,e){let t;try{t=S1(r,"utf-8")}catch(o){C.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=KC.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 Og(r){let e=YC(r,"project configuration");if(e!==void 0)try{return R1.parse(e)}catch(t){C.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function C1(r){let e=YC(r,"workspace configuration");if(e!==void 0)try{return T1.parse(e)}catch(t){C.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function x1(){let r=[],e=Pg(),t=So.parse(e).root,n=15,o=0;for(;o<n;){o++;let i=So.basename(e);if(gl.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 y1(e))if(a.endsWith(_i)){let s=So.join(e,a),c=Og(s);c&&r.push({configFilePath:s,config:c,rootDir:qC(s)})}if(r.length)return r;if(e=So.dirname(e),e===t)break}return r}async function ds(r={}){let{configFilePath:e,nameFilter:t}=r,n=await _1(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:
|
|
4215
|
+
${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 M1(r){let e=C1(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${_i}`)),n=AbortSignal.timeout(2e3),o;try{o=await E1(t,{absolute:!1,cwd:Pg(),dotRelative:!1,maxDepth:_g,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 ${Ig} is misconfigured.`),a}let i=[];for(let a of o){let s=So.join(Pg(),a),c=Og(s);c&&i.push({configFilePath:s,config:c,rootDir:qC(s)})}return i}async function _1(r){if(r){r=So.resolve(r);let t=Og(r);return t||(console.error(`No valid Momentic project file found at ${r}.`),process.exit(1)),[{config:t,configFilePath:r,rootDir:So.dirname(r)}]}if(f1(Ig)){let t=await M1(Ig);if(t)return t}return x1()}function XC(r,e){let t=KC.stringify(r);b1(e,t)}import{z as Lg}from"zod";var JC="test-results";var CLe=Lg.object({width:Lg.number(),height:Lg.number()});import{execFile as P1}from"node:child_process";import{promisify as I1}from"node:util";import O1 from"simple-git";var Oe=O1(),ZC=I1(P1);async function L1(r){let e=await Le(r,Oe.raw(["config","--list"])),t={};if(!e)return t;for(let n of e.split(`
|
|
4216
|
+
`)){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 N1(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 ZC("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 ZC("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function D1(r,e,t){let n=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(n)return N1(r,e,t);if(o)return}catch{}}function fu(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 Le(r,e){try{return(await e).trim()}catch(t){r.error({err:t},"Failed to run git command");return}}function k1(){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 U1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.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 F1(r){let[e,t,n]=await Promise.all([Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.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 B1(r){let[e,t,n,o]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?fu(t):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:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:n,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function z1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?fu(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 H1(r){let[e,t,n]=await Promise.all([Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?fu(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 G1(r,e){let[t,n,o,i,a,s,c,l,u]=await Promise.all([Le(r,Oe.revparse(["HEAD"])),Le(r,Oe.revparse(["--short","HEAD"])),Le(r,Oe.revparse(["--abbrev-ref","HEAD"])),Le(r,Oe.listRemote(["--get-url","origin"])),Le(r,Oe.show(["--no-patch","--format=%ci"])),Le(r,Oe.show(["-s","--pretty=%B"])),Le(r,Oe.show(["-s","--pretty=%an"])),e?Le(r,Oe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),L1(r)]),d=l?await Le(r,Oe.show(["--no-patch","--format=%ci",l])):void 0,p=i?.includes("github.com"),g=i?.includes("gitlab.com"),m=i?fu(i):void 0,h=u["user.email"]||void 0,f=u["user.name"]||void 0,E=u["user.username"]||void 0,b=await D1(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:p?m:void 0,gitlabProjectPath:g?m:void 0,pipelineId:void 0}}async function V1(){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 j1(r){let e=r.config.gitProtectedBranches??[];return r.config.gitMainBranch&&e.push(r.config.gitMainBranch),{gitMainBranch:r.config.gitMainBranch,gitProtectedBranches:e}}async function ps(r,e){let t=k1();if(!t)return G1(r,e);switch(t){case"GithubActions":return U1(r);case"GitlabCI":return F1(r);case"CircleCI":return B1(r);case"Buildkite":return z1(r);case"AzureDevOps":return H1(r);case"GCPCloudBuild":return V1()}}async function W1(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 $1(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 q1(r,e,t){try{if(t.githubRepository){let[n,o]=t.githubRepository.split("/");return await $1(r,e,n,o,t)}else if(t.gitlabProjectPath)return await W1(r,e,t.gitlabProjectPath,t)}catch(n){r.warn({err:n},"Failed to get remote git metadata")}return t}async function Pi(r,e,t){let n=await j1(t),o=await ps(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 q1(r,e,i);return{...n,...o,...a}}import{diff as QC}from"deep-object-diff";import Dn from"fs";import{cloneDeep as K1}from"lodash-es";import Su from"path";import{v4 as Y1}from"uuid";import ms from"yaml";function ex({content:r,schemaVersion:e,momenticFiles:t,project:n,forceSaveOnNoDiffs:o}){let i=t.mobileModules[r.moduleId]?.fullFilePath;if(!i||!Dn.existsSync(i))throw new Error(`Tried to update mobile module ${r.moduleId} that could not be found on disk`);let a=Dn.readFileSync(i,"utf-8"),s=ms.parse(a),c={...s,...r,schemaVersion:e},l=lo({fileType:xe.MOBILE_MODULE,...ha.parse(c),steps:fr.array().parse(r.steps)}),u=QC(l,s);if(u&&Object.keys(u).length===0&&!o)return;let d=ms.stringify(l);Dn.writeFileSync(i,d,"utf-8"),Nn(i,n.config)}function tx({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=gs(i,o),s={...a,...e},c=lo({fileType:xe.MOBILE_MODULE,...cl.parse(s)}),l=QC(c,a);if(l&&Object.keys(l).length===0)return;let u=ms.stringify(c);Dn.writeFileSync(i,u,"utf-8");let d;if(e.name){let p=`${qr(e.name)}.module.yaml`;if(d=Su.join(Su.dirname(i),p),Dn.existsSync(d))throw new Error(`A conflicting file already exists at the following path: ${d}`);Dn.renameSync(i,d)}Nn(d||i,n.config)}async function rx({name:r,description:e,enabled:t,steps:n,folder:o,project:i}){let a=qr(r),s=Su.join(o,`${a}.module.yaml`),c=Y1(),{stepsToSave:l}=await Cn({steps:n}),u={schemaVersion:ln,moduleId:c,description:e,enabled:t},d={fileType:xe.MOBILE_MODULE,...u,steps:l},p=ms.stringify(yy.parse(d));return Dn.writeFileSync(s,p,"utf-8"),Nn(s,i.config),{moduleId:c,name:r,description:e||void 0,steps:n}}function gs(r,e){let t=Dn.readFileSync(r,"utf-8"),n=ms.parse(t);try{return{...cl.parse(n),name:Su.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 Ng(r,e,t,n){let o=gs(r.fullFilePath,t),{resolvedSteps:i}=await xc({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 gs(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]=K1(a)),a}async function nx(r,e){let t={};return await Promise.all(Object.values(r.mobileModules).map(async n=>{await Ng(n,r,e,t)})),Array.from(Object.values(t))}import{randomUUID as X1}from"crypto";import yo from"fs";import Dg from"path";import yu from"yaml";function ox({name:r,description:e="",steps:t=[],settings:n={},folder:o}){let a=`${qr(r)}.test.yaml`,s=Dg.join(o,a);if(yo.existsSync(s))throw new Error(`A test named '${r}' already exists at path '${s}'. Choose a different name.`);let c={fileType:xe.MOBILE_TEST,id:X1(),description:e,schemaVersion:md,settings:n,steps:t},l=yu.stringify(c);return yo.writeFileSync(s,l,"utf-8"),{fullPath:s,testId:c.id}}function J1(r){if(!yo.existsSync(r))throw new Error(`Test file not found: ${r}`);let e=yo.readFileSync(r,"utf-8").replace(/\r\n|\r/g,`
|
|
4217
|
+
`),t=yu.parse(e),n=ul.parse(t);if(n.fileType!==xe.MOBILE_TEST)throw new Error(`File is not a mobile test (fileType=${n.fileType}): ${r}`);return n}async function bu(r,e,t){let n=J1(r),o;try{o=Mr.parse(n)}catch(s){throw new Error(`Mobile test ${r} is missing metadata or has invalid metadata: ${s}`)}let{resolvedStepLists:i}=await OA({rawStepLists:{steps:n.steps,beforeSteps:void 0,afterSteps:void 0},logger:e,testMetadata:o,onFetchModule:async s=>{let c=t.mobileModules[s]?.fullFilePath;if(!c)throw new Error(`Mobile module ${s} not found`);return gs(c,e)}});return{...o,steps:i.steps}}async function ix({filePath:r,steps:e,settings:t,folder:n,project:o,momenticFiles:i}){let a=Dg.isAbsolute(r)?r:Dg.join(n,r);if(!yo.existsSync(a))throw new Error(`Test file not found: ${a}`);let s=yo.readFileSync(a,"utf-8").replace(/\r\n|\r/g,`
|
|
4218
|
+
`),c=yu.parse(s),l=ul.parse(c);if(l.fileType!==xe.MOBILE_TEST)throw new Error(`File at '${a}' is not a mobile test (fileType=${l.fileType}).`);let u;e&&(u=await Cn({steps:e}));let d={...l,...u?.stepsToSave!==void 0?{steps:u.stepsToSave}:{},...t!==void 0?{settings:t}:{}},p=yu.stringify(ul.parse(d));for(let g of u?.moduleUpdates??[])ex({content:g,schemaVersion:md,momenticFiles:i,project:o});yo.writeFileSync(a,p,"utf-8"),Nn(a,o.config)}import{randomUUID as Z1}from"crypto";import kn from"fs";import Ii from"path";var ax=new Set([".DS_Store","__MACOSX"]),sx={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 Q1(r,e,t){if(sx[t]){let i=sx[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 kg=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 lx(r,e){try{let t=Ii.join(e,"metadata.json");return Al.parse(JSON.parse(kn.readFileSync(t,"utf-8")))}catch{throw new kg(r,e)}}function cx(r,e,t){let n=Z1(),o=r.child({runGroupId:n});kn.rmSync(e,{recursive:!0,force:!0});let i=kn.readdirSync(t).filter(c=>!ax.has(c)).map(c=>Ii.join(t,c));if(i.length===0)throw new Error(`No run groups found in results path: ${t}`);kn.mkdirSync(e,{recursive:!0});let a={...lx(t,i[0]),id:n};for(let c of i){let l=Ii.join(c,"runs");if(!kn.existsSync(l))continue;let u=lx(t,c);o.info({oldRunGroupId:u.id},"Merging run groups");for(let p in u){if(p==="id")continue;let g=p;a[g]=Q1(a,u,g)}let d=kn.readdirSync(l);for(let p of d){if(ax.has(p))continue;let g=Ii.join(l,p),m=Ii.join(e,"runs",p);kn.cpSync(g,m,{recursive:!0})}}let s=Ii.join(e,"metadata.json");kn.writeFileSync(s,JSON.stringify(a,null,2))}import dx from"adm-zip";import Gg from"fs";import{z as aH}from"zod";var U="v1",Ug="mobile-cli",bo="0.8.0";var eH=9e4,tH=3,rH=1500,nH=15e3,Tr=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function oH(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Fg=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return bo&&(e[El]=bo),Ug&&(e[Wy]=Ug),e}async sendRequest(e,t){let{retries:n=tH,requestTimeoutMs:o=eH,initialRetryDelayMs:i=rH,maxRetryDelayMs:a=nH,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(p){u=p;try{s?.(u)}catch{}if(p instanceof Tr&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(u=new Sn),c===0)throw u;let g=l-c,m=Math.min(i*Math.pow(2,g-1),a);await new Promise(h=>setTimeout(h,m))}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 p=await oH(u);throw new Tr(u.status,p,`Request to ${t.method} ${e} failed with status ${u.status}: ${p}`)}let d;if(u.status===204)d={};else{let p=await u.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&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)}}},Gr=class extends Fg{apiKey;mode;constructor(e){super(e),this.apiKey=e.apiKey,this.mode=e.mode}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`,[jy]:this.mode??""}}};import{createAnthropic as iH}from"@ai-sdk/anthropic";var Eu=({baseUrl:r,apiKey:e,sessionId:t,extraHeaders:n,loggerTags:o})=>i=>{let a={Authorization:`Bearer ${e}`,[El]:bo??"",...t&&{[qy]:t},...n||{}};return o&&(a[$y]=JSON.stringify(o)),iH({baseURL:`${r}/v1/llm/anthropic/${i}`,headers:a,apiKey:e})(i)};var Eo=class extends Gr{agentConfig;constructor(e,t){let n={...WS,...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 OS.parse(o)}async rankChunksWithRag(e,t){let n=await this.sendRequest(`/${U}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:bo,...e},signal:t.abortSignal});return IS.parse(n)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${U}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return aH.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 Jy.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 ip.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 Xy.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 Yy.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 ip.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 Ky.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 fd.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 Zy.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 gd.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 uS.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 dS.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 Qu.parse(n)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${U}/web-agent/extract-keywords`,{method:"POST",body:e,signal:t.abortSignal});return jS.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 iS.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 lS.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 sS.parse(n)}async getIframeRegex(e,t){let n=await this.sendRequest(`/${U}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Eh.parse(n)}getVercelAnthropicModelFactory({loggerTags:e}){return Eu({baseUrl:this.baseUrl,apiKey:this.apiKey,loggerTags:e})}};import{z as Bg}from"zod";var vr=class extends Gr{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 db.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${U}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return sb.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${U}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return eb.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 rb.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 nb.parse(n)}async queueTests(e){let t=await this.sendRequest(`/${U}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Qy.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${U}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return ub.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${U}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return pb.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 xb.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 mb.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 xS.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 gb.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 hb.parse(n)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${U}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return fb.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 Sb.parse(n)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${U}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Pb.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 Aa.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 Aa.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 cp.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 Aa.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 Aa.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 cp.parse(a)}async getAgentConfig(){let e=await this.sendRequest(`/${U}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Bg.record(Bg.string(),Bg.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${U}/quarantine`,{method:"GET"});return yb.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 bb.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 Eb.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 Tb.parse(e)}async deleteAndroidAsset(e,t){await this.sendRequest(`/${U}/limbar/assets/${e}/${t}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function zg(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 Tu=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvents(e,t){await this.apiClient.reportBillableEvents(e,t)}};var Oi=class extends Gr{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 Th.parse(n)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};var Li=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 sH,en as lH}from"@faker-js/faker";var Ni="v1",Di=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 sH({locale:lH}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ni}/tools/ai/generate`,{method:"POST",body:t}).catch(n=>{throw n instanceof Tr?new Error(n.rawError):new Error(`Failed to send AI generation: ${n.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ni}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ni}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ni}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ni}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ni}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Tr?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};function ux(r,e,t){return fetch(r,{method:"PUT",body:t,headers:{"Content-Type":e}})}var vu=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:n,id:o}=await this.client.generateTestResultsUploadUrl(),i=await ux(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 ki=class extends Gr{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 qS.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 XS.parse(o)}getVercelAnthropicModelFactory({loggerTags:e,sessionId:t}){return Eu({baseUrl:this.baseUrl,apiKey:this.apiKey,sessionId:t,loggerTags:e})}};function Au({orgId:r,client:e,gitMetadata:t,regenerateCache:n,alwaysSaveCache:o,noCache:i}){return i?new vl:new Hg(r,e,t,o)}var Hg=class{constructor(e,t,n,o){this.orgId=e;this.client=t;let{gitBranchName:i,gitProtectedBranches:a}=n;this.cacheHeaders=ap(n),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;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){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&&vm({steps:i,stepCacheEntries:n,logger:e.logger});let{cachesToSave:o}=await Cn({steps:t,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateMobileStepCaches({entries:o,testId:e.testId},this.cacheHeaders)}};import wu from"path";function cH(r){let e=new dx,t=wu.join(r,"metadata.json"),n=Al.parse(JSON.parse(Gg.readFileSync(t,"utf-8")));e.addLocalFile(t);for(let o of Gg.readdirSync(wu.join(r,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new dx(wu.join(r,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(wu.join("runs",i,s.entryName),s.getData())}return{runGroupId:n.id,buffer:e.toBuffer()}}async function Ru(r){let{client:e,consoleLogger:t,resultsPath:n}=r;if(!Gg.existsSync(n)){t.warn("Results path does not exist, skipping upload.");return}let o=new vu(e);try{let{runGroupId:i,buffer:a}=cH(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 uH from"adm-zip";import bt from"fs";import Wt from"path";var hs=class r{constructor(e){this.filePath=e;bt.rmSync(this.filePath,{recursive:!0,force:!0}),bt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new r(Wt.join(this.filePath,e))}cwd(){return this.filePath}mkdir(e){bt.mkdirSync(Wt.join(this.filePath,e),{recursive:!0})}readFile(e){let t=Wt.join(this.filePath,e);if(bt.existsSync(t))return bt.readFileSync(t)}storeFile(e){let{name:t,contents:n}=e,o=Wt.join(this.filePath,t);try{bt.writeFileSync(o,n)}catch{}}createFileStream(e){let t=Wt.join(this.filePath,e);return bt.createWriteStream(t)}createRunArchive(e){return new Vg(Wt.join(this.filePath,"runs"),e)}},Vg=class{constructor(e,t){this.filePath=e;this.tempPath=Wt.join(e,`.${t}`),this.finalPath=Wt.join(e,`${t}.zip`),bt.rmSync(this.tempPath,{recursive:!0,force:!0}),bt.rmSync(this.finalPath,{recursive:!0,force:!0}),bt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let t=Wt.join(this.tempPath,e);if(bt.existsSync(t))return bt.readFileSync(t)}mkdir(e){bt.mkdirSync(Wt.join(this.tempPath,e),{recursive:!0})}cd(e){return new hs(Wt.join(this.tempPath,e))}cwd(){return this.tempPath}storeFile(e){let{name:t,contents:n}=e,o=Wt.join(this.tempPath,t);bt.writeFileSync(o,n)}createFileStream(e){let t=Wt.join(this.tempPath,e);return bt.createWriteStream(t)}close(){let e=new uH;e.addLocalFolder(this.tempPath,void 0,n=>n!==".DS_Store");let t=e.toBuffer();bt.writeFileSync(this.finalPath,t),bt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import Lu from"fs";import xx from"body-parser";import IH from"cors";import OH from"dedent";import{Router as gH}from"express";import Dt from"fs";import{globSync as hH}from"glob";import mt from"path";import Cu from"fs";import dH from"path";var pH=new kc(30,60*1e3),qg="https://api.momentic.ai",Wg,mx=r=>{qg=r},Kg=()=>qg,fs=()=>Wg;var Ui,$g,px,gx=async r=>{if(Wg&&Ui&&px)return Ui;let e=new vr({baseUrl:qg,apiKey:r,logger:C});Wg=e;try{let t=await e.getAuthInfo();return Ui=t.orgId,$g=t.userId,px=r,Ui}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Fi=()=>{if(!Ui)throw new Error("Your organization ID is invalid.");return Ui},xu=()=>{if(!$g)throw new Error("Your user ID is invalid.");return $g};var Yg,jg,hx=(r,e)=>{Yg=r,jg?.abort(),jg=new AbortController;let t=jg.signal,n=[r.configFilePath];r.config.environments?.forEach(o=>{if(!o.envFile)return;let i=dH.resolve(r.rootDir,o.envFile);try{if(Cu.lstatSync(i).isSymbolicLink())return;Cu.existsSync(i)&&n.push(i)}catch(a){C.warn({err:a},`Failed to check if env file ${i} exists`)}});try{mH({filesToWatch:n,revalidator:e,signal:t,project:r})}catch(o){C.error({err:o},"Failed to start config file watchers")}},Ge=()=>Yg;function mH({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()&&(pH.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.`),Yg=await Promise.resolve(e(n.configFilePath)))};Cu.watchFile(o,{persistent:!1},i);let a=()=>{Cu.unwatchFile(o,i),t.removeEventListener("abort",a)};t.addEventListener("abort",a),process.once("SIGUSR2",()=>{a(),process.kill(process.pid,"SIGUSR2")})})}function We(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var ys=gH();function Ss(r){let e=Ge(),t=mt.dirname(e.configFilePath);return mt.join(t,...r)}function fH(r){let e=Ge(),t=mt.dirname(e.configFilePath),n=mt.relative(t,r);return n?n.split(mt.sep):[]}function SH(r,e){let t=Dt.statSync(r),n=fH(r);return Qd.parse({name:e,absolutePath:r,relativePath:n.join(mt.sep),pathSegments:n,isDirectory:t.isDirectory(),size:t.size,createdAt:t.birthtime,modifiedAt:t.mtime,accessedAt:t.atime})}ys.post("/",We(async(r,e,t)=>{let n;try{n=Py.parse(r.body).pathSegments}catch(d){e.status(400).json({error:`Failed to parse folder read body: ${d}`});return}let o=Ss(n);if(!Dt.existsSync(o)){e.status(404).json({error:`Path not found: ${n.join(mt.sep)}`});return}if(!Dt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(mt.sep)}`});return}let a=Ge(),s=Array.from(a.config.exclude??[]).concat(hl),l=hH("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(d=>{let p=mt.join(o,d);return SH(p,d)}),u={absolutePath:o,pathSegments:n,contents:l};e.status(200).json(u)}));ys.put("/",We(async(r,e,t)=>{let n;try{n=Iy.parse(r.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=Ss(n);if(Dt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${n.join(mt.sep)}`,pathSegments:n});return}Dt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${n.join(mt.sep)}`,pathSegments:n};e.status(201).json(i)}));ys.patch("/",We(async(r,e,t)=>{let n,o;try{let l=Oy.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=Ss(n),a=Ss(o);if(!Dt.existsSync(i)){e.status(400).json({error:`Folder not found: ${n.join(mt.sep)}`});return}if(Dt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(mt.sep)}`});return}let s=mt.dirname(a);Dt.existsSync(s)||Dt.mkdirSync(s,{recursive:!0}),Dt.renameSync(i,a);let c={success:!0,message:`Folder moved from ${n.join(mt.sep)} to ${o.join(mt.sep)}`,pathSegments:o};e.status(200).json(c)}));ys.delete("/",We(async(r,e,t)=>{let n,o=!0;try{let c=Ly.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=Ss(n);if(!Dt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${n.join(mt.sep)}`,pathSegments:n});return}if(!Dt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${n.join(mt.sep)}`});return}if(o)Dt.rmSync(i,{recursive:!0,force:!0});else{if(Dt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${n.join("/")}`});return}Dt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${n.join("/")}`,pathSegments:n};e.status(200).json(s)}));var Xg=ys;import{Router as EH}from"express";import{hostname as yH}from"os";var bH="0.8.0",bs=Xo({app:"desktop-server",hostname:yH(),disableConsoleLogs:!0}).child({cliVersion:bH});(async()=>{try{let r=await ps(bs);r.gitBranchName&&bs.addBinding("branch",r.gitBranchName)}catch{}})();var fx=EH();fx.get("/",async(r,e)=>{let t=Ge(),n=fs();if(!n){e.status(500).json({message:"API client not initialized"});return}let o=await Pi(bs,n,t);e.status(200).json(o)});var Jg=fx;import LH from"events";import Mx,{Router as NH}from"express";import DH from"http";import kH from"path";var Mu=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 Sx=new Mu;import{Router as vH}from"express";import{existsSync as AH}from"fs";import wH from"path";import{hostname as TH}from"os";var Zg="0.8.0",Et=Xo({app:"mobile-desktop-server",hostname:TH(),disableConsoleLogs:!0}).child({cliVersion:Zg});(async()=>{try{let r=await ps(Et);r.gitBranchName&&Et.addBinding("branch",r.gitBranchName)}catch{}})();var Qg=vH();Qg.get("/",We(async(r,e)=>{let t=fs();if(!t){e.status(500).json({message:"API client not initialized"});return}let n=await t.getAndroidAssets();e.status(200).json(n)}));Qg.post("/upload-url",We(async(r,e)=>{let t;try{t=By.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=fs();if(!n){e.status(500).json({error:"API client not initialized"});return}let o=wH.resolve(t.filePath);if(!AH(o)){e.status(400).json({error:`File not found: ${o}`});return}await vc({tag:t.tag,channel:t.channel,filePath:o,apiClient:n,logger:Et}),e.sendStatus(204)}));var yx=Qg;import{Router as xH}from"express";import{Router as RH}from"express";import bx from"fs";import CH from"path";var Es=RH();async function eh(r){return(await nx(r,Et)).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)}Es.get("/",We(async(r,e)=>{let t=Ge(),n=await dr(t),o=await eh(n);e.status(200).json(o)}));Es.get("/:moduleId",We(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await dr(Ge()),n=t.mobileModules[r.params.moduleId];if(!n){e.status(404).json({error:"Mobile module not found."});return}try{let o=await Ng(n,t,C);e.json(o)}catch(o){e.status(400).json({err:o})}}));Es.patch("/:moduleId/metadata",We(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t;try{t=zy.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let n=Ge(),o=await dr(n);tx({moduleId:r.params.moduleId,patch:t,momenticFiles:o,logger:C,project:n}),e.status(201).json({message:"ok"})}));Es.post("/",We(async(r,e)=>{let t;try{t=Hy.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{ra(t.name)}catch(c){e.status(400).json({error:`Invalid module name: ${c}`});return}let n=Ge(),i=(await dr(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=CH.join(n.rootDir,t.folderPath??"");if(!bx.existsSync(a)||!bx.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for mobile module creation does not exist: ${a}`});return}let s=await rx({...t,folder:a,project:n});e.status(201).json(s)}));var Ex=Es;var Tx=xH();Tx.get("/",We(async(r,e)=>{let t=Ge(),n=await dr(t),o=await eh(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 vx=Tx;import{Router as MH}from"express";var th=MH();th.get("/",We((r,e)=>{let t=jC(Ge(),Et);e.status(200).json(t)}));th.get("/names",We((r,e)=>{let n=Ge().config.environments?.map(o=>o.name)??[];e.status(200).json(n)}));var Ax=th;import{Router as _H}from"express";var wx=_H();wx.get("/",(r,e)=>{e.status(200).json({userId:xu(),orgId:Fi(),cliVersion:Zg??"0.0.0"})});var Rx=wx;import{Router as PH}from"express";import rh from"path";var _u=PH();_u.patch("/:testPath",We(async(r,e)=>{let t=r.params.testPath;if(!t){e.status(400).json({error:"Missing testPath in path"});return}let n;try{n=Fy.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=Ge(),i=t.endsWith(".test.yaml")?t:`${t}.test.yaml`,a=await dr(o);await ix({filePath:i,steps:n.steps,settings:n.settings,folder:o.rootDir,project:o,momenticFiles:a});let s={message:"ok"};e.status(200).json(s)}));_u.post("/",We((r,e)=>{let t;try{t=Uy.parse(r.body)}catch(m){e.status(400).json({error:`Invalid request body: ${m}`});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{ra(n)}catch(m){e.status(400).json({error:m.message});return}let s=Ge(),c=rh.join(s.rootDir,...a),{fullPath:l,testId:u}=ox({name:n,description:o,steps:[],settings:i,folder:c}),d=rh.basename(l),p=rh.relative(s.rootDir,l),g={id:u,fileName:d,fullPath:l,relativeFilePath:p};e.status(201).json(g)}));_u.get("/:fileName",We(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=Ge(),i=await dr(o),s=await bu(n,Et,i);e.status(200).json(s)}));var Cx=_u;var Pu=class extends Li{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async fetchEnvironment(t,n){let o=Ge();return cs(t,o,C)}};var _x="10mb";async function Px(r){let{serverPort:e,apiKey:t,momenticServerUrl:n,staticDir:o,initialProject:i,driverLogLevel:a,regenerateCache:s,alwaysSaveCache:c,noCache:l}=r;n&&mx(n),await gx(t);let u=Fi(),d=xu(),p=r.logger.child({orgId:u,userId:d});hx(i,w=>ds({configFilePath:w}));let g=Mx();g.use(IH()),g.use(xx.json({limit:_x})),g.use(xx.urlencoded({extended:!1,limit:_x}));let m=NH();if(m.use("/folders",Xg),m.use("/entities",vx),m.use("/identify",Rx),m.use("/mobile-tests",Cx),m.use("/mobile-modules",Ex),m.use("/assets",yx),m.use("/git",Jg),m.use("/environments",Ax),g.use("/api",m),g.use((w,D,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"),D.on("close",()=>{D.statusCode>=400&&(C.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"),Et.error({url:w.url,method:w.method,statusCode:D.statusCode},"Request completed in error on mobile-desktop-server"))}),G()}),g.use((w,D,G,ee)=>{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:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),Et.error({stack:w.stack,msg:w.message,err:w,url:D.url,method:D.method},"Unhandled exception leading to 500 on mobile-desktop-server"),G.status(500).send(`Internal Server Error: ${w.message}`)}),o){let w=Mx.static(o,{setHeaders:D=>{D.setHeader("Cache-Control","no-cache")},redirect:!1});g.use(w),g.use("*",(D,G)=>{G.sendFile(kH.join(o,"index.html"))})}let h=DH.createServer(g),f=`http://localhost:${e}`;await new Promise(w=>{try{h.listen(e,()=>{p.info(`Mobile desktop server is running at ${f}`),w()})}catch(D){D.message.includes("EADDRINUSE")?UH(e):C.error(`An unexpected error occurred while starting the server: ${D.message}`),process.exit(1)}});let b={type:"API_KEY",baseUrl:Kg(),apiKey:t,logger:p},R=new vr(b),A=Ge(),T={...b,mode:"interactive"},{dispose:_}=GC({baseServer:h,logger:p,authorization:b,globalStateManager:Sx,getOrgId:()=>Fi(),androidDriverFactory:async({socket:w,logger:D,creationOpts:G})=>{let ee=Math.floor(Math.random()*1e4)+4e4,Te=await xl(ee,"appium");return Tc({logger:D,driverLogLevel:a,apiClient:R,creationOpts:G,socket:w,appiumPort:Te,sessionId:w.id,orgId:Fi(),onStatusUpdate:fe=>{w.emit("connectionStatusUpdate",{message:fe})}})},mobileGeneratorFactory:async w=>new ki({baseUrl:Kg(),apiKey:t,logger:p,mode:"interactive"}),browserGeneratorFactory:async w=>new Eo(A.config.ai?.agentConfig,T),browserEnricherFactory:async w=>new Oi(T,new Eo(A.config.ai?.agentConfig,T)),storageFactory:async w=>new Pu(R,w),cacheStorageFactory:async w=>{let D=await Pi(p,R,A);return Au({orgId:w,client:R,gitMetadata:D,regenerateCache:s??!1,noCache:l??!1,alwaysSaveCache:c??!1})},localToolsFactory:async()=>new Di({httpClient:R,fakerSeed:void 0}),keepSessionAlive:w=>R.extendAndroidEmulatorTtl(w),settingsFactory:async()=>({emulator:A.config.emulator})});process.once("SIGUSR2",async()=>{return;try{await _(),await yt.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 yt.flush()}finally{h.close(()=>process.exit(0))}}),process.once("SIGINT",async()=>{C.info("SIGINT in Momentic mobile app received");try{await _(),await yt.flush()}finally{h.close(()=>process.exit(0))}})}LH.setMaxListeners(25);process.on("warning",r=>{Et.warn({err:r},`Node warning received on mobile-desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{Et.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=>{Et.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 UH(r){C.error(OH`Port ${r} is already in use by another process. Please close the other process and try again.
|
|
4197
4219
|
Using Bash on MacOS or Linux:
|
|
4198
4220
|
lsof -t -i :58888 | xargs kill -9
|
|
4199
4221
|
|
|
4200
4222
|
Using Command Prompt on Windows:
|
|
4201
4223
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
4202
|
-
`)}import
|
|
4224
|
+
`)}import rG from"open";import Nu from"path";import{fileURLToPath as nG}from"url";import{InvalidArgumentError as nh,Option as ct}from"@commander-js/extra-typings";import{z as FH}from"zod";var Ix=58890;function Ox(r){let e=parseInt(r,10);if(isNaN(e))throw new nh("Not a number.");return e}var Ts=new ct("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(r=>{if(!r)throw new nh("API key is required.");return r}).makeOptionMandatory(),oh=new ct("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),vs=new ct("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(r=>{try{return FH.string().url().parse(r),r}catch{throw new nh("Not a valid URL.")}}),ih=new ct("-y, --yes","Skip all confirmation prompts.").env("CI"),ah=new ct("--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}),sh=new ct("--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}),lh=new ct("--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 ct("--tag <tag>","Tag identifier for the asset."),Lx=new ct("--channel <channel>","Channel name for the asset."),Nx=new ct("--channel <channel>","Channel name for the asset.").makeOptionMandatory(),Dx=new ct("--env <env>","Environment to run all tests in (overrides test-level configuration)."),kx=new ct("--local-avd-id <localAvdId>","Force tests to use a specific local Android Virtual Device (AVD) instead of remote emulators."),Ux=new ct("--local-apk-path <localApkPath>","Path to a local APK file to install when running tests with a local emulator. Overrides remote asset configuration."),Fx=new ct("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Ox),uh=new ct("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Bx=new ct("--upload-results","Upload test results to Momentic Cloud.").default(!1),dh=new ct("--log-level <logLevel>","Log level for Momentic and dependent services.").choices(["error","warn","info","debug"]),zx=new ct("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),Hx=new ct("--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(Ox);import{randomUUID as XH}from"crypto";import{existsSync as JH}from"fs";import ph from"fs";import As from"path";import{cwd as zH}from"process";async function Gx({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(p=>ph.existsSync(p)),d=zH();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:
|
|
4203
4225
|
- ${r.join(`
|
|
4204
4226
|
- `)}
|
|
4205
|
-
`),r.forEach(
|
|
4227
|
+
`),r.forEach(p=>{if(!ph.existsSync(p))throw new Error(`Path '${p}' does not exist.`);let g,m;try{g=ph.statSync(p),m=g.isDirectory()}catch(f){a.warn({err:f},`Skipping path ${p} because it cannot be read`);return}let h=As.resolve(p);Object.values(e.mobileTests).filter(f=>m?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(p=>{r.some(g=>p.relativePath.includes(g))&&c.add(p.fullFilePath)}))}else{!n&&!await wl("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=As.relative(t.rootDir,u);o&&!o.some(p=>new RegExp(p).test(d))&&c.delete(u),i&&i.some(p=>new RegExp(p).test(d))&&c.delete(u)}return(await Promise.all(Array.from(c).map(async u=>{try{let d=As.relative(t.rootDir,u),p=await bu(u,a,e),g=As.basename(u,As.extname(u));return{id:p.id,name:g,description:p.description,schemaVersion:p.schemaVersion,settings:p.settings,steps:p.steps,fullFilePath:u,relativeFilePath:d,quarantined:!!s[p.id],quarantinedReason:s[p.id]}}catch(d){a.error(`Failed to read and resolve mobile test at '${u}': ${d}`),process.exit(1)}}))).filter(u=>!!u)}import{randomUUID as HH}from"crypto";import{existsSync as GH,statSync as VH}from"fs";import{cloneDeep as jH}from"lodash-es";import WH from"path";async function Vx(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,p=await i.startRun({logger:a,testId:c.id,testName:c.name,runId:s,testDescription:c.description,schemaVersion:c.schemaVersion,originalSteps:{steps:jH(c.steps),beforeSteps:void 0,afterSteps:void 0},quarantined:c.quarantined,quarantinedReason:c.quarantinedReason}),g=a.child(p.loggerBindings||{}),m=1+(c.settings?.retries??u.config.retries??1);try{for(let h=0;h<m;h++){let f=new Date,E=await $H({runTracer:p,testDefinition:c,metadata:n,constants:{attemptNumber:h,totalAttempts:m},fixtures:{...t,logger:g},inputs:e,options:o}),b=new Date;if(E.status!=="FAILED")return await p.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!==m-1){a.warn("Retrying failed mobile run");continue}return a.error("Mobile test failed after all exhausting attempts"),await p.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 $H(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:p,logger:g,usageTracker:m}=i,{logUpdate:h,channel:f,tag:E,project:b,envOverride:R}=a,{regenerateCache:A,alwaysSaveCache:T,noCache:_,logLevel:w,localAvdId:D,localApkPath:G}=s;c!==0&&h("RETRY",`attempt ${c}/${l}`);let ee={...a.project.config.emulator,...t.settings?.emulator},Te=G?WH.resolve(G):void 0;if(Te&&(!GH(Te)||!VH(Te).isFile()))throw new Error(`Local APK path "${Te}" does not exist. Provide a valid file path via --local-apk-path.`);let fe=Au({orgId:u,client:p,gitMetadata:d,regenerateCache:A??!1,alwaysSaveCache:T??!1,noCache:_??!1}),ve=new Li(p,u),$={type:"API_KEY",baseUrl:p.baseUrl,apiKey:p.apiKey,logger:g,mode:"runner"},j=new ki($),se=new Eo(b.config.ai?.agentConfig,$),J=new Oi($,se),Ye=new Di({httpClient:p,fakerSeed:void 0}),Ne=Math.floor(Math.random()*1e4)+4e4,kt=await xl(Ne,"appium"),Ht=ee.region==="local"?Te??t.settings?.defaultApkFilePath?.trim():void 0,De=f&&!Ht?{channel:f,tag:E}:void 0,Ie;if(D||ee.region==="local"){if(!ee.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.");Ie={avdId:D??ee.localEmulatorSettings?.avdId,apkToInstall:De,apkFilePath:Ht}}else Ie={region:ee.region,apkToInstall:De,osVersion:ee.remoteEmulatorSettings?.androidVersion??gy};let xt=HH(),gt=await Tc({apiClient:p,logger:g,driverLogLevel:w,creationOpts:Ie,onStatusUpdate:Rs=>{g.debug({status:Rs},"Limbar emulator status update")},appiumPort:kt,orgId:u,sessionId:xt}),Vr=await e.startAttempt({emulatorName:gt.emulatorName,runAttemptId:xt}),To=g.child(Vr.loggerBindings||{}),vo=await Ac({driver:gt.driver,onLogs:Rs=>{Vr.appendLogs(Rs)}}),Du=R||t.settings?.defaultEnv,yh;Du&&(yh=cs(Du,b,To).variables);let qx=new jo({variablesFromEnvironment:yh??{},envName:Du,testName:t.name}),bh=await Ci.init({driver:gt.driver,generator:j,logger:To,limbarClient:gt.limbarClient,playwrightDevice:gt.playwrightDevice,orgId:u,adbPort:gt.adbPort,options:{emulator:ee},fixtures:{storage:ve,browserEnricher:J,browserGenerator:se,localCodeEvalTools:Ye,testContext:qx}}),W;try{W=await gu({containerName:`mobile test ${t.name}`,fixtures:{controller:bh,logger:To,cacheStorage:fe,usageTracker:m},work:{},inputs:{testName:t.name,steps:t.steps,orgId:u,testMetadata:t},tracer:Vr,callbacks:{}})}finally{await vo(),await gt.cleanup(),await bh.cleanup()}return await Vr.finish({logger:To,results:W.results,status:W.status}),W}import{debounce as qH}from"ts-debounce";var ws="0.8.0";var Iu="assets";function KH(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 YH(r){switch(r){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var mh=class{constructor(e,t,n,o){this.keepalive=e;this.testId=t;this.testName=n;this.diskStorage=o;this.interactionTracer=new ho,Qr.initializeRootTracerContext(this.interactionTracer)}children=[];finished=!1;interactionTracer;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Iu}/${t}.jpeg`,contents:n})}attachAfterScreenshot(e){let{snapshotId:t,screenshot:n}=e;this.diskStorage.storeFile({name:`${Iu}/${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:YH(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 Bi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Bi=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(`${Iu}/${t}.jpeg`)}getParentStepIdChain(){return[]}async startStep(e){this.keepalive();let t=new mh(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:KH(e.status),finishedAt:e.finishedAt}))))}},gh=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(`
|
|
4206
4228
|
`);this.logStream.write(t+`
|
|
4207
|
-
`)}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:tu(o,t),beforeResults:i?tu(i,t):void 0,afterResults:a?tu(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
|
|
4208
|
-
${
|
|
4209
|
-
`),
|
|
4229
|
+
`)}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:tu(o,t),beforeResults:i?tu(i,t):void 0,afterResults:a?tu(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 Bi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Bi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Bi(this.keepalive,this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,t){return this.diskStorage.readFile(`${Iu}/${t}.jpeg`)}},hh=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:ln,runAttemptSchemaVersion:Fb,startedAt:new Date,status:"RUNNING"};n.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)});let i=qH(async()=>{await this.client.extendAndroidEmulatorTtl(e.emulatorName)},3e4,{maxWait:6e4}),a=new gh(()=>void i(),this.testId,this.testName,t,o,n);return this.children.push(a),a}},Ou=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:Qt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:ws,labels:a??[]},c=new hs(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:ws,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 hh(this.client,e.testId,e.testName,e.runId,n,t);return this.children.push(o),o}};async function jx(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 tn(){try{await k(Promise.all([qb(),yt.flush()]),{milliseconds:5e3})}catch{}}async function Wx(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:p}=e;JH(d)&&C.warn(`Output directory ${d} already exists, removing before test execution...`);let g=await jx(s,a,e.ignoreQuarantine),m=await dr(i),h=await Gx({tests:n.tests,yes:e.yes,project:i,momenticFiles:m,logger:C,quarantinedTestReasons:g}),f=s.child({orgId:c,runGroupId:l,branch:u.gitBranchName}),E=await Ou.start({logger:f,orgId:c,runGroupId:l,outputDir:d,client:a,gitMetadata:u,labels:[]}),b=[],R=new Date,A=new Set,T=async()=>ZH({runResults:b,startTime:R,ranTests:A,apiClient:a,uploadResults:e.uploadResults??!1,outputDir:d}),_=[],w=async ve=>{C.warn(`${ve} Stopping tests and printing latest results.`),await E.finish({logger:f,status:"CANCELLED"}),await T(),await Promise.allSettled(_.map($=>$())),await tn(),process.exit(1)},D=async()=>{await w("SIGINT received.")};process.once("SIGINT",D);let G;if(e.timeoutMinutes!==void 0&&e.timeoutMinutes>0){let ve=e.timeoutMinutes*60*1e3;G=setTimeout(()=>{w(`Timeout of ${e.timeoutMinutes} minute(s) reached.`)},ve)}let ee={};for(let ve=0;ve<h.length;ve++){let $=Object.values(ee);$.length===p&&await Promise.race($.map(J=>J.promise));let j=h[ve],se=`test-${ve}`;ee[se]={done:!1,promise:(async({testDefinition:J})=>{A.add(se);let Ye=J.relativeFilePath.includes("..")?J.fullFilePath:J.relativeFilePath;Ra({status:"START",testLogRef:Ye,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length});let Ne=setInterval(()=>Ra({status:"RUN",testLogRef:Ye,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),5*60*1e3),kt=XH(),Ht=f.child({testId:J.id,runId:kt}),De=new Lc({logger:Ht,reporter:new Tu(a),runType:"mobile-test-run",runId:kt,testMetadata:J,suiteMetadata:void 0});try{let Ie=await Vx({metadata:{...o,runId:kt},fixtures:{...t,tracer:E,logger:Ht,usageTracker:De},inputs:{...n,project:i,testDefinition:J,channel:n.channel??J.settings?.defaultChannel,tag:n.tag??J.settings?.defaultTag,logUpdate:(xt,gt)=>Ra({status:xt,testLogRef:Ye,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length,additionalText:gt}),runSigIntHandlers:_},options:e});Ra({status:Ie.status,testLogRef:Ye,getRunningTestsCount:()=>A.size,getTotalTestsCount:()=>h.length}),b.push(Ie)}catch(Ie){let xt=`Encountered unexpected fatal error when running test '${J.name}': ${Ie.message}
|
|
4230
|
+
${Ie.stack}`;C.error(xt),Ht.error({err:Ie},`Encountered unexpected fatal error when running test ${J.name}`)}finally{clearInterval(Ne),ee[se].done=!0,delete ee[se]}await De.flush(s)})({testDefinition:j})}}await Promise.allSettled(Object.values(ee).map(ve=>ve.promise)),G&&clearTimeout(G);let fe=b.some(ve=>ve.status==="FAILED"&&!ve.quarantined)?"FAILED":"PASSED";return await E.finish({logger:f,status:fe}),process.off("SIGINT",D),T()}async function ZH({runResults:r,startTime:e,ranTests:t,apiClient:n,uploadResults:o,outputDir:i}){let a=n.getAppUrl(),s=Kb({results:r,startTime:e.getTime(),onFailed:c=>{},getDisplayLine:c=>{let l=`${gp}- ${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 Ru({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 fh(){mA(),Zb("Chromium")||(Qn?(await wl("The Chromium browser is not installed but is required for automating webviews. Install it now?")||process.exit(1),await Cl({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)))}iA({serviceName:"mobile-cli"});nr.setApp("mobile-cli");var Un=new QH;Un.name("momentic-mobile").description("Momentic Mobile CLI").version(ws);var oG=Un.command("assets").description("Manage mobile testing assets");oG.command("upload").description("Upload an asset for mobile tests").argument("<file>","Path to the asset file to upload").addOption(Ts).addOption(vs).addOption(ch).addOption(Nx).action(async(r,e)=>{let{apiKey:t,server:n,tag:o,channel:i}=e,a=Nu.resolve(r);Lu.existsSync(a)||(C.error(`File not found: ${a}`),process.exit(1));let s=new vr({baseUrl:n,apiKey:t,logger:C});/\.apk$/i.test(a)||(C.error(`File is not an APK file: ${a}`),process.exit(1)),await vc({tag:o?.toLowerCase(),channel:i.toLowerCase(),filePath:a,apiClient:s,logger:C})});Un.command("app").addOption(Ts).addOption(vs).addOption(ih).addOption(oh).addOption(dh).addOption(ah).addOption(sh).addOption(lh).action(async r=>{let{apiKey:e,server:t,yes:n,disableCache:o,saveCache:i,regenerateCache:a}=r,s=fp(r.logLevel);nr.setApp("mobile-desktop-server");let c=new vr({baseUrl:t,apiKey:e,logger:nr});await zg({client:c,skipPrompts:n}),C.debug("API key check complete");let l=nG(import.meta.url),u=Nu.dirname(l),d=Nu.resolve(u,"..","static");await fh(),C.debug({appiumHome:Xa},"Resolved resource paths");let p=await ds({configFilePath:r.config}),g=Ix;await Px({momenticServerUrl:t,serverPort:g,apiKey:e,staticDir:d,initialProject:p,driverLogLevel:s,logger:nr,regenerateCache:a,noCache:o,alwaysSaveCache:i});let m=`http://localhost:${g}`;C.info(`Local app started on: ${m}`),await rG(m)});var $x=Un.command("results").description("Merge and upload test results.");$x.command("merge").description("Merge test results files.").addOption(uh).addArgument(new Sh("<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)),Lu.existsSync(r)||(C.warn("Results path does not exist, skipping merge."),process.exit(0)),Lu.existsSync(t)&&C.warn(`Output directory ${t} already exists, removing before merging...`),cx(nr,t,r),await tn(),process.exit(0)});var iG=new Sh("<results>","Path to the results archive.").argRequired();$x.command("upload").description("Upload test results to Momentic cloud.").addOption(Ts).addOption(vs).addArgument(iG).action(async(r,e)=>{let{apiKey:t,server:n}=e,o=nr,i=new vr({baseUrl:n,apiKey:t,logger:o});await Ru({consoleLogger:C,resultsPath:r,client:i}),await tn(),process.exit(0)});var aG=Un.command("run").alias("test").description("Run tests on the local machine");aG.addOption(Ts).addOption(vs).addOption(oh).addOption(ih).addOption(Fx).addOption(dh).addOption(ah).addOption(sh).addOption(lh).addOption(uh).addOption(Bx).addOption(zx).addOption(Hx).addOption(ch).addOption(Lx).addOption(Dx).addOption(kx).addOption(Ux).addArgument(new Sh("<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=fp(e.logLevel);await fh(),C.debug({appiumHome:Xa},"Resolved resource paths");let c=await ds({configFilePath:e.config}),l=a??c.config.outputDir??JC,u=e.parallel??c.config.parallel??1;C.debug("Checking API key and dependencies");let d=new vr({baseUrl:n,apiKey:t,logger:C}),{orgId:p,userId:g}=await zg({client:d,skipPrompts:e.yes});C.debug("API key check and browser installation complete");let m=tG(),h=nr.child({runGroupId:m,orgId:p,userId:g}),f=await Pi(nr,d,c);h.debug(f,"Got local git metadata");try{let E=await Wx({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:m,orgId:p}});await tn(),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),nr.error({err:E},"Failed to run tests locally"),await tn(),process.exit(1)}});Un.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new eG("--name <name>","Name of the project")).action(async r=>{C.info(`Welcome to the Momentic Mobile project setup wizard! \u{1F680}
|
|
4231
|
+
`),C.info("This wizard will help you bootstrap a new Momentic project."),Lu.existsSync(_i)&&(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 Gb("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:xg};XC(t,_i),C.success(`Initialized Momentic project file at ${Nu.resolve(_i)}`)});Un.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: ${Sp.join(", ")}.`).action(async(r,e)=>{!e.all&&r.length===0&&(C.error("No browsers specified"),process.exit(1)),await Cl({rawBrowsers:r,force:e.force,all:e.all})});async function sG(){try{await Un.parseAsync(process.argv),await tn()}catch(r){nr.error({err:r},"Uncaught error in CLI"),C.error(r),await tn(),process.exit(1)}}sG();
|
|
4210
4232
|
//# sourceMappingURL=cli.js.map
|