momentic 2.12.0 → 2.12.1

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,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9bdda1b7-c45e-54b1-847b-1d7e69d70cce")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ff32955f-eefb-5136-87fc-4c324742bd12")}catch(e){}}();
4
4
  var pi=(n,e)=>{},Il=!1;try{let n=await import("@sentry/node");pi=n.captureException,n.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),Il=!0}catch{}import{Command as cO,Option as kt}from"@commander-js/extra-typings";import{execSync as dO}from"child_process";import{randomUUID as uO}from"crypto";import Dy from"body-parser";import kP from"cors";import _P from"dedent";import DP from"events";import Fy,{Router as FP}from"express";import{diff as fC}from"deep-object-diff";import an from"fs";import Xr from"path";import{diff as $v}from"deep-object-diff";import{z as _u}from"zod";var vO=_u.object({input:_u.string()});import{z as Qe}from"zod";var AO=Qe.object({srcs:Qe.array(Qe.string()),urls:Qe.array(Qe.string()),desiredSrc:Qe.string().optional(),desiredUrl:Qe.string().optional()}),Du=Qe.object({srcRegex:Qe.string().optional(),urlRegex:Qe.string().optional()}),Fu=Qe.object({x:Qe.number(),y:Qe.number(),correlation:Qe.number()}),xO=Qe.object({searchImageBase64String:Qe.string(),pageImageBase64String:Qe.string(),id:Qe.string().uuid(),timeoutMs:Qe.number().max(1e4).min(0).optional()});import{z as _}from"zod";import*as F from"zod";function Le(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o){return new this.constructor({...this._def,openapi:o})};let e=n.ZodObject.prototype.extend;n.ZodObject.prototype.extend=function(...o){let i=e.apply(this,o);return i._def.extendMetadata={extends:this},delete i._def.openapi,i};let t=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){let i=t.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i};let r=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){let i=r.apply(this,o);return delete i._def.extendMetadata,delete i._def.openapi,i}}Le(F);var Xn=(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))(Xn||{}),bw=F.object({mPathSelectorTokens:F.string().array(),frameSrcRegex:F.string().optional(),frameUrlRegex:F.string().optional(),indices:F.number().array()}),Pl=F.object({result:F.number(),traceId:F.string()}).array(),gi=F.object({type:F.literal("GCS_TRACES"),traces:Pl}),vr=F.object({id:F.number().int(),dataMomenticId:F.number().int().optional(),selector:F.string().optional(),hybridSelector:F.object({textContent:F.string().nullish(),attributes:F.record(F.string(),F.string()),tagName:F.string(),expandShadowRoot:F.boolean().optional(),classNames:F.string().array(),nthChild:F.number()}).array().optional(),generatedSelectors:F.string().array().optional(),role:F.string().optional(),name:F.string().optional(),numChildren:F.number().optional(),content:F.string().optional(),pathFromRoot:F.string().optional(),serializedForm:F.string().optional(),nodeOnlySerializedForm:F.string().optional(),serializedHtml:F.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:F.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:F.string().url().optional(),boundingBox:F.object({x:F.number().optional(),y:F.number().optional(),width:F.number(),height:F.number()}).describe("css pixel bounding box").optional(),frameCache:bw.optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(Xn).optional(),targetUpdateTime:F.string().optional(),targetUpdateLoggerTags:F.record(F.string(),F.string()).optional(),cacheResolutionUpdateSource:F.string().optional(),cacheResolutionUpdateTime:F.string().optional(),cacheResolutionUpdateLoggerTags:F.record(F.string(),F.string()).optional(),memory:gi.optional()}).openapi({ref:"ElementTargetCache"});function Uu(n){return!!(n.name||n.role||n.content||n.serializedForm||n.serializedHtml||n.screenshotUrl)}var ww=F.object({type:F.literal("description"),elementDescriptor:F.string().describe("Description of the element."),a11yData:vr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"}),Tw=F.object({x:F.number(),y:F.number()}),Ew=F.object({type:F.literal("coordinates"),pixels:Tw}).openapi({ref:"CoordinatesTarget"});function Jn(n){return n.type==="description"}function fn(n){return n.type==="coordinates"}var mt=F.discriminatedUnion("type",[ww,Ew]).openapi({ref:"ElementTarget"});function Ll(n){if(!n)return!1;switch(n.type){case"description":return!!n.elementDescriptor}return!0}function pt(n){if(!n)return"";switch(n.type){case"description":return n.elementDescriptor;case"coordinates":return`x: ${n.pixels.x}, y: ${n.pixels.y}`}}import{v4 as Te}from"uuid";import*as w from"zod";import{z as ee}from"zod";import{z as yo}from"zod";var Ol=yo.object({result:yo.boolean(),traceId:yo.string()}).array(),Ml=yo.object({type:yo.literal("GCS_TRACES"),traces:Ol}),Bu=yo.object({memory:Ml.optional()});var Sa=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};Le(ee);var Hu=ee.object({plan:ee.string().optional(),evidence:ee.string().optional(),thoughts:ee.string(),result:ee.boolean(),relevantElements:ee.array(ee.number()).optional(),updatedMemory:Ol.optional()}),Qn=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(Qn||{});var vw=ee.object({type:ee.literal("ELEMENT_NAME"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Qn),value:ee.string()}).openapi({ref:"ElementNameAssertion"}),Cw=ee.object({type:ee.literal("ELEMENT_STYLE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Qn),property:ee.string(),value:ee.string()}).openapi({ref:"ElementStyleAssertion"}),Rw=ee.object({type:ee.literal("ELEMENT_CONTENT"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Qn),value:ee.string()}).openapi({ref:"ElementContentAssertion"}),Aw=ee.object({type:ee.literal("ELEMENT_ATTRIBUTE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(Qn),attr:ee.string(),value:ee.string()}).openapi({ref:"ElementAttributeValueAssertion"}),bo=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(bo||{}),xw=ee.object({type:ee.literal("ELEMENT_EXISTENCE"),negated:ee.boolean().optional(),condition:ee.nativeEnum(bo).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),zu=ee.discriminatedUnion("type",[Rw,Aw,xw,vw,Cw]).openapi({ref:"ManualElementAssertion"});var Iw=ee.object({type:ee.literal("CONTENT"),negated:ee.boolean().optional(),value:ee.string()}).openapi({ref:"PageContentAssertion"}),$u=ee.discriminatedUnion("type",[Iw]).openapi({ref:"ManualPageAssertion"});import{z as de}from"zod";var ya=de.object({url:de.string(),method:de.union([de.literal("GET"),de.literal("POST"),de.literal("PUT"),de.literal("DELETE"),de.literal("PATCH")]),headers:de.record(de.string(),de.string()).optional(),params:de.record(de.string(),de.string()).optional(),body:de.string().optional(),timeout:de.number().int().optional().describe("Max seconds to wait for the request to complete")}),ju=de.object({url:de.string(),headers:de.record(de.string(),de.string()).optional(),query:de.string(),variables:de.record(de.string(),de.string()).optional(),timeout:de.number().int().optional().describe("Max seconds to wait for the request to complete")}),ba=de.object({code:de.string(),fragment:de.boolean().optional(),environment:de.union([de.literal("NODE"),de.literal("BROWSER")]).optional().describe("default NODE"),timeout:de.number().int().max(60).optional().describe("Max seconds for the code to complete")});var ze=($=>($.AI_EXTRACT="AI_EXTRACT",$.AI_ASSERTION="AI_ASSERTION",$.AUTH_LOAD="AUTH_LOAD",$.AUTH_SAVE="AUTH_SAVE",$.BLUR="BLUR",$.CAPTCHA="CAPTCHA",$.CLICK="CLICK",$.COOKIE="COOKIE",$.COPY="COPY",$.DIALOG="DIALOG",$.DRAG="DRAG",$.ELEMENT_CHECK="ELEMENT_CHECK",$.FILE_UPLOAD="FILE_UPLOAD",$.FOCUS="FOCUS",$.GO_BACK="GO_BACK",$.GO_FORWARD="GO_FORWARD",$.HOVER="HOVER",$.JAVASCRIPT="JAVASCRIPT",$.LOCAL_STORAGE="LOCAL_STORAGE",$.MOUSE_DRAG="MOUSE_DRAG",$.NAVIGATE="NAVIGATE",$.NEW_TAB="NEW_TAB",$.PAGE_CHECK="PAGE_CHECK",$.PASTE="PASTE",$.PRESS="PRESS",$.KEY_DOWN="KEY_DOWN",$.KEY_UP="KEY_UP",$.REFRESH="REFRESH",$.REQUEST="REQUEST",$.GRAPHQL_REQUEST="GRAPHQL_REQUEST",$.SCROLL_DOWN="SCROLL_DOWN",$.SCROLL_UP="SCROLL_UP",$.SCROLL_LEFT="SCROLL_LEFT",$.SCROLL_RIGHT="SCROLL_RIGHT",$.SELECT_OPTION="SELECT_OPTION",$.SWITCH_TAB="TAB",$.TYPE="TYPE",$.VISUAL_DIFF="VISUAL_DIFF",$.WAIT="WAIT",$.WAIT_FOR_URL="WAIT_FOR_URL",$.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",$.AWAIT_LISTENER="AWAIT_LISTENER",$.RECORD_REQUESTS="RECORD_REQUESTS",$.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",$.SET_HEADER="SET_HEADER",$.OFFLINE_MODE="OFFLINE_MODE",$.SUCCESS="SUCCESS",$))(ze||{});Le(w);var q=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),$t=w.object({useSelector:w.boolean().optional(),force:w.boolean().optional(),disableCache:w.boolean().optional().describe("disable element caching for this step"),iframeUrl:w.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Sn=w.object({target:vr}).optional().openapi({ref:"SingleTargetCache"}),wa=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),kl=q.merge(wa).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Ta=$t.merge(w.object({cache:Sn})),Zn=q.merge(Ta.merge(w.object({target:mt.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),er=q.merge(Ta.merge(w.object({target:mt.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),wo=q.merge(Ta.merge(w.object({target:mt.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),To=q.merge(Ta.merge(w.object({target:mt.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),eM=w.discriminatedUnion("type",[Zn,er,wo,To]).openapi({ref:"AllScrollCommands"}),Pw=q.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Lw=q.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),Ow=w.discriminatedUnion("type",[w.object({type:w.literal("SUBSTRING"),url:w.string()}),w.object({type:w.literal("GLOB"),glob:w.string()}),w.object({type:w.literal("REGEX"),regex:w.string()})]),Mw=w.object({caseInsensitive:w.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:w.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:w.number().int().optional().describe("Max seconds to wait for the URL to match")}),_l=q.extend({type:w.literal("WAIT_FOR_URL"),matcher:Ow}).merge(Mw).openapi({ref:"WaitUrlCommand"}),Nw=q.merge(wa).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),kw=q.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),_w=q.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Dw=q.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Fw=q.extend({type:w.literal("AUTH_LOAD"),storageState:w.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),Dl=q.merge($t).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Uw=q.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),Bw=q.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),Hw=q.merge(ba).extend({type:w.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Cr=q.merge($t).extend({type:w.literal("CLICK"),target:mt,doubleClick:w.boolean().optional(),rightClick:w.boolean().optional(),waitForDownload:w.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:w.number().optional(),downloadTimeoutMs:w.number().optional(),cache:Sn,relativePosition:w.object({x:w.number(),y:w.number()}).optional()}).openapi({ref:"ClickCommand"}),fi=q.merge($t).merge(w.object({type:w.literal("DRAG"),fromTarget:mt,toTarget:mt,steps:w.number().optional(),hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:w.object({fromTarget:vr.optional(),toTarget:vr.optional()}).optional()})).openapi({ref:"DragCommand"}),Si=q.merge($t).merge(w.object({type:w.literal("MOUSE_DRAG"),target:mt.optional(),deltaX:w.string().describe("pixels to move horizontally, can be template"),deltaY:w.string().describe("pixels to move vertically, can be template"),steps:w.number().optional(),cache:Sn})).openapi({ref:"MouseDragCommand"}),Rr=q.merge($t).merge(w.object({type:w.literal("HOVER"),target:mt,cache:Sn})).openapi({ref:"HoverCommand"}),yi=q.merge($t).merge(w.object({type:w.literal("FOCUS"),target:mt,cache:Sn})).openapi({ref:"FocusCommand"}),bi=q.merge($t).extend({type:w.literal("BLUR"),target:mt.optional(),cache:Sn}).openapi({ref:"BlurCommand"}),zw=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),$w=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),jw=q.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[zw,$w]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),Gw=w.discriminatedUnion("type",[w.object({type:w.literal("VALUE"),value:w.string()}),w.object({type:w.literal("LABEL"),label:w.string()}),w.object({type:w.literal("INDEX"),index:w.coerce.string()})]),Ar=q.merge($t).extend({type:w.literal("SELECT_OPTION"),target:mt,cache:Sn,choice:Gw.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Fl=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),Eo=q.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:Fl.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:Bu.optional()})).openapi({ref:"AIAssertionCommand"}),yn=5,Ul=600,xr=q.merge($t).extend({type:w.literal("ELEMENT_CHECK"),target:mt,assertion:zu,cache:Sn,timeout:w.number().int().min(0).max(Ul).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Bl=q.extend({type:w.literal("PAGE_CHECK"),assertion:$u,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(Ul).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Ww=q.merge(w.object({type:w.literal("AI_EXTRACT"),goal:w.string(),schema:w.string().optional(),envKey:w.string().optional(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional()})).openapi({ref:"AIExtractCommand"}),Vw=w.object({clearContent:w.boolean().optional(),forceClearContent:w.boolean().optional(),delay:w.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:w.boolean().optional(),pressEnter:w.boolean().optional()}),Gu=25,Ir=q.merge($t).merge(Vw).extend({type:w.literal("TYPE"),target:mt.optional(),value:w.string(),cache:Sn}).openapi({ref:"TypeCommand"}),Hl=q.merge(w.object({type:w.literal("PRESS"),value:w.string(),repeat:w.number().optional(),convertMeta:w.boolean().optional(),delayMs:w.number().optional()})).openapi({ref:"PressCommand"}),qw=q.merge(w.object({type:w.literal("KEY_DOWN"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyDownCommand"}),Kw=q.merge(w.object({type:w.literal("KEY_UP"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyUpCommand"}),Yw=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),Xw=w.object({type:w.literal("REGEX"),pattern:w.string()}),Jw=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),Qw=w.discriminatedUnion("type",[Yw,Xw,Jw]),Zw=q.merge(wa).merge(w.object({type:w.literal("TAB"),action:Qw})).openapi({ref:"TabCommand"}),zl=q.merge(wa).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),eT=q.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),tT=q.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),nT=q.extend({type:w.literal("REQUEST")}).merge(ya).openapi({ref:"RequestCommand"}),rT=q.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(ju).openapi({ref:"GraphQLRequestCommand"}),oT=q.merge(w.object({type:w.literal("SUCCESS"),condition:Eo.optional()})).openapi({ref:"SuccessCommand"}),iT=q.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),aT=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),wi=q.merge($t).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:mt.optional(),screenshot:aT.optional(),cache:Sn})).openapi({ref:"VisualDiffCommand"}),sT=q.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),pattern:w.string(),key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),lT=q.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),cT=q.merge(w.object({type:w.literal("RECORD_REQUESTS"),pattern:w.string(),key:w.string()})).openapi({ref:"RecordRequestsCommand"}),dT=q.merge(w.object({type:w.literal("GET_RECORDED_REQUESTS"),key:w.string()})).openapi({ref:"GetRecordedRequestsCommand"}),uT=q.merge(w.object({type:w.literal("SET_HEADER"),name:w.string(),value:w.string(),urlPattern:w.string().optional().describe("URL pattern to match")})).openapi({ref:"SetHeaderCommand"}),mT=q.merge(w.object({type:w.literal("OFFLINE_MODE"),enable:w.boolean()})).openapi({ref:"OfflineModeCommand"}),Wu=w.discriminatedUnion("type",[Cr,Ir,Hl,qw,Kw,Ar,kl,er,Zn,Eo,Rr,Lw,oT]),pT=w.discriminatedUnion("type",[Ww,Fw,Dw,Dl,eT,Uw,Pw,fi,xr,jw,kw,_w,Hw,tT,Si,zl,Bl,Bw,Nw,nT,rT,wo,To,Zw,wi,yi,bi,_l,sT,lT,cT,dT,uT,mT]),vo=w.discriminatedUnion("type",[...Wu.options,...pT.options]).openapi({ref:"Command"}),Ea=w.discriminatedUnion("type",[...Wu.options,iT]);function _n(n){let e;switch(n){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:Te(),type:n};break;case"AUTH_LOAD":{e={id:Te(),type:n,storageState:""};break}case"AI_EXTRACT":e={id:Te(),type:n,goal:""};break;case"DIALOG":e={id:Te(),type:n,action:"DISMISS"};break;case"DRAG":e={id:Te(),type:n,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Te(),type:n,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Te(),type:n,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:Te(),type:n,delay:1};break;case"BLUR":e={id:Te(),type:n};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Te(),type:n,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Te(),type:n,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:Te(),type:n,value:""};break;case"SELECT_OPTION":e={id:Te(),type:n,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:Te(),type:n,url:""};case"TAB":e={id:Te(),type:n,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:Te(),type:n,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Te(),type:n,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Te(),type:n,key:"",value:""};break;case"JAVASCRIPT":e={id:Te(),type:n,code:""};break;case"AI_ASSERTION":e={id:Te(),type:n,assertion:""};break;case"FILE_UPLOAD":{e={id:Te(),type:n,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Te(),type:n,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Te(),type:n,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Te(),type:n,pattern:"",key:""};break}case"AWAIT_LISTENER":{e={id:Te(),type:n,key:""};break}case"RECORD_REQUESTS":{e={id:Te(),type:n,pattern:"",key:""};break}case"GET_RECORDED_REQUESTS":{e={id:Te(),type:n,key:""};break}case"SET_HEADER":{e={id:Te(),type:n,name:"",value:""};break}case"OFFLINE_MODE":{e={id:Te(),type:n,enable:!0};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}function Vu(n){switch(n.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":return!1;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}import{z as gT}from"zod";var iM=gT.discriminatedUnion("type",[bi,Dl,Cr,fi,yi,Rr,Si,Zn,er,wo,To,Ar,Ir,wi,xr]);function qu(n){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(n)}import{z as hT}from"zod";var wt={type:!0,cache:!0},Pr=hT.discriminatedUnion("type",[Eo.pick(wt),bi.pick(wt),Cr.pick(wt),fi.pick(wt),xr.pick(wt),yi.pick(wt),Rr.pick(wt),Si.pick(wt),Zn.pick(wt),er.pick(wt),wo.pick(wt),To.pick(wt),Ar.pick(wt),Ir.pick(wt),wi.pick(wt)]),$l=Object.values(ze).filter(n=>Pr.options.some(e=>e.shape.type.safeParse(n).success));vo.options.forEach(n=>{if("target"in n.shape&&!$l.includes(n.shape.type.value))throw new Error(`Command ${n.shape.type.value} has a target but no cache`)});import{z as jl}from"zod";import{z as Ku}from"zod";import{z as Lr}from"zod";var jt=Lr.object({index:Lr.number().optional().describe("global index within a test (in-order traversal)"),id:Lr.string(),skipped:Lr.boolean().optional(),envKey:Lr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Lr.boolean().optional(),retries:Lr.number().optional()});Le(Ku);var fT=jt.extend({type:Ku.literal("PRESET_ACTION")}),xt=fT.extend({command:vo}).openapi({ref:"PresetAction"});Le(jl);var Or=jt.extend({type:jl.literal("AI_ACTION"),text:jl.string(),steps:xt.array().optional()}).openapi({ref:"AIAction"});import{z as Tt}from"zod";import{z as va}from"zod";Le(va);var Co=jt.extend({type:va.literal("AI_ACTION_DYNAMIC"),text:va.string(),retries:va.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Yu}from"zod";var Gl=jt.extend({type:Yu.literal("CONDITIONAL"),skipped:Yu.boolean().optional()});import{z as ae}from"zod";var ST=ae.object({cacheKey:ae.string(),cacheExpiryMs:ae.number()}),Wl=jt.extend({id:ae.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ae.record(ae.string()).optional(),cacheConfig:ST.optional()}),Dn=Wl.extend({type:ae.literal("MODULE"),moduleId:ae.string().uuid()}),yT=ae.union([Dn.pick({type:!0,moduleId:!0}),ae.record(ae.unknown())]),bT=ae.object({type:ae.literal("URL_REGEX"),regex:ae.string()}),wT=ae.object({type:ae.literal("PAGE_CHECK"),substring:ae.string()}),Vl=ae.object({cacheInvalidation:ae.discriminatedUnion("type",[wT,bT]).optional()}),It=ae.object({moduleId:ae.string().uuid(),name:ae.string(),description:ae.string().nullish(),enabled:ae.boolean().nullish(),parameters:ae.string().array().nullish(),defaultParameters:ae.record(ae.string(),ae.string()).nullish(),parameterEnums:ae.record(ae.string(),ae.string().array()).nullish(),defaultCacheKey:ae.string().nullish(),defaultCacheTtl:ae.number().nullish(),defaultCacheAllInvocations:ae.boolean().nullish(),autoAuth:ae.boolean().nullish(),advanced:Vl.nullish()});import{z as Gt}from"zod";var ql=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(ql||{});var TT=Gt.discriminatedUnion("type",[Gt.object({type:Gt.literal("NAVIGATE_URL"),url:Gt.string().url()}),Gt.object({type:Gt.literal("GO_TO_SECTION_START")})]),ET=Gt.object({trigger:Gt.nativeEnum(ql).optional(),attempts:Gt.number().int().optional(),restartBehavior:TT}),Ti=jt.extend({type:Gt.literal("SECTION"),description:Gt.string().describe("user provided goal of what the section should accomplish"),plan:Gt.string().array().optional(),autohealingConfig:ET.optional()});var Xu=It.merge(Wl).extend({type:Tt.literal("RESOLVED_MODULE"),steps:Tt.lazy(()=>De.array())}),Kl=It.extend({steps:Tt.lazy(()=>De.array())}),Yl=Ti.extend({steps:Tt.lazy(()=>xe.array())}),vT=Ti.extend({steps:Tt.lazy(()=>De.array())}),Mr=Gl.extend({blocks:Tt.object({assertion:Tt.lazy(()=>xt),steps:Tt.lazy(()=>xe.array())}).array(),elseSteps:Tt.lazy(()=>xe.array().optional())}),CT=Gl.extend({blocks:Tt.object({assertion:Tt.lazy(()=>xt),steps:Tt.lazy(()=>De.array())}).array(),elseSteps:Tt.lazy(()=>De.array().optional())}),xe=Tt.discriminatedUnion("type",[xt,Or,Co,Dn,Mr,Yl]),De=Tt.discriminatedUnion("type",[xt,Or,Co,Xu,CT,vT]);import{z as Wt}from"zod";var RT=Wt.object({steps:xe.array(),beforeSteps:xe.array().nullish(),afterSteps:xe.array().nullish()}),Ro=Wt.object({steps:De.array(),beforeSteps:De.array().nullish(),afterSteps:De.array().nullish()}),Nr=Wt.object({steps:Wt.record(Wt.string(),Wt.unknown()).array(),beforeSteps:Wt.record(Wt.string(),Wt.unknown()).array().nullish(),afterSteps:Wt.record(Wt.string(),Wt.unknown()).array().nullish()});var se="1.0.20";import{z as tr}from"zod";var Xl=tr.object({key:tr.string(),testId:tr.string().optional(),moduleId:tr.string().optional(),organizationId:tr.string(),value:Pr}),Jl=Xl.extend({uniqueKey:tr.string()}),fN=tr.record(tr.string(),Jl);var Ju=_.object({phrase:_.string()}),Ql=_.object({thoughts:_.string().optional(),result:_.union([_.literal("NOT_FOUND"),_.string(),_.number(),_.array(_.unknown()),_.record(_.unknown(),_.unknown()),_.unknown()])}),JN=_.object({text:_.string()}),Qu=_.object({thoughts:_.string(),review:_.string().optional(),id:_.number().int(),updatedMemory:Pl.optional()}),Ca=(m=>(m.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",m.FEW_WORDS="FEW_WORDS",m.STYLE_TAG="STYLE_TAG",m.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",m.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",m.NONE="NONE",m.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",m.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",m.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",m.PREFER_ASSERTION="PREFER_ASSERTION",m.HTML_ELEMENTS="HTML_ELEMENTS",m.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",m))(Ca||{});var Zu=_.object({thoughts:_.string(),category:_.nativeEnum(Ca)}),AT=_.discriminatedUnion("op",[_.object({op:_.literal("replace"),path:_.string(),value:_.string()}),_.object({op:_.literal("add"),path:_.string(),value:_.string()}),_.object({op:_.literal("remove"),path:_.string()})]),QN=_.object({thoughts:_.string(),patches:AT.array()}),xT=[_.literal("add"),_.literal("replace"),_.literal("remove")],IT=_.object({op:_.union(xT),path:_.string(),value:De.optional()}),em=_.object({patches:IT.array(),thoughts:_.string()}),Zl=(r=>(r.LEGITIMATE="LEGITIMATE",r.RECOVERABLE="RECOVERABLE",r.INELIGIBLE="INELIGIBLE",r))(Zl||{}),tm=_.object({thoughts:_.string(),scenario:_.nativeEnum(Zl),instructions:_.string().nullish()}),nm=_.object({reasoning:_.string(),scenario:_.string(),patch:_.null().optional()}),ZN=_.object({thoughts:_.string(),evaluation:_.number().min(1).max(10)}),ek=_.object({observations:_.string(),reasoning:_.string(),command:Ea});var ec=_.object({summary:_.string(),reasoning:_.string(),evaluation:_.discriminatedUnion("type",[_.object({type:_.literal("DONE")}),_.object({type:_.literal("RIGHT_TRACK")}),_.object({type:_.literal("WRONG_TRACK"),feedback:_.string()}),_.object({type:_.literal("IMPOSSIBLE")})])});import{z as O}from"zod";import*as te from"zod";var ak=te.object({thoughts:te.string().optional().describe("only provided if a description was provided"),target:vr.optional().describe("only provided if a description was provided"),pageState:te.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:te.object({label:te.string(),value:te.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:te.object({data:te.string(),height:te.number().int(),width:te.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Ra=te.union([te.literal("ELEMENT_CHECK"),te.literal("NEGATED_CHECK"),te.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),te.literal("SELECT_OPTION"),te.literal("TYPE")]);function kr(n){if(!("useSelector"in n&&n.useSelector)){if(n.type==="SELECT_OPTION")return"SELECT_OPTION";if(n.type==="TYPE")return"TYPE";if(n.type==="ELEMENT_CHECK"&&n.assertion.type==="ELEMENT_EXISTENCE"&&n.assertion.condition==="EXISTS"&&n.assertion.negated)return"NEGATED_CHECK";if(n.type==="ELEMENT_CHECK"&&n.assertion.type==="ELEMENT_EXISTENCE"&&n.assertion.condition==="VISIBLE"&&n.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(n.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Ei=(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))(Ei||{}),Ao=te.object({matched:te.boolean(),reason:te.string().optional().describe("Human understandable description"),logs:te.string().array().optional().describe("Logs for debugging")}),PT=Ao.extend({type:te.literal("USER_SELECTOR")}),LT=Ao.extend({type:te.literal("CSS_SELECTOR"),selectors:te.string().array()}),OT=Ao.extend({type:te.literal("HYBRID_SELECTOR")}),MT=Ao.extend({type:te.literal("HTML_DISTANCE"),distance:te.number().optional(),closestElement:te.string().optional(),savedElement:te.string().optional()}),NT=Ao.extend({type:te.literal("TEMPLATE_MATCHING"),elementImageUrl:te.string().url()}),kT=Ao.extend({type:te.literal("AUTO_FRAME"),logs:te.string().array().optional()}),rm=te.discriminatedUnion("type",[PT,LT,OT,MT,NT,kT]);import{z as xi}from"zod";import{z as jT}from"zod";import*as G from"zod";import{cloneDeep as Ci}from"lodash-es";import cm from"truncate-json";import*as Dr from"zod";import{z as tn}from"zod";import{z as $e}from"zod";var tc=$e.object({autoFollowNewTabs:$e.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:$e.union([$e.boolean(),$e.literal("inputs-only")]).optional(),ignoreHrefForCaching:$e.boolean().optional(),disableSecondaryCacheResolution:$e.boolean().optional(),hybridSelectorMode:$e.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:$e.boolean().optional(),visualActions:$e.boolean().optional(),autoExpandIframes:$e.boolean().optional()});var om=1e4,im=6e4,_r=tc.extend({pageLoadTimeoutMs:$e.number().optional().refine(n=>n===void 0||n<=im&&n>=-1,{message:`Page load timeout must be between 0 and ${im/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:$e.number().optional().refine(n=>n===void 0||n<=om&&n>=-1,{message:`Smart waiting timeout must be between 0 and ${om/1e3} seconds`}),localChromeExtensionPaths:$e.string().array().optional(),extraHeaders:$e.record($e.string(),$e.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:$e.string().optional(),disableGpu:$e.boolean().optional(),bustCacheOnBoundingBoxChange:$e.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:$e.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long.")});var rt="BASE_URL",Aa="CURRENT_URL",xo="ENV_NAME",vi="TEST_NAME",mk={[rt]:"https://www.google.com"},am=tn.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),sm=tn.object({name:tn.string(),variables:tn.record(tn.string().describe("variable name"),tn.string().describe("variable value"))}),lm=tn.object({name:tn.string(),variables:tn.record(tn.string().describe("variable name"),tn.unknown().describe("variable value")),browser:_r.optional()});Le(Dr);var Ri=Dr.object({env:Dr.record(Dr.unknown())}).openapi({ref:"TestContextSnapshot"}),_T="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",DT=[rt,xo,vi],dm=[Aa,rt,xo,vi],Vt=class n{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,t=void 0,r={}){return new n({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:t,variablesFromEnvironment:r})}static fromSnapshot({snapshot:e,environmentVariables:t}){let r=e.env[rt]??"about:blank",o=e.env[Aa]??"about:blank",i=e.env[xo],a=e.env[vi],s={};for(let[c,d]of Object.entries(e.env))dm.includes(c)||(t??{})[c]===void 0&&(s[c]=d);return new n({baseUrl:r,currentUrl:o,dynamicVariables:s,envName:i,testName:a,variablesFromEnvironment:t??{}})}setEnvVariables(e){let t=Ci(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){DT.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[xo]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Ci(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>dm.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,_T]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:i}=cm(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(i)}catch{e.env[r]=void 0}}let{jsonString:t}=cm(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Aa]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Ci(e.variablesFromEnvironment),this.setMomenticSystemVariable(rt,e.baseUrl),e.envName&&this.setMomenticSystemVariable(xo,e.envName),e.testName&&this.setMomenticSystemVariable(vi,e.testName)}getDynamicVariablesCopy(){return Ci(this.env)}getVariablesFromEnvironmentCopy(){return Ci(this.varsFromMomenticEnvironment)}};var Ee=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ee||{}),xa=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))(xa||{});import{z as Fr}from"zod";Le(Fr);var ge=(c=>(c.AI_PROVIDER="AIProviderError",c.USER_INFRA="UserInfrastructureError",c.ACTION_FAILURE="ActionFailureError",c.ASSERTION_FAILURE="AssertionFailureError",c.CONFIG_ERROR="UserConfigurationError",c.WEB_AGENT_PLATFORM="InternalWebAgentError",c.UNKNOWN_PLATFORM="InternalPlatformError",c.JOB_TIMEOUT="JobTimeoutError",c.UNKNOWN="UnknownError",c))(ge||{});var um=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Ia={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error"},Io={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},nc=Fr.object({reason:Fr.nativeEnum(ge),summary:Fr.string()}).openapi({ref:"TestResultClassification"}),Pa=Fr.object({errorMessage:Fr.string(),errorStack:Fr.string().optional(),classification:nc.optional()}).openapi({ref:"TestFailureDetails"});Le(G);var rc=G.object({beforeUrl:G.string().optional(),afterUrl:G.string().optional(),message:G.string().optional(),beforeScreenshot:G.string().optional(),afterScreenshot:G.string().optional(),beforeSnapshot:G.string().optional(),afterSnapshot:G.string().optional(),startedAt:G.coerce.date(),finishedAt:G.coerce.date()}),FT=rc.extend({viewport:G.object({height:G.number(),width:G.number()}).nullish(),status:G.nativeEnum(xa),message:G.string().optional(),elementInteracted:G.string().optional()}),Ur=rc.extend({status:G.nativeEnum(Ee),message:G.string().optional(),data:G.unknown().optional(),beforeTestContext:Ri.optional(),afterTestContext:Ri.optional(),failureReason:G.nativeEnum(ge).optional(),details:G.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"}),La=Ur.merge(xt).extend({results:FT.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:G.lazy(()=>Ze.array()).optional(),proposedStep:xt.optional()}),UT=Ur.merge(Or).extend({results:G.lazy(()=>La.array()),previousAttempts:G.lazy(()=>Ze.array()).optional()}),BT=Ur.merge(Co).extend({results:G.lazy(()=>La.array()),previousAttempts:G.lazy(()=>Ze.array()).optional()}),HT=Ur.merge(Dn).extend({moduleName:G.string().optional(),results:G.lazy(()=>Ze.array()),previousAttempts:G.lazy(()=>Ze.array()).optional()}),zT=Ur.merge(Mr).extend({assertion:La.optional(),results:G.lazy(()=>Ze.array()).describe("results for the block actually executed"),previousAttempts:G.lazy(()=>Ze.array()).optional()}),$T=Ur.merge(Ti).extend({results:G.lazy(()=>Ze.array()),healingAttempts:G.lazy(()=>Ze.array().array()).optional(),previousAttempts:G.lazy(()=>Ze.array()).optional()}),Ze=G.discriminatedUnion("type",[UT,BT,La,HT,zT,$T]),Oa=Ur.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Ma=rc.extend({index:G.number().optional(),description:G.string(),pageState:G.string().optional(),elementInteracted:G.string().optional(),startedAt:G.coerce.date().or(G.string()).optional().catch(void 0),finishedAt:G.coerce.date().or(G.string()).optional().catch(void 0)});var oc=jT.object({results:Ze.array().describe("main results"),beforeResults:Ze.array().optional(),afterResults:Ze.array().optional()}),Na=oc.partial();import{z as U}from"zod";import{z as Fe}from"zod";var ic=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(ic||{});var GT=Fe.object({type:Fe.literal("DESCRIPTION_UPDATE"),thoughts:Fe.string()}),ka=Fe.discriminatedUnion("type",[GT]),WT=Fe.object({testId:Fe.string(),name:Fe.string(),orgId:Fe.string(),runId:Fe.string(),steps:De.array(),purpose:Fe.nativeEnum(ic),details:ka.or(ka.array()).optional()});var Hk=WT.pick({name:!0,orgId:!0}),ac=Fe.object({id:Fe.string(),name:Fe.string().nullish(),createdAt:Fe.string().pipe(Fe.coerce.date()).or(Fe.date()),organizationId:Fe.string(),schemaVersion:Fe.string(),runId:Fe.string().nullish(),purpose:Fe.nativeEnum(ic),details:ka.or(ka.array()).optional(),applied:Fe.boolean().nullish(),appliedAt:Fe.coerce.date().nullish()}),mm=ac.extend({steps:De.array()});import{isValidCron as VT}from"cron-validator";import{z as oe}from"zod";import{z as sc}from"zod";var Fn=(r=>(r.CHROMIUM="Chromium",r.GOOGLE_CHROME="Google Chrome",r.CHROME_FOR_TESTING="Chrome for Testing",r))(Fn||{});var _a=sc.object({width:sc.number().min(200).max(1e4),height:sc.number().min(200).max(1e4)}),pm={"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}},jk=Object.keys(pm);var Pt=pm["Desktop Large"],Po="en-us",Lo="America/Los_Angeles";var Oo={latitude:37.7749,longitude:-122.4194};var gm=["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 hm=2e3,Da=_r.extend({browserType:oe.nativeEnum(Fn).optional(),slowMoMs:oe.number().optional().refine(n=>n===void 0||n<=hm&&n>=-1,{message:`Slow motion must be between 0 and ${hm} milliseconds`}),basicAuthorization:oe.object({username:oe.string().optional(),password:oe.string().optional()}).optional(),geolocation:oe.object({latitude:oe.coerce.number().refine(n=>n>=-90&&n<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:oe.coerce.number().refine(n=>n>=-180&&n<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:oe.boolean().optional(),locale:oe.string().optional(),timezone:oe.enum(gm).optional(),colorScheme:oe.enum(["light","dark"]).optional()}),fm=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],lc=oe.object({useMemory:oe.boolean().optional(),failureRecovery:oe.boolean().optional().describe("undefined means inherit org settings")}),qT=lc.extend({disableAICaching:oe.boolean().optional(),failureRecoveryInstructions:oe.string().optional()}),KT=oe.object({viewport:_a.optional()}),Br=KT.merge(qT).merge(Da),Mo=oe.object({cron:oe.string().refine(n=>VT(n),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:oe.boolean().default(!1),env:oe.string().optional(),timeZone:oe.string().default("America/Los_Angeles"),jobKey:oe.string().optional()}),No=oe.object({onSuccess:oe.boolean().default(!1),failureMessage:oe.string().optional(),onFailure:oe.boolean().default(!0),successMessage:oe.string().optional()}),YT=oe.object({name:oe.string(),required:oe.boolean().optional(),defaultValue:oe.string().describe("this is not optional because we need a value when the editor is first loaded")}),Fa=YT.array(),XT=oe.object({name:oe.string(),value:oe.string()}),Sm=XT.array(),Ua=oe.object({name:oe.string(),default:oe.boolean().optional(),fixtures:am.array().optional()});Le(U);var qt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ue=(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))(ue||{}),Ba=(t=>(t.BEFORE_ALL="BEFORE_ALL",t.AFTER_ALL="AFTER_ALL",t))(Ba||{});var Ke=U.string().pipe(U.coerce.date()).or(U.date()),Ai=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),createdAt:Ke,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:Ke.or(U.null()),startedAt:Ke.or(U.null()),updatedAt:Ke.nullish(),finishedAt:Ke.or(U.null()),resolvedBaseUrl:U.string().nullish(),environmentName:U.string().nullish(),gitBranchName:U.string().nullish(),githubRepository:U.string().nullish(),gitlabProjectPath:U.string().nullish(),labels:U.array(U.string()).optional(),gitOriginUrl:U.string().nullish(),gitCommitSha:U.string().nullish(),gitCommitShaShort:U.string().nullish(),gitCommitAuthorName:U.string().nullish(),cliVersion:U.string().nullish(),section:U.nativeEnum(Ba).nullish(),status:U.nativeEnum(ue),trigger:U.nativeEnum(qt),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(ue),startedAt:Ke.or(U.null()),finishedAt:Ke.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(ge).nullish(),failureDetails:Pa.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),testFragments:U.array(ac).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),JT={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},Ha=Ai.pick({...JT,test:!0}),ym=Ai.omit({failureReason:!0,failureDetails:!0,test:!0}),cc=Ai.extend({stepsSnapshot:U.array(U.record(U.unknown())).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),test:U.object({name:U.string(),id:U.string(),description:U.string().nullish(),baseUrl:U.string().nullish(),advanced:Br.nullish()}).nullish()}).merge(oc),bm=n=>n.includes("PASSED")&&n.includes("FAILED");var QT=xi.object({id:xi.string().uuid(),startedAt:Ke.or(xi.null()),finishedAt:Ke.or(xi.null()),status:xi.nativeEnum(ue)}).merge(Na),u_=QT.array();var za=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(za||{});import{z as Ye}from"zod";var ZT=Ye.object({id:Ye.string(),status:Ye.nativeEnum(ue),trigger:Ye.nativeEnum(qt),createdAt:Ke,startedAt:Ke.nullish(),finishedAt:Ke.nullish(),gitCommitSha:Ye.string().nullish(),gitCommitShaShort:Ye.string().nullish(),gitCommitTimestamp:Ke.nullish(),gitBranchName:Ye.string().nullish(),gitOriginUrl:Ye.string().nullish(),gitCommitMessage:Ye.string().nullish(),gitCommitAuthorName:Ye.string().nullish(),githubRepository:Ye.string().nullish(),gitlabProjectPath:Ye.string().nullish(),pipelineId:Ye.string().nullish(),cliVersion:Ye.string().nullish(),labels:Ye.string().array().optional(),suite:Ye.object({id:Ye.string(),name:Ye.string()}).nullish(),runs:Ye.object({status:Ye.nativeEnum(ue)}).array()}).openapi({ref:"RunGroup"}),wm=ZT.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:Ha.array()});import{z as ot}from"zod";var eE=ot.object({type:ot.literal("TARGETING"),name:ot.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:rm.array(),pageState:ot.string().optional(),targetSource:ot.nativeEnum(Xn).optional(),targetUpdateTime:ot.string().optional()}),tE=ot.object({type:ot.literal("AI_LOCATION"),matched:ot.boolean(),pageState:ot.string().optional(),ragUsed:ot.boolean().optional(),thoughts:ot.string().optional()}),nE=ot.object({type:ot.literal("ASSERTION"),relevantElementsSerialized:ot.string().array().optional(),pageState:ot.string().optional(),ragUsed:ot.boolean().optional()}),Tm=ot.discriminatedUnion("type",[eE,tE,nE]);function $a(){return{details:[]}}import{z as je}from"zod";var rE=je.object({id:je.string(),name:je.string()}),R_=rE.merge(je.object({createdAt:Ke,createdBy:je.string(),schedule:Mo,notification:No,environment:je.object({name:je.string()}).nullish(),beforeTests:je.object({id:je.string()}).array().nullish(),afterTests:je.object({id:je.string()}).array().nullish()})),Em=je.object({id:je.string().uuid(),orgId:je.string(),createdAt:Ke,startedAt:Ke.or(je.null()),finishedAt:Ke.or(je.null()),status:je.nativeEnum(ue),trigger:je.nativeEnum(qt),suite:je.object({id:je.string(),name:je.string()}).nullish(),runs:Ai.array()}),A_=Em.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),vm=Em.extend({runs:Ha.array()});import{z as Kt}from"zod";import{cloneDeep as L_}from"lodash-es";import{z as fe}from"zod";var D_=fe.object({thoughts:fe.string(),subGoals:fe.object({instruction:fe.string()}).array()}),F_=fe.object({thoughts:fe.string(),newPlanMarkdown:fe.string()}),U_=fe.object({thoughts:fe.string(),correct:fe.boolean(),failedActionIndex:fe.number().optional()}),oE=fe.object({type:fe.literal("PLANNING"),beforePlan:fe.string(),goalDecision:fe.string(),thoughts:fe.string()}),iE=fe.object({type:fe.literal("RUNNING"),stepDisplayName:fe.string(),status:fe.nativeEnum(Ee),results:Ze.array()}),aE=fe.object({type:fe.literal("REVISING"),beforePlan:fe.string(),afterPlan:fe.string(),errString:fe.string(),diffs:fe.string(),thoughts:fe.string()}),sE=fe.object({type:fe.literal("SYSTEM"),message:fe.string()}),lE=fe.discriminatedUnion("type",[oE,iE,aE,sE]),Cm=lE.array();var j_=Kt.object({id:Kt.string(),scheduledAt:Kt.coerce.date().nullable(),startedAt:Kt.coerce.date().nullable(),finishedAt:Kt.coerce.date().nullable(),status:Kt.nativeEnum(ue),history:Cm.nullable(),testPlan:Kt.object({id:Kt.string(),name:Kt.string()}).nullable(),test:Kt.object({id:Kt.string(),name:Kt.string()}).nullable()});import{z as Et}from"zod";var dc=Et.object({content:Et.string(),ids:Et.string().array(),tokenLength:Et.number()}),cE=Et.object({chunks:dc.array()}),sD=Et.object({ids:Et.string().array(),score:Et.number(),tokenLength:Et.number()}),lD=cE.extend({description:Et.string().describe("Input to pass to RAG engine"),tokenLimit:Et.number()}),Rm=Et.object({ids:Et.number().array()}),Am=Et.object({indices:Et.number().array()});var Lt=O.object({disableCache:O.boolean().optional(),useMemory:O.boolean().optional(),loggerTags:O.record(O.string(),O.string()).optional(),langfuseSessionId:O.string().optional(),agentConfigVersion:O.string().optional()}),fD=Lt.extend({chunks:dc.array(),description:O.string().describe("Input to pass to AI"),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),softTokenLimit:O.number(),hardTokenLimit:O.number()}),dE=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),xm=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:Ra.optional().catch(void 0),memory:O.discriminatedUnion("type",[gi,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),Im=O.object({target:O.string().or(O.number()),browserState:O.string().optional(),screenshot:O.string().optional(),boundingBox:O.object({x:O.number(),y:O.number(),height:O.number(),width:O.number()}).optional()}),Pm=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),Lm=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:Fl.optional(),memory:O.discriminatedUnion("type",[Ml,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),Om=O.object({command:vo}),uc=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:dE.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),Mm=O.object({results:Ma.array(),errorMessage:O.string(),errorStack:O.string().optional()}),Nm=O.object({results:Ma.array(),goal:O.string(),errorMessage:O.string()}),km=O.object({failedResults:Ma.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),SD=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()});import{z as Ii}from"zod";var wD=Ii.object({goal:Ii.string()}),_m=Ii.object({keywords:Ii.array(Ii.string())});import{z as mc}from"zod";var pc=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(pc||{}),vD=mc.nativeEnum(pc),uE=mc.enum(["v1","v2"]),CD=uE.or(mc.string().describe("for people with special configurations"));import{z as Ge}from"zod";var mE=Ge.object({id:Ge.number(),thoughts:Ge.string(),attributesRequired:Ge.array(Ge.string()).optional(),elementsRequired:Ge.array(Ge.number()).optional(),textRequired:Ge.boolean()}),Dm=Ge.object({description:Ge.string(),screenXml:Ge.string(),screenshot:Ge.string()}),Fm=Ge.object({assertion:Ge.string(),screenXml:Ge.string(),screenshot:Ge.string()}),pE=Ge.object({thoughts:Ge.string(),result:Ge.boolean(),relevantElements:Ge.array(Ge.number()).optional()});var Um=n=>!(!n.org_id||!n.user_id||!n.platform);import{z as Hr}from"zod";var Bm=Hr.object({id:Hr.string().uuid(),skipped:Hr.boolean().optional(),envKey:Hr.string().optional().describe("key in the environment to save the result of this step to")}),gc=Bm.merge(ya).extend({type:Hr.literal("REQUEST")}),hc=Bm.merge(ba).extend({type:Hr.literal("JAVASCRIPT")}),fc=Hr.discriminatedUnion("type",[hc,gc]);import{z as Yt}from"zod";import{z as zr}from"zod";var gE=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Ce=n=>{let e=n.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 ja=zr.string().min(1).max(255).superRefine((n,e)=>{try{$r(n)}catch(t){return e.addIssue({code:zr.ZodIssueCode.custom,message:t.message,fatal:!0}),zr.NEVER}});function $r(n){if(n=n.toLowerCase().trim(),n.length===0||n.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(n))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(n.endsWith("-")||n.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(n.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(n))throw new Error(`"${n}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(n)||/^\s|\s$/.test(n))throw new Error("Name cannot start or end with a space or dot.");if(n.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(n==="none")throw new Error("Name cannot be 'none'.");if(n.match(gE))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Ga=zr.preprocess(n=>n===null?"":n,zr.union([zr.string().url(),zr.literal("")])).optional();var Hm=Yt.object({id:Yt.string(),name:ja,description:Yt.string().optional().nullish(),baseUrl:Ga.nullish(),schemaVersion:Yt.string(),advanced:Yt.unknown().optional(),retries:Yt.number(),envs:Yt.array(Ua).nullish(),parameters:Fa.nullish()}),hE=Yt.object({createdAt:Yt.coerce.date(),updatedAt:Yt.coerce.date(),schedule:Mo.nullish(),notification:No.nullish(),createdBy:Yt.string(),organizationId:Yt.string()}),fE=Hm.merge(hE),XD=fE.extend({steps:fc.array()}),JD=Hm.extend({steps:fc.array()});import{z as Ot}from"zod";var zm=Ot.object({startedAt:Ot.coerce.date(),finishedAt:Ot.coerce.date(),status:Ot.nativeEnum(Ee),message:Ot.string().optional(),data:Ot.unknown().optional()}),SE=zm.merge(hc).extend({type:Ot.literal("JAVASCRIPT")}),yE=zm.merge(gc).extend({type:Ot.literal("REQUEST")}),bE=Ot.discriminatedUnion("type",[SE,yE]),$m=Ot.object({startedAt:Ot.coerce.date(),finishedAt:Ot.coerce.date().nullish(),status:Ot.nativeEnum(ue),results:bE.array(),failureReason:Ot.string().nullish(),failureDetails:Pa.nullish()});import{z as Mt}from"zod";var wE=Mt.object({id:Mt.string(),organizationId:Mt.string(),createdAt:Mt.coerce.date(),updatedAt:Mt.coerce.date(),createdBy:Mt.string(),scheduledAt:Mt.coerce.date().nullish(),startedAt:Mt.coerce.date().nullish(),finishedAt:Mt.coerce.date().nullish(),status:Mt.nativeEnum(ue),trigger:Mt.nativeEnum(qt),results:$m.array().nullish(),apiTestName:Mt.string().nullish(),apiTestPath:Mt.string().nullish(),apiTestId:Mt.string().nullish()}),sF=wE.pick({status:!0,startedAt:!0,finishedAt:!0});var Pi=(t=>(t.TestRun="test-run",t.CreditsUsed="credits-used",t))(Pi||{}),jm=3;function TE(n){return n==="MODULE"||n==="CONDITIONAL"||n==="SECTION"||n==="RESOLVED_MODULE"}function Li(n){if(!TE(n))switch(n){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"})(n)}}function Oi(n){switch(n.type){case"AI_EXTRACT":case"AI_ASSERTION":return jm;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 n.useSelector||!n.target||n.target.type!=="description"?0:1;case"DRAG":return n.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"OFFLINE_MODE":return 0;default:(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}var nr=class{async reportBillableEvent(e,t,r){}async reportCreditsUsed(e,t,r,o){}};function Sc(n,e){return{...n,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as EE,splitCookiesString as vE}from"set-cookie-parser";import{z as be}from"zod";var yc=be.object({name:be.string(),value:be.string(),url:be.string().optional(),domain:be.string().optional(),path:be.string().optional(),expires:be.number().default(Date.now()/1e3+60*60*24*365),httpOnly:be.boolean().optional(),secure:be.boolean().default(!0),sameSite:be.union([be.literal("Strict"),be.literal("Lax"),be.literal("None")]).default("None")});function Wa(n,e){let t=[],r=vE(n);for(let o of r){let i=EE(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let d=i.sameSite.trim().toLowerCase();if(d==="strict")a="Strict";else if(d==="lax")a="Lax";else if(d==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=yc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});t.push(s);let l=[s.name,...Object.keys(s)].map(d=>d.toLowerCase()),c=o.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[u,m]=d.split("=");if(!u||!m)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(u.toLowerCase())||t.push({...s,name:u,value:m})}}return t}var CE=be.object({origin:be.string(),localStorage:be.array(be.object({name:be.string(),value:be.string()}))}),RE=be.object({entries:be.record(be.string(),be.array(be.tuple([be.unknown(),be.unknown()]))),version:be.number().optional()}),Va=be.object({cookies:yc.array().optional(),origins:CE.array().optional(),idb:be.record(be.string(),RE).optional().describe("key is db name")});function Gm(n,e){let t=[];return n.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=yc.safeParse({name:r.key,...r});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),t.push(i)}),t}var PF=new Set(Object.values(ze));var AE={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},LF={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],OFFLINE_MODE:[],SUCCESS:[]},OF={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import xE from"semver";import{z as IE}from"zod";var _F=IE.string().refine(n=>xE.valid(n),{message:"must be a valid semver string"});import{Faker as UF,en as BF}from"@faker-js/faker";import{z as V}from"zod";var qa=55555,jF=V.object({body:V.string(),to:V.string(),from:V.string()}),GF=V.object({from:V.string().optional(),to:V.string(),timeout:V.number().optional(),beforeDate:V.string().pipe(V.coerce.date()).or(V.date()).optional(),afterDate:V.string().pipe(V.coerce.date()).or(V.date()).optional()}),WF=V.object({to:V.string(),from:V.string(),subject:V.string(),body:V.string()}),VF=V.object({inbox:V.string(),afterDate:V.string().pipe(V.coerce.date()).or(V.date()).optional(),timeout:V.number().optional(),trimWhitespace:V.boolean().optional()}),qF=V.object({inbox:V.string(),limit:V.number().optional(),afterDate:V.string().pipe(V.coerce.date()).or(V.date()).optional(),trimWhitespace:V.boolean().optional()});var Wm=V.object({result:V.unknown(),variableUpdates:V.record(V.string(),V.unknown()).optional(),persistentVariableUpdates:V.record(V.string(),V.unknown()).optional(),error:V.string().optional(),success:V.boolean()}),KF=V.object({id:V.string().optional(),orgId:V.string(),momenticLambdaAuthHash:V.string(),code:V.string(),fragment:V.boolean(),state:Ri,timeoutMs:V.number().optional()}),rr=15e3;import*as gt from"zod";Le(gt);var PE=gt.object({url:gt.string(),lineNumber:gt.number(),columnNumber:gt.number()}).openapi({ref:"CodeLocation"}),Ka=gt.object({timestamp:gt.number(),text:gt.string(),type:gt.string(),tabIndex:gt.number(),args:gt.unknown().array().optional(),url:gt.string().optional(),location:PE.optional()}).openapi({ref:"ConsoleLog"}),Vm=Ka.array(),LE=Vm.array();import*as wc from"zod";import{z as I}from"zod";var OE=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),ME=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),NE=I.object({onContentLoad:I.number().optional(),onLoad:I.number().optional(),comment:I.string().optional()}),Km=I.object({startedDateTime:I.string(),id:I.string(),title:I.string().optional(),pageTimings:NE,comment:I.string().optional()}),kE=I.array(Km),_E=I.object({name:I.string(),value:I.string(),path:I.string().optional(),domain:I.string().optional(),expires:I.string().optional(),httpOnly:I.boolean().optional(),secure:I.boolean().optional(),comment:I.string().optional()}),Ym=I.array(_E),DE=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),Xm=I.array(DE),FE=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),UE=I.array(FE),BE=I.object({name:I.string(),value:I.string().optional(),fileName:I.string().optional(),contentType:I.string().optional(),comment:I.string().optional()}),HE=I.array(BE),zE=I.object({mimeType:I.string(),params:HE,text:I.string(),comment:I.string().optional()}),$E=I.object({method:I.string(),url:I.string(),httpVersion:I.string().optional(),cookies:Ym,headers:Xm,queryString:UE,postData:zE.optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),jE=I.object({size:I.number().optional(),compression:I.number().optional(),mimeType:I.string().optional(),text:I.string().optional(),encoding:I.string().optional(),comment:I.string().optional()}),GE=I.object({status:I.number(),statusText:I.string(),httpVersion:I.string().optional(),cookies:Ym,headers:Xm,content:jE,redirectURL:I.string().optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),qm=I.object({expires:I.string().optional(),lastAccess:I.string(),eTag:I.string(),hitCount:I.number(),comment:I.string().optional()}),WE=I.object({beforeRequest:qm.optional(),afterRequest:qm.optional(),comment:I.string().optional()}),VE=I.object({blocked:I.number().optional(),dns:I.number().optional(),connect:I.number().optional(),send:I.number(),wait:I.number(),receive:I.number(),ssl:I.number().optional(),comment:I.string().optional()}),Jm=I.object({pageref:I.string().optional(),startedDateTime:I.string(),time:I.number().optional(),request:$E,response:GE.optional(),cache:WE.optional(),timings:VE,serverIPAddress:I.string().optional(),connection:I.string().optional(),comment:I.string().optional(),_resourceType:I.string().optional()}),qE=I.array(Jm),KE=I.object({version:I.string().default("1.1"),creator:OE.optional(),browser:ME.optional(),pages:kE.optional(),entries:qE,comment:I.string().optional()}),YE=I.object({log:KE}),Qm=I.record(I.string(),Km),Zm=I.record(I.string(),Jm);function bc(n,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(n).sort((t,r)=>new Date(t.startedDateTime).getTime()-new Date(r.startedDateTime).getTime()),entries:Object.values(e).sort((t,r)=>new Date(t.startedDateTime).getTime()-new Date(r.startedDateTime).getTime())}}}Le(wc);var XE=wc.object({logsPerPage:Ka.array().array(),harPages:Qm.optional(),harEntries:Zm.optional()}).openapi({ref:"DebugData"});var nn=class{async getConsoleLogsForRunAttempt(e,t,r){}async getNetworkLogsForRunAttempt(e,t,r){}async getHtmlSnapshot(e,t){}async getA11yTreeSnapshot(e,t){}async getScreenshot(e,t){}async storeConsoleLogsForRunAttempt(e,t,r,o){}async storeNetworkLogsForRunAttempt(e,t,r,o){}async storeScreenshot(e,t,r){}async storeHtmlSnapshot(e,t,r){}};var Ya=class extends Error{constructor(e,t,r,o={}){super(`The ${r} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function ep(n){for(let e of Object.values(ge))if(n.includes(e))return e}var A=class extends Error{reason;constructor(e,t,r){let o=!1;for(let i of Object.values(ge))if(t.startsWith(i)){o=!0,e=i;break}if(r?.errOptions?.cause)super(o?t:`${e}: ${t}`,r?.errOptions);else{let i=o?t:`${e}${t?`: ${t}`:""}`;super(i,r?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e,Object.defineProperty(this,"lastScreenshotBuffer",{value:r?.lastScreenshotBuffer,enumerable:!1})}getLastScreenshotBuffer(){return"lastScreenshotBuffer"in this?this.lastScreenshotBuffer:void 0}toString(){return this.message}toJSON(){return{message:this.message}}},bn=class extends Error{decisions;constructor(e,t,r={}){super(e,r),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
5
5
  Decisions:
6
6
  ${this.decisions.map(e=>e.toString()).join(`
@@ -34,7 +34,7 @@ ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length
34
34
  `)}function _g(n,e){try{if(!n)return n;if(typeof n=="string")return qe(n,3e4);if(typeof n=="object"){let{jsonString:t}=kg(JSON.stringify(n,(r,o)=>e?.includes(r)||typeof o=="string"&&o.length>3e4?"REDACTED":o),2e4);return JSON.parse(t)}return n}catch{return n}}function $c(n,e){for(let t=0;t<n.length;t++){let r=n[t];try{if(r.data){let{jsonString:o}=kg(JSON.stringify(r.data),1e3);r.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),r.data=`Result output data could not be serialized: ${o}`}switch(r.details&&(r.details=void 0),r.type){case"PRESET_ACTION":Mg(r);break;case"CONDITIONAL":r.assertionResult&&Mg(r.assertionResult),$c(r.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{$c(r.results,e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}}function Mg(n){let e=n.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Ng(n,e){let t=JSON.stringify(n),r=t.replaceAll("\\u0000","");if(t.length!==r.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 r}function ls(n,e){let t=qv(n);if($c(t,e),t.length>Pg)return e.error("Database content violation: results too long, truncating before insertion"),t.slice(0,Pg);let r=Ng(t,e);if(r.length>Lg)for(e.error({serializedLength:r.length,resultsArrayLength:t.length},"Database content violation: results too large, truncating before insertion");r.length>Lg;)t.pop(),r=Ng(t,e);try{return Ze.array().parse(JSON.parse(r))}catch(o){throw e.error({serialized:r,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as sj}from"lodash-es";var Yv=/^(?!.*\S+\s+\S+).*$/,Xv=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,Jv=/style="([^"]*)/g,Qv=/data-[\w-]+/g,Zv=n=>{switch(n.type){case"AI_ASSERTION":return{type:n.type,assertion:n.assertion};case"DRAG":if(n.fromTarget.type==="description")return{type:n.type,description:n.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(n.target?.type==="description")return{type:n.type,description:n.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function Dg(n){let e=Zv(n),t=e.type==="AI_ASSERTION"?e.assertion:e.description;return!t||t==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:Yv.test(t)&&Xv.test(t)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:Jv.test(t)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:Qv.test(t)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(t)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function Fg(n,e){if(!(!n.envs||!n.envs.length)){for(let t of n.envs){let r=t;e in t&&(r[e]&&(t.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}n.envs.some(t=>t.default)||(n.envs[0].default=!0)}}import{cloneDeep as ch}from"lodash-es";import oC from"diff-lines";import ds,{gte as iC}from"semver";var Ug={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async n=>(n=n.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),n=n.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),n)};var Bg={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 n=>n.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,r=t[t.length-1];return r&&r.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var eC=["target","fromTarget","toTarget"];function Hg(n){for(let e of eC){if(n[e]===void 0)continue;let t=n[e];t.elementDescriptor!==void 0?t.type="description":n[e]={type:"description",elementDescriptor:""}}}var zg={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":return Hg(e.command),e;case"AI_ACTION":{let t=e.commands;for(let r of t??[])Hg(r);return e}default:return e}})};import{v4 as tC}from"uuid";var $g={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=tC()),e;default:return e}})};import{v4 as jg}from"uuid";var Gg={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??jg(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??jg()}})),delete e.commands),e;default:return e}})};var Wg={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 n=>n.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 nC}from"uuid";var Vg={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 n=>n.map(e=>("id"in e&&typeof e.id=="string"||(e.id=nC()),e))};import{v4 as qg}from"uuid";var Kg={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 n=>n.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=qg())}return e.id=qg(),e})};var Yg={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 n=>n.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 rC}from"uuid";var Xg={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=rC()),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 Jg={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.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 Qg={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Zg(t),e})};function Zg(n){n&&Object.keys(n).forEach(e=>{if(typeof n[e]=="object"&&n[e]){Zg(n[e]);return}if(typeof n[e]!="string")return;let t=n[e];e==="code"?n[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(n[e]=t.replace(/inputs\./g,"env."))})}var eh={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async n=>n.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 th={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async n=>n.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 nh={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 n=>n.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 rh={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 n=>n.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 oh={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async n=>n.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var cs=new Set(["CLICK","TYPE","SELECT_OPTION"]),ih={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type,o=t?.elementDescriptor;return(o!==void 0||cs.has(r))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,l=a?.type;(s!==void 0||cs.has(l))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,l=s?.elementDescriptor,c=s?.type;(l!==void 0||cs.has(c))&&(s.target={elementDescriptor:l??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(u=>{let m=u?.elementDescriptor,g=u?.type;(m!==void 0||cs.has(g))&&(u.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var ah={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var sh={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async n=>n.map(e=>{let t=e.command,r=t?.type;return r?.startsWith("PRESET_")&&(t.type=r.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(c=>{let d=c.type;d?.startsWith("PRESET_")&&(c.type=d.slice(7))})}),e}),stopOnFailure:!0};var Wr=[oh,ah,sh,ih,Ug,Bg,zg,$g,Gg,Wg,Vg,Kg,Yg,Xg,Jg,Qg,eh,th,nh,rh];if(se!==Wr[Wr.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Wr.forEach((n,e)=>{if(!ds.valid(n.toVersion)||!ds.valid(n.fromVersion))throw new Error(`Migration '${n.name}' has invalid version`);if(!ds.gt(n.toVersion,n.fromVersion))throw new Error(`Migration '${n.name}' has toVersion <= fromVersion`);if(e===0)return;if(Wr[e-1].toVersion!==n.fromVersion)throw new Error(`Migration '${n.name}' at index ${e} is not contiguous with previous migration`)});function aC(n){return n.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Bi=async({metadata:n,steps:e,logger:t,toVersion:r})=>{let o=e,{schemaVersion:i,id:a}=n,s=Wr.findIndex(d=>ds.gt(d.toVersion,i));if(s===-1)return{steps:o,newVersion:i};let l=i;for(let d=s;d<Wr.length;d++){if(r&&iC(l,r)){t.debug("Stopping migration early because toVersion was reached");break}let u=Wr[d],m={id:a,migration:u.name,toVersion:u.toVersion};try{o=await lh(o,u),l=u.toVersion}catch(g){throw t.error({err:g,...m},"Migration failed"),new Error(`Step migration ${u.name} failed: ${g}`)}}let c=oC(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:a},"Migration diffs"),{newVersion:l,steps:o}};async function lh(n,e){let t=await e.execute(n);for(let r of t)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let i=r[o];!i||!Array.isArray(i)||aC(i)&&(r[o]=await lh(i,e))}return t}async function dh({rawSteps:n,metadata:e,logger:t,callbacks:r}){Fg(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await us({rawSteps:n.steps,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o}),s={...e,steps:i,schemaVersion:a};for(let l of["beforeSteps","afterSteps"]){let c=n[l];if(!c)continue;let{resolvedSteps:d}=await us({rawSteps:c,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o});s[l]=d}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function Vr(n,e,t){let{newVersion:r,steps:o}=await Bi({metadata:n,steps:e,logger:t});try{return{steps:xe.array().parse(o),newVersion:r}}catch(i){throw t.error({type:"zod",err:i,newVersion:r,id:n.id,steps:o},"Failed to parse test steps while migrating test"),new Ya(`Failed to parse test steps while migrating test: ${i}`,n.id,"entity",{cause:i})}}async function us({rawSteps:n,migrationMetadata:e,logger:t,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await Vr(e,n,t),s=[];for(let l of a)s.push(await Hi({step:l,callbacks:r,logger:t,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function Hi({step:n,callbacks:e,logger:t,resolvedModuleCache:r}){switch(n.type){case"AI_ACTION":return n;case"AI_ACTION_DYNAMIC":return n;case"PRESET_ACTION":return n;case"MODULE":{let l=n.moduleId,c=r[l];if(c)return{...ch(c),...n,type:"RESOLVED_MODULE"};let d=await e.onFetchModule({id:l,logger:t});if(!d)throw new Error(`Could not find module with id ${l}`);let{newVersion:u,steps:m}=await Bi({metadata:{id:l,schemaVersion:d.schemaVersion},steps:d.steps,logger:t}),g;try{g=xe.array().parse(m)}catch(f){throw t.error({type:"zod",err:f,steps:m,newVersion:u,id:l},"Module failed to parse"),f}let p;try{p=await Promise.all(g.map(f=>Hi({step:f,callbacks:e,logger:t,resolvedModuleCache:r})))}catch(f){throw t.error({err:f,...n},`Failed to recursively resolve module '${d.name}': ${f}`),f}let h={...d,steps:p};return r[l]=ch(h),{...h,...n,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of n.blocks){let c=[];for(let d of l.steps)c.push(await Hi({step:d,callbacks:e,logger:t,resolvedModuleCache:r}));o.push({...l,steps:c})}let i;if(n.elseSteps){i=[];for(let l of n.elseSteps)i.push(await Hi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}))}return{...n,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let l of n.steps)a.push(await Hi({step:l,callbacks:e,logger:t,resolvedModuleCache:r}));return{...n,steps:a};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}function sC(n){return typeof n=="object"&&n!==null}function Un(n){if(Array.isArray(n))return n.map(Un);if(sC(n)){let e={};return Object.entries(n).forEach(([t,r])=>{r!==void 0&&(e[t]=Un(r))}),e}return n}import{cloneDeep as lC}from"lodash-es";import{stringify as uh}from"yaml";async function mh({test:n,processedModuleNames:e=new Set,createNewCacheIds:t=!1}){let r={id:n.id,name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:n.schemaVersion,advanced:n.advanced,retries:n.retries,envs:n.envs,disabled:n.disabled,labels:n.labels},o={},i=await cC({originalStepLists:{steps:n.steps,beforeSteps:n.beforeSteps,afterSteps:n.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:t}),a={fileType:we.TEST,...r,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:uh(a),modules:o}}async function cC({originalStepLists:n,modules:e,processedModuleNames:t,createNewCacheIds:r}){let o=lC(n);Object.values(o).forEach(s=>{dC(s??[])});let{stepsToSave:i,moduleUpdates:a}=await Be({stepLists:o,createNewCacheIds:r});for(let s of a)t.has(s.name)||(e[s.name]=uC(s),t.add(s.name));return i}function dC(n){Dc({steps:n,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function uC(n){let e=It.parse(n),t={fileType:we.MODULE,...e,schemaVersion:se,steps:n.steps};return uh(t)}async function X(n,e){if(!(n<=0))return new Promise((t,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),t()},n);function i(){clearTimeout(o),e?.removeEventListener("abort",i),r(e?.reason)}})}async function zi({promiseGenerator:n,signal:e,codePath:t,logger:r}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}r?.warn({codePath:t,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${t})`)},5e3);return new Promise((s,l)=>{function c(){clearInterval(a),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(a);return}e?.addEventListener("abort",c),(async()=>{try{s(await n())}catch(d){l(d)}finally{clearInterval(a),e?.removeEventListener("abort",c)}})()})}async function qr({promiseGenerator:n,timeoutMs:e,codePath:t,logger:r,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},l=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",s);try{return await zi({promiseGenerator:n,signal:a.signal,codePath:t,logger:r})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(l)}}function ms(n){let e=[];for(let t of n)switch(t.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(t);break;case"RESOLVED_MODULE":{let r={...t,type:"MODULE"};e.push(Dn.parse(r));break}case"SECTION":{let r={...t,steps:ms(t.steps)};e.push(xe.parse(r));break}case"CONDITIONAL":{let r={...t,blocks:t.blocks.map(o=>({assertion:o.assertion,steps:ms(o.steps)})),elseSteps:t.elseSteps?ms(t.elseSteps):void 0};e.push(Mr.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function ps(n){return ms([n])[0]}import mC from"picomatch";var ph=(n,e,t)=>{t?.caseInsensitive&&(n=n.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=t?.caseInsensitive?e.url.toLowerCase():e.url;r=n.includes(o);break}case"GLOB":{let o=t?.caseInsensitive?e.glob.toLowerCase():e.glob;r=n===e.glob||mC(o)(n);break}case"REGEX":{r=new RegExp(e.regex).test(n);break}}return t?.negated?!r:r},gs=(n,e)=>{try{let{hostname:t,pathname:r}=new URL(n),{hostname:o,pathname:i}=new URL(e);return t!==o||r!==i}catch{return!1}},Fo=n=>{try{return new URL(n),!0}catch{return!1}},gh=n=>!n.toLowerCase().startsWith("http"),Uo=(n,e)=>{try{return new URL(n,e),!0}catch{return!1}};function Kr(n,e){try{return!!new URL(n).origin.trim()}catch(t){return e?.error({url:n,err:t},"Invalid URL in check"),!1}}import Bo from"yaml";import{z as yh}from"zod";import{execSync as pC}from"child_process";function Yr(n,e){let t=e.hooks?.postSave;if(!t)return;let r;t.includes("$1")?r=t.replaceAll("$1",n):r=`${t} ${n}`,y.debug({postSaveCommand:r},"Executing post-save hook command");try{pC(r,{encoding:"utf-8"})}catch(o){y.warn({err:o,postSaveCommand:r},"Failed to execute post-save hook command, continuing...")}}import{diff as hh}from"deep-object-diff";import vn from"fs";import{cloneDeep as gC}from"lodash-es";import $i from"path";import{v4 as hC}from"uuid";import ji from"yaml";function Ut({content:n,schemaVersion:e,momenticFiles:t,project:r,forceSaveOnNoDiffs:o}){let i=t.modules[n.moduleId]?.fullFilePath;if(!i||!vn.existsSync(i))throw new Error(`Tried to update module ${n.moduleId} that could not be found on disk`);let a=vn.readFileSync(i,"utf-8"),s=ji.parse(a),l;if(n.name&&n.name!==s.name){let g=`${Ce(n.name)}.${ft.MODULE}`;if(l=$i.join($i.dirname(i),g),vn.existsSync(l))throw new Error(`Module with name '${n.name}' already exists at path '${l}'`)}let c={...n,schemaVersion:e},d=Un({fileType:we.MODULE,...Lc.parse(c),steps:xe.array().parse(n.steps)}),u=hh(d,s);if(u&&Object.keys(u).length===0&&!o){y.debug(`Skipping save for module ${n.moduleId} since there are no changes`);return}let m=ji.stringify(d);vn.writeFileSync(i,m,"utf-8"),l&&vn.renameSync(i,l),Yr(l||i,r.config)}function fh({moduleId:n,content:e,momenticFiles:t,project:r,logger:o}){let i=t.modules[n]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${n} that could not be found on disk`);let a=Bn(i,o),s={...a,...e},l=Un({fileType:we.MODULE,...Lc.parse(s),steps:a.steps}),c=hh(l,a);if(c&&Object.keys(c).length===0){y.debug(`Skipping save for module ${n} since there are no changes`);return}let d=ji.stringify(l);vn.writeFileSync(i,d,"utf-8");let u;if(e.name){let m=`${Ce(e.name)}.${ft.MODULE}`;if(u=$i.join($i.dirname(i),m),vn.existsSync(u))throw new Error(`Module with name '${e.name}' already exists at path '${u}'`);vn.renameSync(i,u)}Yr(u||i,r.config)}async function Sh({name:n,description:e,enabled:t,steps:r,folder:o,project:i}){let a=Ce(n),s=$i.join(o,`${a}.module.yaml`),l=hC(),{stepsToSave:c}=await Be({stepLists:{steps:r}}),d={fileType:we.MODULE,schemaVersion:se,moduleId:l,name:n,description:e,enabled:t,steps:c.steps},u=ji.stringify(d);return vn.writeFileSync(s,u,"utf-8"),Yr(s,i.config),{moduleId:l,name:n,description:e,enabled:t,steps:r}}function Bn(n,e){let t=vn.readFileSync(n,"utf-8"),r=ji.parse(t);try{return Pc.parse(r)}catch(o){throw e.error({err:o,moduleFilePath:n,moduleContents:t},`${n} does not parse as a valid Momentic module`),o}}async function hs(n,e,t,r){let o=Bn(n.fullFilePath,t),{resolvedSteps:i}=await us({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:r,logger:t,callbacks:{onFetchModule:async({id:s})=>{let l=e.modules[s]?.fullFilePath;if(l)return Bn(l,t)}}}),a={...o,steps:i};return r&&(r[n.id]=gC(a)),a}async function fs(n,e){let t={};return await Promise.all(Object.values(n.modules).map(async r=>{await hs(r,n,e,t)})),Array.from(Object.values(t))}async function bh({test:n,name:e,folder:t}){let r=await mh({test:n});if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${Ce(e)}.${ft.TEST}`,a=Xr.join(t,i);return an.writeFileSync(a,r.test,"utf-8"),a}function jc(n,e,t){let r=Xr.join(t.rootDir,n);if(!an.existsSync(r))throw new Error(`Test not found at path '${n}' in project '${t.rootDir}'`);let o=an.readFileSync(r,"utf-8"),i=Bo.parse(o),a,s;if(e.name&&e.name!==i.name){let m=`${Ce(e.name)}.${ft.TEST}`;if(a=Xr.join(Xr.dirname(n),m),s=Xr.join(t.rootDir,a),an.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let l={...i,...e},c=Xt.parse(l),d={fileType:we.TEST,...Xt.parse(c),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},u=Bo.stringify(d);return an.writeFileSync(r,u,"utf-8"),s&&an.renameSync(r,s),Yr(r,t.config),{newRelativeTestPath:a}}function vt({relativeTestPath:n,steps:e,schemaVersion:t,project:r,forceSaveOnNoDiffs:o}){let i=Xr.join(r.rootDir,n);if(!an.existsSync(i))throw new Error(`Test not found at path '${n}' in project '${r.rootDir}'`);let a=an.readFileSync(i,"utf-8"),s=Bo.parse(a),l=Xt.parse({...s,schemaVersion:t}),c=xe.array().or(yh.undefined()).parse(e.beforeSteps),d=xe.array().parse(e.steps),u=xe.array().or(yh.undefined()).parse(e.afterSteps),m=Un({fileType:we.TEST,...l,beforeSteps:c&&c.length>0?c:void 0,steps:d,afterSteps:u&&u.length>0?u:void 0}),g=fC(m,s);if(g&&Object.keys(g).length===0&&!o){y.debug(`Skipping save for test ${l.name} since there are no changes`);return}let p=Bo.stringify(m);an.writeFileSync(i,p,"utf-8"),y.debug(`Saving test ${l.name} to ${i}`),Yr(i,r.config)}function Ss(n,e){let t=Xr.join(e.rootDir,n);if(!t)throw new Error(`Could not find test with path ${n} in Momentic project (${e.rootDir})`);let r;try{r=an.readFileSync(t,"utf8"),r=r.replace(/\r\n|\r/g,`
35
35
  `)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=Bo.parse(r)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return ht.parse(o)}function Jr(n,e,t){let r=t.project.rootDir,o;try{o=an.readFileSync(n,"utf-8")}catch(a){throw e.error({err:a,projectRoot:r},a.message),new Error(a.message)}let i=Bo.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${n} is missing steps`);return i}async function Ct(n,e,t){let r=Jr(n,e,t),o;try{o=Xt.parse(r)}catch(a){throw new Error(`Test ${n} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await dh({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let l=t.modules[a]?.fullFilePath;if(l)return Bn(l,s)}}});return i}import SC from"@dotenvx/dotenvx";import yC from"fs";import wh from"path";function Eh(n,e){return(n.config.environments??[]).map(t=>Gi(t.name,n,e))}function Th(n){return n.includes("${")?n.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[r,o]=t.split(/:-|-/,2),i=process.env[r];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):n}function Gi(n,e,t){let r=(e.config.environments??[]).find(a=>a.name===n);if(!r)throw new Error(`Environment ${n} not found in local project configuration file`);let o={[rt]:Th(r.baseUrl)};if(r.envVariables){let a={};for(let[s,l]of Object.entries(r.envVariables))if(typeof l=="string"){let c=Th(l);c&&(a[s]=c)}else{let c=l.fromFile,d;try{d=yC.readFileSync(wh.resolve(e.rootDir,c),"utf-8")}catch(u){throw new Error(`Failed to read environment variable '${s}' from file '${c}': ${u}`)}if(l.json)try{a[s]=JSON.parse(d)}catch(u){throw new Error(`Failed to parse environment variable '${s}' from file '${c}' as JSON: ${u}`)}else a[s]=d}Object.keys(a).length>0&&y.debug(a,"Set environment variables with interpolation from project configuration"),Object.assign(o,a)}if(r.envFile){let a={},s=SC.config({path:wh.resolve(e.rootDir,r.envFile),processEnv:a,logLevel:"error",quiet:!0});if(s.error)throw new Error(`Failed to load .env file: ${s.error.message}`);t.debug(a,"Set environment variables from .env file"),Object.assign(o,a)}return r.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:n,variables:o,browser:r.browser}}import{existsSync as vC,readFileSync as CC,readdirSync as RC,writeFileSync as AC}from"fs";import{globSync as xC}from"glob";import Qr,{dirname as Ah}from"path";import{cwd as Kc}from"process";import xh from"yaml";import{z as Pe}from"zod";import vh from"fs";import{globSync as bC}from"glob";import Wi from"path";import wC from"yaml";import{z as Gc}from"zod";var Ch=!1,Wc=[`**/*.${ft.TEST}`,`**/*.${ft.MODULE}`],Vc=Gc.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),qc=50,TC=Gc.object({fileType:Gc.nativeEnum(we)});function J(n,e){let t={project:n,tests:{},modules:{},duplicateEntities:{}},r=n.config.include??Wc,o=Array.from(n.config.exclude??[]).concat(es),i=bC(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:qc,nodir:!0});for(let a of i){let s=EC(n.rootDir,a,t,e);s&&(t.duplicateEntities[s.id]=s.paths)}return Ch=!0,t}function EC(n,e,t,r){let o=Wi.join(n,e),i;try{i=vh.readFileSync(o,"utf-8")}catch(m){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${m}`);return}let a;try{if(a=wC.parse(i),typeof a!="object"||a===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(m){r.warn(`Could not parse possible Momentic file at ${o}, skipping: ${m}`);return}let s=TC.safeParse(a);if(s.success===!1){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let l=s.data.fileType,c;try{c=vh.statSync(o)}catch(m){r.warn(`Skipping path '${o}' because it could not be stat, skipping: ${m}`);return}let d={relativePath:e,fullFilePath:o,platformSep:Wi.sep,fullPathSegments:o.split(Wi.sep),relativePathSegments:e.split(Wi.sep),fileName:Wi.basename(o),lastModified:c.mtime,createdAt:c.birthtime},u;switch(l){case we.TEST:try{let m=Xt.parse(a);if(t.tests[m.id]){let g=t.tests[m.id].fullFilePath;u={id:m.id,paths:[g,o]}}return t.tests[m.id]={type:we.TEST,name:m.name,id:m.id,description:m.description??void 0,labels:m.labels,...d},u}catch(m){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${m}`);return}case we.MODULE:try{let m=It.parse(a);if(t.modules[m.moduleId]){let p=t.modules[m.moduleId].fullFilePath;u={id:m.moduleId,paths:[p,o]}}t.modules[m.moduleId]={type:we.MODULE,name:m.name,id:m.moduleId,description:m.description??void 0,...d};let g=d.fileName.replace(".module.yaml","");return!Ch&&Ce(m.name)!==g&&r.warn(`The module with ID ${m.moduleId} has a name (${m.name}) that does not match its file name (${g}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),u}catch(m){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${m}`);return}default:throw new Error(`Unsupported file type ${l}`)}}var Ho="momentic.config.yaml",Rh="momentic.workspace.yaml",IC=Pe.object({projects:Pe.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),PC=Pe.union([Pe.string(),Pe.object({fromFile:Pe.string(),json:Pe.boolean().optional()})]),LC=Pe.object({name:Vc,baseUrl:Pe.string(),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(),PC).optional(),inheritFromShell:Pe.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:_r.optional()}),OC=Pe.object({postSave:Pe.string().optional()}),MC=Pe.object({name:Vc,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(),retries:Pe.number().optional().describe("number of retries per test"),parallel:Pe.number().optional().describe("degree of parallelism"),environments:Pe.array(LC).optional(),gitMainBranch:Pe.string().optional(),gitProtectedBranches:Pe.string().array().optional(),ai:Oc.optional(),browser:_r.optional(),advanced:Mc.optional(),hooks:OC.optional()});function Ih(n,e){let t;try{t=CC(n,"utf-8")}catch(o){y.warn(`Could not read possible Momentic ${e} file at ${n}: ${o}`);return}let r;try{if(r=xh.parse(t),typeof r!="object"||r===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof r} instead`)}catch(o){y.warn(`Possible Momentic ${e} file at ${n} does not parse as valid YAML: ${o}`);return}return r}function Yc(n){let e=Ih(n,"project configuration");if(e!==void 0)try{return MC.parse(e)}catch(t){y.warn(`Possible Momentic project configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function NC(n){let e=Ih(n,"workspace configuration");if(e!==void 0)try{return IC.parse(e)}catch(t){y.warn(`Possible Momentic workspace configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function kC(){let n=[],e=Kc(),t=Qr.parse(e).root,r=15,o=0;for(;o<r;){o++;let i=Qr.basename(e);if(Za.includes(i))return y.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),n;for(let a of RC(e))if(a.endsWith(Ho)){let s=Qr.join(e,a),l=Yc(s);l&&n.push({configFilePath:s,config:l,rootDir:Ah(s)})}if(n.length)return n;if(e=Qr.dirname(e),e===t)break}return n}function it(n={}){let{configFilePath:e,nameFilter:t}=n,r=Xc(e);if(t&&(r=r.filter(o=>o.config.name===t)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
36
36
  ${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function _C(n){let e=NC(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${Ho}`)),r=xC(t,{absolute:!1,cwd:Kc(),dotRelative:!1,maxDepth:qc,nodir:!0}),o=[];for(let i of r){let a=Qr.join(Kc(),i),s=Yc(a);s&&o.push({configFilePath:a,config:s,rootDir:Ah(a)})}return o}function Xc(n){if(n){n=Qr.resolve(n);let t=Yc(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:Qr.dirname(n)}]}if(vC(Rh)){let t=_C(Rh);if(t)return t}return kC()}function zo(n,e){let t=xh.stringify(n);AC(e,t)}import $o from"fs";import Jc from"path";import{z as Qc}from"zod";var Ph="golden/visual-diff",Lh="reports",Oh="test-results";var DC=Qc.object({width:Qc.number(),height:Qc.number()}),jo=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Jc.join(e.rootDir,e.config.goldenFileDir??Ph);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Jc.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return $o.mkdirSync(Jc.dirname(o),{recursive:!0}),$o.writeFileSync(o,r.buffer),$o.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if($o.existsSync(o)){let a=$o.readFileSync(o),s=DC.parse(JSON.parse($o.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var lr=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import{execFile as FC}from"node:child_process";import{promisify as UC}from"node:util";import BC from"simple-git";var Re=BC(),Mh=UC(FC);async function HC(n){let e=await Ae(n,Re.raw(["config","--list"])),t={};if(!e)return t;for(let r of e.split(`
37
- `)){let o=r.indexOf("=");if(o===-1)continue;let i=r.slice(0,o),a=r.slice(o+1).trim();t[i]=a}return t}async function zC(n,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let r;try{if(e?.startsWith("http://")||e?.startsWith("https://"))r=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(r=e.slice(o+1,i))}}catch{}if(r=r?.toLowerCase(),!!r){try{if(e?.startsWith("git@")&&r?.includes("github")){let{stdout:o,stderr:i}=await Mh("ssh",["-T","-o","BatchMode=yes",`git@${r}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=r&&r!=="github.com"?["api","--hostname",r,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await Mh("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function $C(n,e,t){let r=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(r)return zC(n,e,t);if(o)return}catch{}}function ys(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function Ae(n,e){try{return(await e).trim()}catch(t){n.error({err:t},"Failed to run git command");return}}function jC(){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 GC(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:t,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function WC(n){let[e,t,r]=await Promise.all([Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function VC(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?ys(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function qC(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?ys(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,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 KC(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?ys(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function YC(n,e){let[t,r,o,i,a,s,l,c,d]=await Promise.all([Ae(n,Re.revparse(["HEAD"])),Ae(n,Re.revparse(["--short","HEAD"])),Ae(n,Re.revparse(["--abbrev-ref","HEAD"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"])),e?Ae(n,Re.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),HC(n)]),u=c?await Ae(n,Re.show(["--no-patch","--format=%ci",c])):void 0,m=i?.includes("github.com"),g=i?.includes("gitlab.com"),p=i?ys(i):void 0,h=d["user.email"]||void 0,f=d["user.name"]||void 0,S=d["user.username"]||void 0,b=await $C(n,i,d)??S??void 0;return n.debug({userUsername:b,gitLocalUserLogin:S,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:t,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:l,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:u?new Date(u):void 0,githubRepository:m?p:void 0,gitlabProjectPath:g?p:void 0,pipelineId:void 0}}async function XC(){let n=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:n?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:n?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function JC(n){let e=n.config.gitProtectedBranches??[];return n.config.gitMainBranch&&e.push(n.config.gitMainBranch),{gitMainBranch:n.config.gitMainBranch,gitProtectedBranches:e}}async function Zc(n,e){let t=jC();if(!t)return YC(n,e);switch(t){case"GithubActions":return GC(n);case"GitlabCI":return WC(n);case"CircleCI":return VC(n);case"Buildkite":return qC(n);case"AzureDevOps":return KC(n);case"GCPCloudBuild":return XC()}}async function QC(n,e,t,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGitlab(t,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let i=await e.getCommitFromGitlab(t,r.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}return o}async function ZC(n,e,t,r,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGithub(t,r,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName){let a=await e.getCommitFromGithub(t,r,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}return i}async function eR(n,e,t){try{if(t.githubRepository){let[r,o]=t.githubRepository.split("/");return await ZC(n,e,r,o,t)}else if(t.gitlabProjectPath)return await QC(n,e,t.gitlabProjectPath,t)}catch(r){n.warn({err:r},"Failed to get remote git metadata")}return t}async function cr(n,e,t){let r=await JC(t),o=await Zc(n,r.gitMainBranch),i={...r,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===r.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await eR(n,e,i);return{...r,...o,...a}}import ZV from"yaml";import UP from"http";import{z as td}from"zod";var H="v1",Vi="2.12.0";var dr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Nh=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function B(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{if(e.signal){let{signal:u}=e;if(u.aborted)return c(Nh(u));s=()=>c(Nh(u)),u.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(u){c(u)}else{typeof n.cancel=="function"&&Promise.resolve().then(()=>n.cancel()).catch(()=>{});let u=o instanceof Error?o:new dr(o??`Promise timed out after ${t}ms`);c(u)}};a=i.setTimeout(d,t),Promise.resolve(n).then(u=>l(u)).catch(u=>c(u))}).finally(()=>{i.clearTimeout(a),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var bs=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let r=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(r),!1)}};var tR=9e4,nR=3,rR=1500,oR=15e3,sn=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function iR(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var ed=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Vi&&(e[wp]=Vi),e}async sendRequest(e,t){let{retries:r=nR,requestTimeoutMs:o=tR,initialRetryDelayMs:i=rR,maxRetryDelayMs:a=oR}=t,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(u){if(c=u,u instanceof sn&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError"&&(c=new dr),s===0)throw c;let m=l-s,g=Math.min(i*Math.pow(2,m-1),a);await new Promise(p=>setTimeout(p,g))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),r),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s);let l={...this.getHeaders(),...t.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let u=await iR(c);throw new sn(c.status,u,`Request to ${t.method} ${e} failed with status ${c.status}: ${u}`)}let d;if(c.status===204)d={};else{let u=await c.text();try{d=JSON.parse(u)}catch{d=u}}return this.logger&&!t.noLog&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},Rt=class extends ed{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends Rt{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${H}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Hp.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${H}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return Dp.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${H}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Op.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${H}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${H}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Mp.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${H}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Lp.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${H}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Bp.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${H}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zp.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${H}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return lg.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${H}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${H}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${H}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${H}/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(`/${H}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $p.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${H}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return wm.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${H}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${H}/billing/events`,{method:"POST",body:t,noLog:!0,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${H}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return jp.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${H}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${H}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Gp.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${H}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return Wp.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${H}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return Vp.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${H}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return pg.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${H}/knowledge-base/icons`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3})}catch(r){t.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,r,o){let i=new URLSearchParams;i.set("base",r),i.set("head",o);let a=await this.sendRequest(`/${H}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return Ui.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${H}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return Ui.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${H}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return Ui.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${H}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return Ui.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${H}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return td.record(td.string(),td.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${H}/quarantine`,{method:"GET",noLog:!0});return qp.parse(e)}async quarantineTest(e,t,r){await this.sendRequest(`/${H}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...r??{}},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,r){await this.sendRequest(`/${H}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...r??{}},noLog:!0,retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${H}/limbar/android`,{method:"POST",noLog:!0,retries:3,body:e,requestTimeoutMs:6e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Kp.parse(t)}async getAndroidAssetUrls({channel:e,tag:t,md5:r}){let o={channel:e,tag:t,md5:r},i=await this.sendRequest(`/${H}/limbar/android/upload-url`,{method:"POST",noLog:!0,retries:3,body:o,requestTimeoutMs:15e3});return Yp.parse(i)}};import{randomUUID as kh}from"crypto";var ws=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??kh(),properties:Sc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??kh(),properties:Sc({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var Go=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 aR,en as sR}from"@faker-js/faker";var Wo="v1",ur=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 aR({locale:sR}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Wo}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof sn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof sn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as lR}from"zod";var Vo=class extends Rt{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${H}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Am.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${H}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Vi,...e},signal:t.abortSignal});return Rm.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${H}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return lR.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${H}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Ip.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${H}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return Rc.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${H}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return xp.parse(o)}async getVisualAssertionResult(e,t){let r={...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(`/${H}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return Rc.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${H}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Ap.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${H}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${H}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ec.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${H}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Pp.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${H}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return Ql.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${H}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return nc.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${H}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return _m.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${H}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return em.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${H}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return nm.parse(r)}async getFailureRecoveryPlan(e,t){let r=await this.sendRequest(`/${H}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return tm.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${H}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Du.parse(r)}};var qo=class extends Rt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${H}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Fu.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function _h(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ts=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await _h(r,"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}};function Ko({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new Sa:new nd(n,e,t,r)}var nd=class{constructor(e,t,{gitMainBranch:r,gitBranchName:o,gitProtectedBranches:i,gitCommitTimestamp:a,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:l},c){this.orgId=e;this.client=t;this.cacheHeaders={},r&&(this.cacheHeaders[Tp]=r),o&&(this.cacheHeaders[Ep]=o),a&&(this.cacheHeaders[vp]=a.toISOString()),s&&(this.cacheHeaders[Cp]=s),l&&(this.cacheHeaders[Rp]=l.toISOString()),c?this.writeCaches=!0:o?this.writeCaches=!i.includes(o):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:r,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,steps:t,schemaVersion:e.schemaVersion},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[t,r,o])s&&_o({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await Be({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import BP from"path";import{Server as _I}from"socket.io";var cR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async()=>{e.info({sessionId:r},"Cancel event received");let o=t.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},Dh={event:"cancel",createHandler:cR};var dR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message})}}},Fh={event:"fetchA11yTree",createHandler:dR};var uR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.html();i({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message})}}},Uh={event:"fetchDom",createHandler:uR};var mR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),t.removeSession(r,e)}},Bh={event:"disconnect",createHandler:mR};function Cn(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=pR(t);gR(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await hR(i,e,r,o)}catch(a){n.logger.error({result:n.result,err:a},"Error hoisting scalar result metadata")}})())}function pR(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function gR(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function hR(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import qi from"os";import fR from"v8";var Hh,Rn,SR=qi.platform(),yR=qi.cpus().map(n=>({model:n.model,speed:n.speed}));function zh(n){let e=()=>{try{let t=!1,r=bR(),o=wR();r.freeMemory<1e6&&(t=!0);let i=fR.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:yR,platform:SR}}function bR(){let n=qi.totalmem(),e=qi.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function wR(){let n=qi.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)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,!Rn)return Rn=t,null;let r={user:t.user-Rn.user,nice:t.nice-Rn.nice,sys:t.sys-Rn.sys,idle:t.idle-Rn.idle,irq:t.irq-Rn.irq,total:t.total-Rn.total};return Hh={measurementTime:e,intervalMs:e-Rn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},Rn=t,Hh}import{randomUUID as PR}from"crypto";import{faker as TR}from"@faker-js/faker";import ER from"assert";import vR from"axios";import*as CR from"child_process";import RR from"moment";import*as AR from"otpauth";import xR from"pg";async function $h(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Wa(r,e);t.push(...o)}),t}var IR=Object.getPrototypeOf(async function(){}).constructor;async function jh(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let u;r.includes("createAppAuth")&&(u=(await import("@octokit/auth-app")).createAppAuth);let m=async()=>await Promise.resolve(new IR("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(vR,RR,i.fakerInstance??TR,ER,xR,d,u,AR,CR,$h,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),g=!0,p,h;try{p=await B(m(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error({err:f,env:o,evalCode:r},`[${n}] Error executing code: ${f}`),g=!1,f instanceof dr?h=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:h=f instanceof Error?f.message:`${f}`}return{result:p,variableUpdates:a,persistentVariableUpdates:l,success:g,error:h}}async function Gh({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=rr}){let s=PR(),l=await jh(s,{code:n,options:{fragment:e,timeoutMs:a},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as LR,randomUUID as OR}from"crypto";import MR from"fetch-retry";var NR=MR(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Wh=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Vh=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function qh({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=rr,retries:i=2,signal:a,logger:s}){if(!Wh)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Vh)throw new Error("Missing lambda auth secret.");let u=LR("sha256",Vh).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let g={id:OR(),orgId:n,momenticLambdaAuthHash:u,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await B(NR(Wh,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(p){c=p}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let m;try{m=Wm.parse(await l.json())}catch(g){throw new Error(`Code evaluation server returned invalid response: ${g}`)}if(m.error)throw new Error(`Code evaluation error: ${m.error}`);return m}async function Zr(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await qh(n);else if(n.localTools)e=await Gh({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
37
+ `)){let o=r.indexOf("=");if(o===-1)continue;let i=r.slice(0,o),a=r.slice(o+1).trim();t[i]=a}return t}async function zC(n,e,t){try{let o=t["github.user"]||void 0;if(o)return o}catch{}let r;try{if(e?.startsWith("http://")||e?.startsWith("https://"))r=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(r=e.slice(o+1,i))}}catch{}if(r=r?.toLowerCase(),!!r){try{if(e?.startsWith("git@")&&r?.includes("github")){let{stdout:o,stderr:i}=await Mh("ssh",["-T","-o","BatchMode=yes",`git@${r}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=r&&r!=="github.com"?["api","--hostname",r,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await Mh("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function $C(n,e,t){let r=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(r)return zC(n,e,t);if(o)return}catch{}}function ys(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function Ae(n,e){try{return(await e).trim()}catch(t){n.error({err:t},"Failed to run git command");return}}function jC(){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 GC(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:t,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function WC(n){let[e,t,r]=await Promise.all([Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function VC(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?ys(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function qC(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?ys(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,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 KC(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?ys(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function YC(n,e){let[t,r,o,i,a,s,l,c,d]=await Promise.all([Ae(n,Re.revparse(["HEAD"])),Ae(n,Re.revparse(["--short","HEAD"])),Ae(n,Re.revparse(["--abbrev-ref","HEAD"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"])),e?Ae(n,Re.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),HC(n)]),u=c?await Ae(n,Re.show(["--no-patch","--format=%ci",c])):void 0,m=i?.includes("github.com"),g=i?.includes("gitlab.com"),p=i?ys(i):void 0,h=d["user.email"]||void 0,f=d["user.name"]||void 0,S=d["user.username"]||void 0,b=await $C(n,i,d)??S??void 0;return n.debug({userUsername:b,gitLocalUserLogin:S,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:t,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:l,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:u?new Date(u):void 0,githubRepository:m?p:void 0,gitlabProjectPath:g?p:void 0,pipelineId:void 0}}async function XC(){let n=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:n?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:n?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function JC(n){let e=n.config.gitProtectedBranches??[];return n.config.gitMainBranch&&e.push(n.config.gitMainBranch),{gitMainBranch:n.config.gitMainBranch,gitProtectedBranches:e}}async function Zc(n,e){let t=jC();if(!t)return YC(n,e);switch(t){case"GithubActions":return GC(n);case"GitlabCI":return WC(n);case"CircleCI":return VC(n);case"Buildkite":return qC(n);case"AzureDevOps":return KC(n);case"GCPCloudBuild":return XC()}}async function QC(n,e,t,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGitlab(t,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let i=await e.getCommitFromGitlab(t,r.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}return o}async function ZC(n,e,t,r,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGithub(t,r,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName){let a=await e.getCommitFromGithub(t,r,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}return i}async function eR(n,e,t){try{if(t.githubRepository){let[r,o]=t.githubRepository.split("/");return await ZC(n,e,r,o,t)}else if(t.gitlabProjectPath)return await QC(n,e,t.gitlabProjectPath,t)}catch(r){n.warn({err:r},"Failed to get remote git metadata")}return t}async function cr(n,e,t){let r=await JC(t),o=await Zc(n,r.gitMainBranch),i={...r,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===r.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await eR(n,e,i);return{...r,...o,...a}}import ZV from"yaml";import UP from"http";import{z as td}from"zod";var H="v1",Vi="2.12.1";var dr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Nh=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function B(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{if(e.signal){let{signal:u}=e;if(u.aborted)return c(Nh(u));s=()=>c(Nh(u)),u.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(u){c(u)}else{typeof n.cancel=="function"&&Promise.resolve().then(()=>n.cancel()).catch(()=>{});let u=o instanceof Error?o:new dr(o??`Promise timed out after ${t}ms`);c(u)}};a=i.setTimeout(d,t),Promise.resolve(n).then(u=>l(u)).catch(u=>c(u))}).finally(()=>{i.clearTimeout(a),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var bs=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let r=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(r),!1)}};var tR=9e4,nR=3,rR=1500,oR=15e3,sn=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function iR(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var ed=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Vi&&(e[wp]=Vi),e}async sendRequest(e,t){let{retries:r=nR,requestTimeoutMs:o=tR,initialRetryDelayMs:i=rR,maxRetryDelayMs:a=oR}=t,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(u){if(c=u,u instanceof sn&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError"&&(c=new dr),s===0)throw c;let m=l-s,g=Math.min(i*Math.pow(2,m-1),a);await new Promise(p=>setTimeout(p,g))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),r),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s);let l={...this.getHeaders(),...t.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let u=await iR(c);throw new sn(c.status,u,`Request to ${t.method} ${e} failed with status ${c.status}: ${u}`)}let d;if(c.status===204)d={};else{let u=await c.text();try{d=JSON.parse(u)}catch{d=u}}return this.logger&&!t.noLog&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},Rt=class extends ed{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends Rt{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${H}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Hp.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${H}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return Dp.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${H}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Op.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${H}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${H}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Mp.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${H}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Lp.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${H}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Bp.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${H}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zp.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${H}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return lg.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${H}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${H}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${H}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${H}/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(`/${H}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $p.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${H}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return wm.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${H}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${H}/billing/events`,{method:"POST",body:t,noLog:!0,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${H}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return jp.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${H}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${H}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return Gp.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${H}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return Wp.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${H}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return Vp.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${H}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return pg.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${H}/knowledge-base/icons`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3})}catch(r){t.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,r,o){let i=new URLSearchParams;i.set("base",r),i.set("head",o);let a=await this.sendRequest(`/${H}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return Ui.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${H}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return Ui.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${H}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return Ui.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${H}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return Ui.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${H}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return td.record(td.string(),td.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${H}/quarantine`,{method:"GET",noLog:!0});return qp.parse(e)}async quarantineTest(e,t,r){await this.sendRequest(`/${H}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:t,...r??{}},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t,r){await this.sendRequest(`/${H}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:t,...r??{}},noLog:!0,retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let t=await this.sendRequest(`/${H}/limbar/android`,{method:"POST",noLog:!0,retries:3,body:e,requestTimeoutMs:6e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Kp.parse(t)}async getAndroidAssetUrls({channel:e,tag:t,md5:r}){let o={channel:e,tag:t,md5:r},i=await this.sendRequest(`/${H}/limbar/android/upload-url`,{method:"POST",noLog:!0,retries:3,body:o,requestTimeoutMs:15e3});return Yp.parse(i)}};import{randomUUID as kh}from"crypto";var ws=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??kh(),properties:Sc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??kh(),properties:Sc({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var Go=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 aR,en as sR}from"@faker-js/faker";var Wo="v1",ur=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 aR({locale:sR}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Wo}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof sn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Wo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof sn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Wo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof sn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as lR}from"zod";var Vo=class extends Rt{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${H}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Am.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${H}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Vi,...e},signal:t.abortSignal});return Rm.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${H}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return lR.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${H}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Ip.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${H}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return Rc.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${H}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return xp.parse(o)}async getVisualAssertionResult(e,t){let r={...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(`/${H}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return Rc.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${H}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Ap.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${H}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${H}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ec.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${H}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Pp.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${H}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return Ql.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${H}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return nc.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${H}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return _m.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${H}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return em.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${H}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return nm.parse(r)}async getFailureRecoveryPlan(e,t){let r=await this.sendRequest(`/${H}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return tm.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${H}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Du.parse(r)}};var qo=class extends Rt{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${H}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return Fu.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function _h(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ts=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await _h(r,"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}};function Ko({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new Sa:new nd(n,e,t,r)}var nd=class{constructor(e,t,{gitMainBranch:r,gitBranchName:o,gitProtectedBranches:i,gitCommitTimestamp:a,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:l},c){this.orgId=e;this.client=t;this.cacheHeaders={},r&&(this.cacheHeaders[Tp]=r),o&&(this.cacheHeaders[Ep]=o),a&&(this.cacheHeaders[vp]=a.toISOString()),s&&(this.cacheHeaders[Cp]=s),l&&(this.cacheHeaders[Rp]=l.toISOString()),c?this.writeCaches=!0:o?this.writeCaches=!i.includes(o):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:r,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,steps:t,schemaVersion:e.schemaVersion},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[t,r,o])s&&_o({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await Be({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import BP from"path";import{Server as _I}from"socket.io";var cR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async()=>{e.info({sessionId:r},"Cancel event received");let o=t.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},Dh={event:"cancel",createHandler:cR};var dR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message})}}},Fh={event:"fetchA11yTree",createHandler:dR};var uR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.html();i({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message})}}},Uh={event:"fetchDom",createHandler:uR};var mR=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),t.removeSession(r,e)}},Bh={event:"disconnect",createHandler:mR};function Cn(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=pR(t);gR(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await hR(i,e,r,o)}catch(a){n.logger.error({result:n.result,err:a},"Error hoisting scalar result metadata")}})())}function pR(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertionResult){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function gR(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function hR(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import qi from"os";import fR from"v8";var Hh,Rn,SR=qi.platform(),yR=qi.cpus().map(n=>({model:n.model,speed:n.speed}));function zh(n){let e=()=>{try{let t=!1,r=bR(),o=wR();r.freeMemory<1e6&&(t=!0);let i=fR.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:yR,platform:SR}}function bR(){let n=qi.totalmem(),e=qi.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function wR(){let n=qi.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)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,!Rn)return Rn=t,null;let r={user:t.user-Rn.user,nice:t.nice-Rn.nice,sys:t.sys-Rn.sys,idle:t.idle-Rn.idle,irq:t.irq-Rn.irq,total:t.total-Rn.total};return Hh={measurementTime:e,intervalMs:e-Rn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},Rn=t,Hh}import{randomUUID as PR}from"crypto";import{faker as TR}from"@faker-js/faker";import ER from"assert";import vR from"axios";import*as CR from"child_process";import RR from"moment";import*as AR from"otpauth";import xR from"pg";async function $h(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Wa(r,e);t.push(...o)}),t}var IR=Object.getPrototypeOf(async function(){}).constructor;async function jh(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let u;r.includes("createAppAuth")&&(u=(await import("@octokit/auth-app")).createAppAuth);let m=async()=>await Promise.resolve(new IR("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(vR,RR,i.fakerInstance??TR,ER,xR,d,u,AR,CR,$h,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),g=!0,p,h;try{p=await B(m(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error({err:f,env:o,evalCode:r},`[${n}] Error executing code: ${f}`),g=!1,f instanceof dr?h=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:h=f instanceof Error?f.message:`${f}`}return{result:p,variableUpdates:a,persistentVariableUpdates:l,success:g,error:h}}async function Gh({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=rr}){let s=PR(),l=await jh(s,{code:n,options:{fragment:e,timeoutMs:a},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as LR,randomUUID as OR}from"crypto";import MR from"fetch-retry";var NR=MR(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Wh=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Vh=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function qh({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=rr,retries:i=2,signal:a,logger:s}){if(!Wh)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Vh)throw new Error("Missing lambda auth secret.");let u=LR("sha256",Vh).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let g={id:OR(),orgId:n,momenticLambdaAuthHash:u,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await B(NR(Wh,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(p){c=p}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let m;try{m=Wm.parse(await l.json())}catch(g){throw new Error(`Code evaluation server returned invalid response: ${g}`)}if(m.error)throw new Error(`Code evaluation error: ${m.error}`);return m}async function Zr(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await qh(n);else if(n.localTools)e=await Gh({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
38
38
  ${e.error}
39
39
  Code received:
40
40
  ${n.code}`;throw n.logger.error({err:e.error,code:n.code,env:n.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}import{set as kR}from"lodash-es";async function Bt(n){let{orgId:e,s:t,context:r,logger:o,signal:i,flagStore:a,retries:s=2,timeoutMs:l=rr,allowUndefined:c=!1}=n,d=/{{(.*?)}}/g,u=t.matchAll(d),m=t;for(let g of u){if(g.length<2)continue;let p=g[1].trim(),h;try{h=await Zr({orgId:e,code:p,fragment:!0,context:r,timeoutMs:l,logger:o,retries:s,localTools:n.localTools,signal:i,flagStore:a})}catch(S){throw o.error({err:S,value:t},"Error evaluating template string"),S}if(h===void 0&&!c)throw new A("UserConfigurationError",`Template fragment '${p}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let f=typeof h=="string"?h:`${h}`;f=f.replaceAll(/\$/g,"$$$$"),m=m.replace(g[0],f)}return m}async function Es(n){return Kh(n)}async function Kh({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o=[],replacements:i=[],...a}){for(let s in n){if(e.includes(s))continue;let l=!1;if(t)if(t.includes(s))l=!0;else continue;let c=n[s],d=[...o,s];if(typeof c=="string"&&c.includes("{{")){let u=await Bt({s:c,context:r,...a});if(c===u)continue;i.push({path:d,original:c}),n[s]=u}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await Kh({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:i,allowList:l?void 0:t,...a})}return i}function Yh(n,e){for(let{path:t,original:r}of e)kR(n,t,r)}import _R from"fetch-retry";var C3=process.env.MAILINATOR_API_KEY,R3=_R(global.fetch,{retryOn:function(n,e,t){return n>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(n){return 500}});import{hostname as zR}from"os";async function Xh(n){let{command:e,tracer:t,timeoutMs:r,targetingWrapper:o,disableCache:i,fixtures:a}=n,{logger:s,abortSignal:l}=a;if(e.target&&!Jn(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated&&(e.assertion.condition==="EXISTS"||e.assertion.condition==="VISIBLE"),d=Date.now(),u=0,m,g=500;for(;u<2||Date.now()-d<r;){u++,u>1&&await X(g,l),l?.throwIfAborted();try{let{newTarget:p,elementInteractedDisplayString:h,result:f}=await o({ctx:a.ctx,tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async S=>DR(S.locator,n),options:{...e,disableCache:i,disableGlobalLocatorRedirect:!0,source:kr(e),allowZeroOpacityOverride:!0}});if(m={success:f.success,data:f.data,err:f.err,newTarget:p,elementInteractedDisplayString:h},!f.success){m=f,g=Math.min(g*2,1e4);continue}return m}catch(p){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${p.message}`};if(s.warn({err:p},"Element assertion ended in error, retrying..."),!(p instanceof A)||p.reason!="ActionFailureError")throw p;m={success:!1,err:p}}}if(!m)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return m}async function DR(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,a;switch(r.type){case"ELEMENT_CONTENT":{let l=await n.textContent()??"";if(a={elementTextContent:qe(l,500,!0)},!vs(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,i=new A("AssertionFailureError",`The content ${c} '${r.value}': ${l}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:qe(await n.evaluate(c=>c.cloneNode(!1).outerHTML),500,!0)};let l;try{l=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(c){i=new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${c}`),o=!1;break}if(!vs(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,r.operation==="EXISTS"?i=new A("AssertionFailureError",`The attribute ${r.attr} ${c}`):i=new A("AssertionFailureError",`The attribute ${r.attr} ${c} '${r.value}': ${l}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.evaluate(async(c,d)=>{let u=Date.now();for(;Date.now()-u<d;){await new Promise(g=>setTimeout(g,250));let m=c.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(c).visibility!=="hidden"&&window.getComputedStyle(c).display!=="none")return!0}return!1},yn*1e3);break}case"EDITABLE":{o=await n.isEditable({timeout:yn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:yn*1e3});break}case"FOCUSED":{o=await n.evaluate(c=>c===document.activeElement);break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let l=r.negated?Bc[r.condition]:Hc[r.condition];i=new A("AssertionFailureError",`The element ${l}`)}break}case"ELEMENT_NAME":{let l=await n.evaluate(c=>c.tagName);if(!vs(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,i=new A("AssertionFailureError",`The element tag name ${c} '${r.value}': ${l}`)}break}case"ELEMENT_STYLE":{let l=await n.evaluate((c,d)=>window.getComputedStyle(c).getPropertyValue(d),r.property);if(!vs(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,r.operation==="EXISTS"?i=new A("AssertionFailureError",`The style property ${r.property} ${c}`):i=new A("AssertionFailureError",`The style property ${r.property} ${c} '${r.value}': ${l}`)}break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{success:o,data:a,err:i}}function vs(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}case"EXISTS":{o=n.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 r?!o:o}import{Jimp as FR}from"jimp";async function Ki(n,e){let t=await n.screenshot(e),r=await FR.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as Jh}from"jimp";import rd from"jpeg-js";import UR from"pixelmatch";async function Qh({ctx:n,tracer:e,command:t,disableCache:r,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!Jn(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let l={clearHighlights:!0,hideCaret:!0},c;t.target?.elementDescriptor?c=(await i({ctx:n,tracer:e,command:t,target:t.target,cache:t.cache?.target??t.target?.a11yData,action:async k=>Ki(o,{locator:k.locator,...l}),options:{...t,disableCache:r,disableGlobalLocatorRedirect:!0}})).result:c=await Ki(o,l);let d=await s.prepareGoldenScreenshotForComparison(a,t,c);if((c.height!==d.height||c.width!==d.width)&&a.debug({currHeight:c.height,currWidth:c.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-d.height)>10||Math.abs(c.width-d.width)>10){let W=`${c.width}x${c.height}`,k=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${W}) does not match saved screenshot dimensions (${k}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let u=await Jh.fromBuffer(c.buffer),m={width:c.width,height:c.height},g=await Jh.fromBuffer(d.buffer),p={width:d.width,height:d.height},h,f=m.width*m.height,S=p.width*p.height,b=Math.abs(m.height-p.height),T=Math.abs(m.width-p.width);if(f>S){let W=u.cover({w:p.width,h:p.height});c.buffer=await W.getBuffer("image/jpeg"),h="current",c.width=p.width,c.height=p.height}else if(S>f){let W=g.cover({w:m.width,h:m.height});d.buffer=await W.getBuffer("image/jpeg"),h="saved"}let C={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},R=t.threshold??.1,x=UR(rd.decode(d.buffer).data,rd.decode(c.buffer).data,C.data,c.width,c.height,{threshold:R,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,D=x>R*100,N=`Visual diff of ${x.toFixed(2)}% detected, which is ${D?"over":"under"} the threshold of ${R*100}%.`;if(h&&(N+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${T} pixels.`),D)throw new A("ActionFailureError",N);return{fail:D,thoughts:N,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:rd.encode(C,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var BR=3e4;async function Zh({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??BR/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([g,p])=>g&&p)),a=new URLSearchParams;Object.entries(n.params||{}).filter(([g,p])=>g&&p).forEach(([g,p])=>{a.append(g,p)});let s=a.toString(),l;if(Fo(n.url)&&(l=n.url),t&&Uo(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${n.url}`);e.debug({url:l,searchParams:s,headers:i,body:n.body,method:n.method},"Making HTTP request");let d=await B((async()=>{let g=s?`${l}?${s}`:l;try{return await r(g,{headers:i,method:n.method,body:n.body})}catch(p){throw e.error({err:p},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${p}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let g;try{g=await d.text()}catch(p){g=`Failed to read response body: ${p}`}throw new A("ActionFailureError",`Fetch request failed with status ${d.status}: ${g}`)}let u={};d.headers.forEach((g,p)=>{u[p]=g});let m={status:d.status,headers:u};if(d.headers.get("content-type")?.includes("json"))try{m.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(m.text=await d.text());return m}var HR=5e3;async function Cs({timeout:n=yn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,a=0,s=500;for(;a-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await ef(e),a=Date.now();let c=a-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await X(s,e.signal),s=Math.min(Math.floor(s*1.5),HR);else return i}return i=await ef(e),i}async function ef({assertion:n,browser:e,autoExpandIframes:t}){switch(n.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let l=await e.evaluateFunctionInAllFrames(tf,{value:n.value,negated:!!n.negated,returnHtml:!1});i=n.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(tf,{value:n.value,negated:!!n.negated,returnHtml:!0},"checking page content"));if(!i){let l=n.negated?Jt.CONTAINS:Qt.CONTAINS;a=new A("AssertionFailureError",`The page ${l} '${n.value}'.`),o=s}}catch(s){a=new A("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"})(n.type)}}function tf({value:n,negated:e,returnHtml:t}){let r=document.documentElement.outerHTML,o=r.includes(n)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?r:void 0}}var od=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:a,controller:s}=n.fixtures,l=s.browser,{orgId:c,runId:d}=n.inputs,u=s.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let m,g=!1,p,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await Bt({orgId:c,s:f,context:o,logger:r,localTools:a,signal:u,flagStore:s.flagStore});h={orgId:c,cacheKeys:[S,...Object.entries(t).map(([T,C])=>`${T}:${C}`)]},r.debug({original:f,keyParams:h},"Module cache key params");let b=Date.now();for(;Date.now()-b<rg;){u?.throwIfAborted();let T=await i.getCacheResult(h);if(T){r.debug({cacheResult:T},"Got result from module execution cache"),m=Rs(e,t,"SUCCESS"),m.message="Used cached module result.",m.data=JSON.parse(T),g=!0;break}else r.debug({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let C=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${zR()};runId:${d}`},u);if(C.acquired){p=C.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:p,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:p,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await X(2500+Math.random()*1e4,u)}}try{if(!m)m=await $R(n);else if(e.autoAuth){let f=Va.safeParse(m.data);if(!f.success)throw new A("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,b=e.advanced?.cacheInvalidation;if(b&&b.type==="PAGE_CHECK"){let T={type:"CONTENT",value:b.substring},C=await Cs({timeout:yn,assertion:T,browser:l,logger:r,signal:u,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});C.success?r.debug({invalResult:C},"Cached result still valid after page check, continuing..."):(r.info({invalResult:C},"Invalidating cached result due to page check failure"),S=!0)}if(h&&S)return await i.deleteCacheResult(h),od(n)}}finally{try{p!==void 0&&!g&&m?.status==="SUCCESS"&&await jR({step:e,result:m,browser:s.browser,cacheKeyPrefix:p,logger:r,storage:i})}finally{p!==void 0&&await i.releaseCacheLock(p)}}return m},$R=async n=>{let{step:e,tracer:t}=n.moduleParams,r=Rs(e,n.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await mr(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}}));return r.results=a,r.status=i,r.finishedAt=new Date,Cn({asyncTasks:n.work.asyncTasks,nestedResults:a,result:r,logger:n.fixtures.logger}),r};function Rs(n,e,t){let r={};return Object.entries(e).forEach(([i,a])=>{r[i]=JSON.stringify(a)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function nf({orgId:n,step:e,context:t,logger:r,flagStore:o,codeEvalTools:i,signal:a}){let s={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}s[l]=await Zr({orgId:n,code:c,fragment:!0,context:t,logger:r,localTools:i,signal:a,flagStore:o})}return s}catch(l){throw a?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function jR({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let a=n.cacheConfig?.cacheExpiryMs;(!a||a===cg)&&(a=n.defaultCacheTtl??dg);let s;n.autoAuth?s=JSON.stringify(await t.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:r,ttlMs:a,truncatedCacheResultJson:_g(s)},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:r,ttlMs:a})}async function eo(n,e,t){return GR(n,e,t)}async function GR(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof A?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=Rs(n,{},"FAILED");return l.message=s,l.startedAt=r,l.finishedAt=i,l}return{...ps(n),startedAt:r,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function mr(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as rf}from"crypto";var As=async n=>{let{step:e,tracer:t}=n.presetParams,{logger:r,controller:o,context:i,billingReporter:a}=n.fixtures,{collectDebugData:s}=n.options,{testMetadata:l,suiteMetadata:c}=n.inputs,d=e.command.type,u=r.child({commandType:d,stepId:e.id,commandId:e.command.id}),m=Oi(e.command);n.work.asyncTasks.push(a.reportCreditsUsed(u,d,m,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let g=o.browser.url(),p=new Date,h,f=rf(),S=rf();if(s)try{h=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75});let v=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:u,snapshotId:f,html:v}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(u,f,v))}catch(v){u.debug({err:v},"Failed to take before screenshot, continuing...")}let b,T,C,R=$a();try{let v=await o.executePresetCommand(R,t,e.command,i,l?.advanced.disableAICaching??!1);v.beforeScreenshotOverride&&(h=v.beforeScreenshotOverride),C=v.afterScreenshotOverride;let{proposedStep:x}=WR({work:n.work,step:e,newTargets:v.newTargets,logger:u}),D=new Date,N=o.browser.url();T={beforeUrl:g,afterUrl:N,startedAt:p,finishedAt:D,viewport:o.browser.getViewport(),status:v.fail?"FAILED":"SUCCESS",elementInteracted:v.elementInteracted},b={...e,message:v.thoughts??VR(v.newTargets)??"Successfully executed preset action.",beforeUrl:g,afterUrl:N,finishedAt:D,startedAt:p,status:v.fail?"FAILED":"SUCCESS",data:v.data,results:[T],details:R.details,proposedStep:x},"assertion"in e.command&&(b.message=v.thoughts||"Assertion passed.")}catch(v){u.error({message:v.message,stack:v.stack},`Failed executing preset step ${sr(e.command)}`);let x=o.browser.url(),D=new Date,N=v instanceof Error?v.message:`${v}`;v instanceof A&&v.getLastScreenshotBuffer()&&(C=v.getLastScreenshotBuffer()),T={beforeUrl:g,afterUrl:x,startedAt:p,finishedAt:D,viewport:o.browser.getViewport(),status:v instanceof DOMException&&v.name==="AbortError"?"CANCELLED":"FAILED",message:N},b={...e,startedAt:p,finishedAt:D,beforeUrl:g,afterUrl:x,status:v instanceof DOMException&&v.name==="AbortError"?"CANCELLED":"FAILED",message:N,failureReason:v instanceof A?v.reason:void 0,results:[T],details:R.details}}if(s)try{C||(C=await o.browser.screenshot({retries:1,quality:75}));let v=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:u,snapshotId:S,html:v}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(u,S,v))}catch(v){u.debug({err:v},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return T.beforeSnapshot=f,b.beforeSnapshot=f,T.afterSnapshot=S,b.afterSnapshot=S,h&&(t.attachBeforeScreenshot({logger:u,snapshotId:f,screenshot:h}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(u,f,h))),C&&(t.attachAfterScreenshot({logger:u,snapshotId:S,screenshot:C}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(u,S,C))),b};function WR({step:n,newTargets:e,logger:t}){if(!e?.length)return{proposedStep:void 0};let r=n.command;return xg(r,e,t),{proposedStep:void 0}}function VR(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
@@ -3927,7 +3927,7 @@ ${n}`;default:return n}}var aI=15;async function Bd({command:n,aiPageFiltering:e
3927
3927
  `)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=J(this._project,this._logger),t=await Ct(iP.join(this._project.rootDir,this._testPath),this._logger,e),r=[];return r.push("### Test","```json",JSON.stringify(t,null,2),"```"),r.join(`
3928
3928
  `)}addError(e){this._result.push(e),this._isError=!0}async serialize(){let e=[];this._result.length&&(e.push("### Result"),e.push(this._result.join(`
3929
3929
  `)),e.push(""));let t=await this.snapshot();t&&e.push(t,"");let r=this.testContext();r&&e.push(r,"");let o=await this.test();return o&&e.push(o,""),{content:[{type:"text",text:e.join(`
3930
- `)}],isError:this._isError}}};import{z as sP}from"zod";import{tool as aP}from"ai";var dt=n=>({builder:(t,r)=>aP({description:n.schema.description,inputSchema:n.schema.inputSchema,execute:async o=>{try{await n.handle(t,o,r)}catch(i){r.addError(String(i))}return r.serialize()}}),name:n.schema.name});var lP=dt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:sP.object({})},handle:async(n,e,t)=>{t.setIncludeSnapshot()}}),xy=[lP];import{randomUUID as Qs}from"crypto";import{z as oa}from"zod";import{z as cP}from"zod";var ao={id:!0,cache:!0},so=cP.discriminatedUnion("type",[Cr.omit(ao),Ir.omit(ao),Ar.omit(ao),er.omit(ao),Zn.omit(ao),Rr.omit(ao),xr.omit(ao),kl.omit({id:!0}),Hl.omit({id:!0}),Eo.omit({id:!0}),Bl.omit({id:!0}),zl.omit({id:!0}),_l.omit({id:!0})]);import{createAnthropic as dP}from"@ai-sdk/anthropic";import{randomUUID as uP}from"crypto";var Iy=n=>e=>dP({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${n}`}})(e);var ra=async({step:n,controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,socket:a,testContext:s,orgId:l})=>{let{results:c}=await mP({steps:[n],controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,socket:a,testContext:s,orgId:l});return c[0]},mP=async({steps:n,controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,socket:a,testContext:s,orgId:l})=>{let c={controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,context:s,debugDataStorage:new nn,billingReporter:new nr};return ln({listParams:{containerName:"copilot-steps",steps:n,tracer:new fr({parentStep:null,parentTracer:null,socket:a})},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:l,runId:uP(),steps:n,testMetadata:null},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};var pP=dt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:oa.object({description:oa.string().describe("Description of the element to preview.")})},handle:async({controller:n,logger:e,testContext:t},r,o)=>{o.setIncludeSnapshot();try{let i=await n.locateElement({description:r.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});i.resolution.locator&&await Promise.all([n.browser.scrollIntoViewIfNeeded(i.resolution.locator),n.browser.highlight(i.resolution.locator)]),o.addResult(`Found element matching description: ${i.target.id}`),i.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${i.target.nodeOnlySerializedHtml}`);return}catch(i){o.addError(`Failed to find any element matching description: ${i}`)}}}),gP=dt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:oa.object({assertion:oa.string().describe("Assertion to confirm page state.")})},handle:async(n,e,t)=>{t.setIncludeSnapshot();let{logger:r,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:l,analytics:c,testContext:d}=n,u={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:Qs()},id:Qs()},m=await ra({step:u,controller:i,storage:o,codeEvalTools:a,logger:r,analytics:c,socket:s,orgId:l,testContext:d});if(!m){t.addError("Assertion executed with unknown result.");return}if(m.status==="SUCCESS"){t.addResult(`Assertion is true: ${m.message}`);return}t.addError(`Assertion is false: ${m.message}`)}}),hP=dt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:oa.object({command:so})},handle:async(n,e,t)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:r,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:l,analytics:c,testContext:d}=n;t.setIncludeSnapshot();let u={type:"PRESET_ACTION",command:{...e.command,id:Qs()},id:Qs()},m=await ra({step:u,controller:i,storage:o,codeEvalTools:a,logger:r,analytics:c,socket:s,orgId:l,testContext:d});if(!m){t.addError("Assertion executed with unknown result.");return}if(m.status==="SUCCESS"){t.addResult(`Assertion is true: ${m.message}`);return}t.addError(`Assertion is false: ${m.message}`)}}),Py=[pP,gP,hP];import fP from"path";import{z as Zs}from"zod";var SP=dt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:Zs.object({})},handle:async(n,e,t)=>{t.setIncludeTestContext()}}),yP=dt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:Zs.object({})},handle:async(n,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await n.controller.browser.reset({})}}),bP=dt({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:Zs.object({index:Zs.number()})},handle:async(n,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:r,logger:o,testPath:i,storage:a,controller:s,codeEvalTools:l,socket:c,orgId:d,analytics:u,testContext:m}=n,g=J(r,o),h=(await Ct(fP.join(r.rootDir,i),o,g)).steps[e.index];if(!h){t.addError(`Step at index ${e.index} does not exist.`);return}let f=await ra({step:h,controller:s,storage:a,codeEvalTools:l,logger:o,analytics:u,socket:c,orgId:d,testContext:m});if(!f){t.addError(`Step at index ${e.index} executed with unknown result.`);return}if(f.status==="SUCCESS"){t.addResult(`Step at index ${e.index} executed successfully: ${f.message}`),f.data&&t.addResult(`Data: ${JSON.stringify(f.data,null,2)}`);return}t.addError(`Step at index ${e.index} failed: ${f.message}`)}}),Ly=[SP,yP,bP];import{randomUUID as Sr}from"crypto";import ia from"path";import{z as dn}from"zod";var wP=dt({schema:{name:"test_get",description:"Get test contents.",inputSchema:dn.object({})},handle:async(n,e,t)=>{t.setIncludeTest()}}),TP=dt({schema:{name:"test_insert_step",description:"Insert a step into the test.",inputSchema:dn.object({index:dn.number(),command:so})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Sr()},id:Sr()};l.steps.splice(e.index,0,c);let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),EP=dt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:dn.object({index:dn.number(),command:so})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Sr()},id:Sr()};l.steps.splice(e.index,1,c);let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),vP=dt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:dn.object({index:dn.number()})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s);l.steps.splice(e.index,1);let{stepsToSave:c,moduleUpdates:d}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});d.forEach(u=>{Ut({content:u,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:c,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),CP=dt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:dn.object({startIndex:dn.number(),deleteCount:dn.number(),commands:so.array()})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Sr()},id:Sr()}));l.steps.splice(e.startIndex,e.deleteCount,...c);let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),RP=dt({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:dn.object({commands:so.array()})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Sr()},id:Sr()}));l.steps=c;let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),Oy=[wP,TP,EP,vP,CP,RP];var My=[...xy,...Ly,...Py,...Oy];import{randomUUID as AP}from"node:crypto";import{PostHog as xP}from"posthog-node";var el=class{identify(){return this}child(){return this}track(){return this}async shutdown(){}},tl=class n{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new xP("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new n({...this.bindings,...e},this.options)}track(e,t){if(!Um(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:r,...o}=e;return this.client.capture({distinctId:AP(),event:r,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};var lo=new tl({platform:"local_app"},{flushAt:1,flushInterval:0});var Gn=MP();Gn.get("/",le((n,e)=>{let t=re(),r=J(t,y),o=Object.values(r.tests);e.status(200).json(o)}));Gn.post("/",le(async(n,e)=>{let t;try{t=cp.parse(n.body)}catch(u){e.status(400).json({error:`Invalid request body: ${u}`});return}try{$r(t.name)}catch(u){e.status(400).json({error:u.message});return}let o={id:ky(),name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:se,advanced:{browserType:t.browserType??"Chromium",viewport:t.viewport??Pt},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let i=re(),a=J(i,y);if(Object.values(a.tests).find(u=>u.name===t.name)){e.status(400).send(`A test with the name "${t.name}" already exists. Please use a different name.`);return}let l=co.join(i.rootDir,...t.pathSegments||[]),c=await bh({test:o,name:t.name,folder:l}),d={...o,relativeFilePath:co.relative(i.rootDir,c)};lo.track({type:"test_editor:test_create"}),e.status(201).json(d)}));Gn.get("/:testPath",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r=re(),o=J(r,y),i;try{i=await Ct(co.join(r.rootDir,t),He,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:s}=await Be({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});s.forEach(l=>{Ut({content:l,schemaVersion:se,momenticFiles:o,project:r})}),vt({relativeTestPath:t,steps:a,schemaVersion:se,project:r})}catch(a){He.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));Gn.patch("/:testPath/metadata",le(async(n,e)=>{if(!n.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=lp.parse(n.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:jc(n.params.testPath,t,re()).newRelativeTestPath};e.status(200).json(o)}));Gn.patch("/:testPath",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=sp.parse(n.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let o=re(),i=J(o,y),a;try{a=Ss(t,o)}catch(g){e.status(400).json({error:`Existing test file on disk is invalid: ${g}`});return}let{stepsToSave:s,moduleUpdates:l,cachesToSave:c}=await Be({stepLists:r.stepLists,cacheCreationParams:{testId:a.id,orgId:en()}}),d=new Xe({apiKey:Jd(),baseUrl:Qi(),logger:He}),u=await cr(He,d,o);await Ko({orgId:en(),client:d,gitMetadata:u}).saveStepCacheEntries({logger:He,testId:a.id,entries:c}),l.forEach(g=>{Ut({content:g,schemaVersion:r.schemaVersion,momenticFiles:i,project:o})}),vt({relativeTestPath:t,steps:s,schemaVersion:r.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));Gn.patch("/:testPath/environments",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=gp.parse(n.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}jc(t,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},re()),e.status(201).json({message:"ok"})}));Gn.post("/:testPath/duplicate",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=dp.parse(n.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{$r(r.name)}catch(f){e.status(400).json({error:f.message});return}let o=re(),i=co.join(o.rootDir,t);if(!Ny.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=J(o,y),s;try{s=await Ct(i,He,a)}catch(f){e.status(400).send({error:f.message});return}let l=ky(),c=Xt.parse({...s,name:r.name,id:l}),{stepsToSave:d}=await Be({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:l,orgId:en()}}),u=Un({fileType:we.TEST,...c,beforeSteps:d.beforeSteps??void 0,steps:d.steps,afterSteps:d.afterSteps??void 0}),m=co.dirname(i),g=co.join(m,`${r.name}.${ft.TEST}`),p=NP.stringify(u);Ny.writeFileSync(g,p,"utf-8");let h={relativeFilePath:co.relative(o.rootDir,g)};lo.track({type:"test_editor:test_create"}),e.status(201).json(h)}));Gn.post("/:testPath/chat",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r=Ys.getLatestSession();if(!r){e.status(400).json({error:"No active session."});return}let{messages:o}=n.body,i=Jd(),a=en(),s=Qi(),l=re(),c=He,d=new Xe({apiKey:i,baseUrl:s,logger:c}),u=new ti(d,a),m=new lr(l.config),g=new ur({httpClient:new Rt({baseUrl:d.baseUrl,apiKey:d.apiKey,logger:c}),fakerSeed:l.config.advanced?.fakerConstantSeed?qa:void 0}),p={project:l,apiKey:i,orgId:a,baseUrl:s,logger:c,storage:u,analytics:lo,flagStore:m,codeEvalTools:g,testPath:t,testContext:r.context,controller:r.controller,socket:r.socket},h=My.reduce((b,{name:T,builder:C})=>(b[T]=C(p,new Js(p.controller.browser,p.testContext,p.project,p.logger,p.testPath)),b),{}),f=Iy(i);LP({model:f("claude-opus-4-20250514"),stopWhen:PP(15),maxRetries:2,system:OP`
3930
+ `)}],isError:this._isError}}};import{z as sP}from"zod";import{tool as aP}from"ai";var dt=n=>({builder:(t,r)=>aP({description:n.schema.description,inputSchema:n.schema.inputSchema,execute:async o=>{try{await n.handle(t,o,r)}catch(i){r.addError(String(i))}return r.serialize()}}),name:n.schema.name});var lP=dt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:sP.object({})},handle:async(n,e,t)=>{t.setIncludeSnapshot()}}),xy=[lP];import{randomUUID as Qs}from"crypto";import{z as oa}from"zod";import{z as cP}from"zod";var ao={id:!0,cache:!0},so=cP.discriminatedUnion("type",[Cr.omit(ao),Ir.omit(ao),Ar.omit(ao),er.omit(ao),Zn.omit(ao),Rr.omit(ao),xr.omit(ao),kl.omit({id:!0}),Hl.omit({id:!0}),Eo.omit({id:!0}),Bl.omit({id:!0}),zl.omit({id:!0}),_l.omit({id:!0})]);import{createAnthropic as dP}from"@ai-sdk/anthropic";import{randomUUID as uP}from"crypto";var Iy=n=>e=>dP({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${n}`},apiKey:n})(e);var ra=async({step:n,controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,socket:a,testContext:s,orgId:l})=>{let{results:c}=await mP({steps:[n],controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,socket:a,testContext:s,orgId:l});return c[0]},mP=async({steps:n,controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,socket:a,testContext:s,orgId:l})=>{let c={controller:e,storage:t,codeEvalTools:r,logger:o,analytics:i,context:s,debugDataStorage:new nn,billingReporter:new nr};return ln({listParams:{containerName:"copilot-steps",steps:n,tracer:new fr({parentStep:null,parentTracer:null,socket:a})},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:l,runId:uP(),steps:n,testMetadata:null},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};var pP=dt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:oa.object({description:oa.string().describe("Description of the element to preview.")})},handle:async({controller:n,logger:e,testContext:t},r,o)=>{o.setIncludeSnapshot();try{let i=await n.locateElement({description:r.description,disableCache:!0,skipWait:!0,logger:e,testContext:t});i.resolution.locator&&await Promise.all([n.browser.scrollIntoViewIfNeeded(i.resolution.locator),n.browser.highlight(i.resolution.locator)]),o.addResult(`Found element matching description: ${i.target.id}`),i.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${i.target.nodeOnlySerializedHtml}`);return}catch(i){o.addError(`Failed to find any element matching description: ${i}`)}}}),gP=dt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:oa.object({assertion:oa.string().describe("Assertion to confirm page state.")})},handle:async(n,e,t)=>{t.setIncludeSnapshot();let{logger:r,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:l,analytics:c,testContext:d}=n,u={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:Qs()},id:Qs()},m=await ra({step:u,controller:i,storage:o,codeEvalTools:a,logger:r,analytics:c,socket:s,orgId:l,testContext:d});if(!m){t.addError("Assertion executed with unknown result.");return}if(m.status==="SUCCESS"){t.addResult(`Assertion is true: ${m.message}`);return}t.addError(`Assertion is false: ${m.message}`)}}),hP=dt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:oa.object({command:so})},handle:async(n,e,t)=>{t.setIncludeSnapshot(),t.setIncludeTestContext();let{logger:r,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:l,analytics:c,testContext:d}=n;t.setIncludeSnapshot();let u={type:"PRESET_ACTION",command:{...e.command,id:Qs()},id:Qs()},m=await ra({step:u,controller:i,storage:o,codeEvalTools:a,logger:r,analytics:c,socket:s,orgId:l,testContext:d});if(!m){t.addError("Assertion executed with unknown result.");return}if(m.status==="SUCCESS"){t.addResult(`Assertion is true: ${m.message}`);return}t.addError(`Assertion is false: ${m.message}`)}}),Py=[pP,gP,hP];import fP from"path";import{z as Zs}from"zod";var SP=dt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:Zs.object({})},handle:async(n,e,t)=>{t.setIncludeTestContext()}}),yP=dt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:Zs.object({})},handle:async(n,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot(),await n.controller.browser.reset({})}}),bP=dt({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:Zs.object({index:Zs.number()})},handle:async(n,e,t)=>{t.setIncludeTestContext(),t.setIncludeSnapshot();let{project:r,logger:o,testPath:i,storage:a,controller:s,codeEvalTools:l,socket:c,orgId:d,analytics:u,testContext:m}=n,g=J(r,o),h=(await Ct(fP.join(r.rootDir,i),o,g)).steps[e.index];if(!h){t.addError(`Step at index ${e.index} does not exist.`);return}let f=await ra({step:h,controller:s,storage:a,codeEvalTools:l,logger:o,analytics:u,socket:c,orgId:d,testContext:m});if(!f){t.addError(`Step at index ${e.index} executed with unknown result.`);return}if(f.status==="SUCCESS"){t.addResult(`Step at index ${e.index} executed successfully: ${f.message}`),f.data&&t.addResult(`Data: ${JSON.stringify(f.data,null,2)}`);return}t.addError(`Step at index ${e.index} failed: ${f.message}`)}}),Ly=[SP,yP,bP];import{randomUUID as Sr}from"crypto";import ia from"path";import{z as dn}from"zod";var wP=dt({schema:{name:"test_get",description:"Get test contents.",inputSchema:dn.object({})},handle:async(n,e,t)=>{t.setIncludeTest()}}),TP=dt({schema:{name:"test_insert_step",description:"Insert a step into the test.",inputSchema:dn.object({index:dn.number(),command:so})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Sr()},id:Sr()};l.steps.splice(e.index,0,c);let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),EP=dt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:dn.object({index:dn.number(),command:so})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Sr()},id:Sr()};l.steps.splice(e.index,1,c);let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),vP=dt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:dn.object({index:dn.number()})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s);l.steps.splice(e.index,1);let{stepsToSave:c,moduleUpdates:d}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});d.forEach(u=>{Ut({content:u,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:c,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),CP=dt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:dn.object({startIndex:dn.number(),deleteCount:dn.number(),commands:so.array()})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Sr()},id:Sr()}));l.steps.splice(e.startIndex,e.deleteCount,...c);let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),RP=dt({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:dn.object({commands:so.array()})},handle:async(n,e,t)=>{t.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=n,s=J(r,o),l=await Ct(ia.join(r.rootDir,i),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Sr()},id:Sr()}));l.steps=c;let{stepsToSave:d,moduleUpdates:u}=await Be({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ut({content:m,schemaVersion:se,momenticFiles:s,project:r})}),vt({relativeTestPath:i,steps:d,schemaVersion:se,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),Oy=[wP,TP,EP,vP,CP,RP];var My=[...xy,...Ly,...Py,...Oy];import{randomUUID as AP}from"node:crypto";import{PostHog as xP}from"posthog-node";var el=class{identify(){return this}child(){return this}track(){return this}async shutdown(){}},tl=class n{bindings;client;options;constructor(e,t={}){this.bindings=e,this.options=t,this.client=new xP("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...t})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new n({...this.bindings,...e},this.options)}track(e,t){if(!Um(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:r,...o}=e;return this.client.capture({distinctId:AP(),event:r,timestamp:t?.timestamp,properties:{...this.bindings,...o}}),this}};var lo=new tl({platform:"local_app"},{flushAt:1,flushInterval:0});var Gn=MP();Gn.get("/",le((n,e)=>{let t=re(),r=J(t,y),o=Object.values(r.tests);e.status(200).json(o)}));Gn.post("/",le(async(n,e)=>{let t;try{t=cp.parse(n.body)}catch(u){e.status(400).json({error:`Invalid request body: ${u}`});return}try{$r(t.name)}catch(u){e.status(400).json({error:u.message});return}let o={id:ky(),name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:se,advanced:{browserType:t.browserType??"Chromium",viewport:t.viewport??Pt},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let i=re(),a=J(i,y);if(Object.values(a.tests).find(u=>u.name===t.name)){e.status(400).send(`A test with the name "${t.name}" already exists. Please use a different name.`);return}let l=co.join(i.rootDir,...t.pathSegments||[]),c=await bh({test:o,name:t.name,folder:l}),d={...o,relativeFilePath:co.relative(i.rootDir,c)};lo.track({type:"test_editor:test_create"}),e.status(201).json(d)}));Gn.get("/:testPath",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r=re(),o=J(r,y),i;try{i=await Ct(co.join(r.rootDir,t),He,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:s}=await Be({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});s.forEach(l=>{Ut({content:l,schemaVersion:se,momenticFiles:o,project:r})}),vt({relativeTestPath:t,steps:a,schemaVersion:se,project:r})}catch(a){He.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));Gn.patch("/:testPath/metadata",le(async(n,e)=>{if(!n.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=lp.parse(n.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:jc(n.params.testPath,t,re()).newRelativeTestPath};e.status(200).json(o)}));Gn.patch("/:testPath",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=sp.parse(n.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let o=re(),i=J(o,y),a;try{a=Ss(t,o)}catch(g){e.status(400).json({error:`Existing test file on disk is invalid: ${g}`});return}let{stepsToSave:s,moduleUpdates:l,cachesToSave:c}=await Be({stepLists:r.stepLists,cacheCreationParams:{testId:a.id,orgId:en()}}),d=new Xe({apiKey:Jd(),baseUrl:Qi(),logger:He}),u=await cr(He,d,o);await Ko({orgId:en(),client:d,gitMetadata:u}).saveStepCacheEntries({logger:He,testId:a.id,entries:c}),l.forEach(g=>{Ut({content:g,schemaVersion:r.schemaVersion,momenticFiles:i,project:o})}),vt({relativeTestPath:t,steps:s,schemaVersion:r.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));Gn.patch("/:testPath/environments",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=gp.parse(n.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}jc(t,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},re()),e.status(201).json({message:"ok"})}));Gn.post("/:testPath/duplicate",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=dp.parse(n.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{$r(r.name)}catch(f){e.status(400).json({error:f.message});return}let o=re(),i=co.join(o.rootDir,t);if(!Ny.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=J(o,y),s;try{s=await Ct(i,He,a)}catch(f){e.status(400).send({error:f.message});return}let l=ky(),c=Xt.parse({...s,name:r.name,id:l}),{stepsToSave:d}=await Be({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:l,orgId:en()}}),u=Un({fileType:we.TEST,...c,beforeSteps:d.beforeSteps??void 0,steps:d.steps,afterSteps:d.afterSteps??void 0}),m=co.dirname(i),g=co.join(m,`${r.name}.${ft.TEST}`),p=NP.stringify(u);Ny.writeFileSync(g,p,"utf-8");let h={relativeFilePath:co.relative(o.rootDir,g)};lo.track({type:"test_editor:test_create"}),e.status(201).json(h)}));Gn.post("/:testPath/chat",le(async(n,e)=>{let{testPath:t}=n.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let r=Ys.getLatestSession();if(!r){e.status(400).json({error:"No active session."});return}let{messages:o}=n.body,i=Jd(),a=en(),s=Qi(),l=re(),c=He,d=new Xe({apiKey:i,baseUrl:s,logger:c}),u=new ti(d,a),m=new lr(l.config),g=new ur({httpClient:new Rt({baseUrl:d.baseUrl,apiKey:d.apiKey,logger:c}),fakerSeed:l.config.advanced?.fakerConstantSeed?qa:void 0}),p={project:l,apiKey:i,orgId:a,baseUrl:s,logger:c,storage:u,analytics:lo,flagStore:m,codeEvalTools:g,testPath:t,testContext:r.context,controller:r.controller,socket:r.socket},h=My.reduce((b,{name:T,builder:C})=>(b[T]=C(p,new Js(p.controller.browser,p.testContext,p.project,p.logger,p.testPath)),b),{}),f=Iy(i);LP({model:f("claude-opus-4-20250514"),stopWhen:PP(15),maxRetries:2,system:OP`
3931
3931
  <core-identity>
3932
3932
  You are the Momentic Copilot. You are an experienced SDET who is building and editing a Momentic browser E2E test. Instead of CSS selectors, Momentic uses natural language descriptions to identify elements. Your responses must be specific, accurate, and concise.
3933
3933
  </core-identity>
@@ -3982,7 +3982,7 @@ ${a.stack}`),l.status(500).send("Internal Server Error")}),n){let a=Fy.static(n,
3982
3982
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
3983
3983
  `)}import mO from"events";import xl from"fs";import pO from"open";import{cpus as cw}from"os";import Al from"path";import{fileURLToPath as gO}from"url";import lL from"diff-lines";import{gt as cL}from"semver";import{execSync as zP}from"child_process";import{platform as $P}from"os";function eu(){return zy()?(y.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),y.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
3984
3984
  `),2):(y.dimmed("Setting device pixel ratio to 1."),y.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
3985
- l.`),1)}function zy(){return $P()==="darwin"&&zP("system_profiler SPDisplaysDataType").toString().includes("Retina")}function tu(n){zy()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import jP from"@actions/exec";import GP from"@actions/io";import WP from"quote";import VP from"string-argv";async function $y(n,e=!0){let t=VP(n),r=await GP.which(t[0],!0),o=t.slice(1),i=jP.exec(WP(r),o,{delay:100});if(e)return i}import{existsSync as qP,statSync as KP}from"fs";var sa=!!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;function jy(n){try{return qP(n)&&KP(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import YP from"csv-parser";import{createReadStream as XP}from"fs";function nu(n){return new Promise((e,t)=>{let r=[];XP(n).pipe(YP()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import nl from"semver";import{z as rl}from"zod";var On="2.12.0",JP="https://registry.npmjs.org/momentic",QP=rl.object({versions:rl.record(rl.string(),rl.unknown()).optional()});async function Gy(n){try{await ZP(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function ZP(n){if(!On){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await B(fetch(JP),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=QP.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))nl.valid(r)&&(!t||nl.gt(r,t))&&nl.gt(r,On)&&nl.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${On} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{confirm as tL,input as nL}from"@inquirer/prompts";import{existsSync as rL,mkdirSync as oL,statSync as iL}from"fs";import{dirname as aL}from"path";import{hostname as eL}from"os";var K=Vs({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:eL(),disableConsoleLogs:!0}).child({version:"2.12.0"});var sL=!1,Vy=(()=>{try{return iL("/.dockerenv"),!0}catch{return!1}})();async function yt(n,e){return sa||sL||Vy?!0:(K.flush(),await new Promise(r=>setTimeout(r,500)),await tL({message:n}))}async function ru(n){let e=aL(n);return jy(e)?rL(n)?yt(`File '${Wy(n)}' already exists. Overwrite existing content?`,!0):!0:await yt(`Directory '${Wy(e)}' doesn't exist. Create it now?`,!0)?(oL(e,{recursive:!0}),!0):!1}function Wy(n){return n.replace(/(\s+)/g,"\\$1")}async function qy(n,e){return sa||Vy?e:(await nL({message:n,default:e})).trim()||e}async function Ky({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){cL(e.schemaVersion,se)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Ag(e.steps).forEach(p=>{t.modules[p]||(y.error(`The test patch contains a module with id ${p} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await yt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await yt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=Jr(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let d,u;if(e.schemaVersion!==se){let{steps:p,newVersion:h}=await Bi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=h,u=De.array().parse(p)}else u=De.array().parse(e.steps);let{stepsToSave:m}=await Be({stepLists:{steps:u}});m.beforeSteps=l.beforeSteps??void 0,m.afterSteps=l.afterSteps??void 0;let g=lL(JSON.stringify(c,void 0,2),JSON.stringify(m,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(g),y.dimmed("=".repeat(30)),y.dimmed(""),d&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await yt("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),vt({relativeTestPath:n.relativePath,steps:m,schemaVersion:d??e.schemaVersion,project:t.project}),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as zt}from"crypto";import{z as fb}from"zod";var st=" ".repeat(6);import hb from"chalk";import{Argument as uo,InvalidArgumentError as la,Option as ve}from"@commander-js/extra-typings";import{validateHeaderValue as dL}from"http";import{z as Xy}from"zod";var Yy=58888,ol=30*60*1e3;function Wn(n){let e=parseInt(n,10);if(isNaN(e))throw new la("Not a number.");return e}function il(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);dL(o,i),e[o]=i}return e}var un=new ve("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new la("API key is required.");return n}).makeOptionMandatory(),mn=new ve("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(n=>{try{return Xy.string().url().parse(n),n}catch{throw new la("Not a valid URL.")}}),yr=new ve("-y, --yes","Skip all confirmation prompts.").env("CI"),ou=new ve("-w, --wait","Wait for tests to finish running before exiting."),iu=new ve("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${ol/1e3} seconds.`).default(ol/1e3).implies({wait:!0}).argParser(Wn),al=new ve("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),Jy=new ve("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(za)),Qy=new ve("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),au=new ve("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zy=new ve("--upload-results","Upload test results to Momentic Cloud.").default(!1),su=new ve("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),lu=new ve("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),cu=new ve("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(Wn),eb=new ve("--port <port>",`Port to run the app on. Defaults to ${Yy}.`).default(Yy).argParser(Wn),du=new ve("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),sl=new ve("--env <env>","Name of the environment to use when running tests."),ll=new ve("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(n=>{try{return Xy.string().url().parse(n),n}catch{throw new la("Not a valid URL.")}}),tb=new ve("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=Wn(n);if(e<1)throw new la("Shard index must be greater than 0.");return e}),nb=new ve("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Wn),Ht=new ve("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),ri=new ve("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),rb=new ve("--fix","Attempt to fix any issues found."),uu=new ve("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),mu=new ve("--disable-cache","Disable caching of test results."),ob=new ve("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),ib=new ve("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),ab=new ve("--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}),sb=new ve("--ignore-failed-setup","Set the status of tests that failed during setup to 'cancelled' instead of failed, in order to not fail the entire pipeline."),lb=new uo("<tests...>","One or more test paths to queue on Momentic Cloud."),cb=new uo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),pu=new uo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),db=new uo("<suites...>","One or more suite paths that exist on Momentic Cloud."),ub=new uo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),mb=new uo("<results>","Path to the results archive.").argRequired(),gu=new ve("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),hu=new uo("<test>","Name of the test to quarantine.").argOptional();async function fu(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(y.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return y.debug("Got auth info from API"),r}import{Console as pb}from"console";import{format as ca}from"util";var Su=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},cl=class n extends pb{_buffer=[];_groupDepth=0;Console=pb;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new Su(void 0,n.write).stack;if(!i)return e;let a=i.split(`
3985
+ l.`),1)}function zy(){return $P()==="darwin"&&zP("system_profiler SPDisplaysDataType").toString().includes("Retina")}function tu(n){zy()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import jP from"@actions/exec";import GP from"@actions/io";import WP from"quote";import VP from"string-argv";async function $y(n,e=!0){let t=VP(n),r=await GP.which(t[0],!0),o=t.slice(1),i=jP.exec(WP(r),o,{delay:100});if(e)return i}import{existsSync as qP,statSync as KP}from"fs";var sa=!!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;function jy(n){try{return qP(n)&&KP(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import YP from"csv-parser";import{createReadStream as XP}from"fs";function nu(n){return new Promise((e,t)=>{let r=[];XP(n).pipe(YP()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import nl from"semver";import{z as rl}from"zod";var On="2.12.1",JP="https://registry.npmjs.org/momentic",QP=rl.object({versions:rl.record(rl.string(),rl.unknown()).optional()});async function Gy(n){try{await ZP(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function ZP(n){if(!On){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await B(fetch(JP),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=QP.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))nl.valid(r)&&(!t||nl.gt(r,t))&&nl.gt(r,On)&&nl.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${On} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{confirm as tL,input as nL}from"@inquirer/prompts";import{existsSync as rL,mkdirSync as oL,statSync as iL}from"fs";import{dirname as aL}from"path";import{hostname as eL}from"os";var K=Vs({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:eL(),disableConsoleLogs:!0}).child({version:"2.12.1"});var sL=!1,Vy=(()=>{try{return iL("/.dockerenv"),!0}catch{return!1}})();async function yt(n,e){return sa||sL||Vy?!0:(K.flush(),await new Promise(r=>setTimeout(r,500)),await tL({message:n}))}async function ru(n){let e=aL(n);return jy(e)?rL(n)?yt(`File '${Wy(n)}' already exists. Overwrite existing content?`,!0):!0:await yt(`Directory '${Wy(e)}' doesn't exist. Create it now?`,!0)?(oL(e,{recursive:!0}),!0):!1}function Wy(n){return n.replace(/(\s+)/g,"\\$1")}async function qy(n,e){return sa||Vy?e:(await nL({message:n,default:e})).trim()||e}async function Ky({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){cL(e.schemaVersion,se)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Ag(e.steps).forEach(p=>{t.modules[p]||(y.error(`The test patch contains a module with id ${p} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await yt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await yt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=Jr(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let d,u;if(e.schemaVersion!==se){let{steps:p,newVersion:h}=await Bi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=h,u=De.array().parse(p)}else u=De.array().parse(e.steps);let{stepsToSave:m}=await Be({stepLists:{steps:u}});m.beforeSteps=l.beforeSteps??void 0,m.afterSteps=l.afterSteps??void 0;let g=lL(JSON.stringify(c,void 0,2),JSON.stringify(m,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(g),y.dimmed("=".repeat(30)),y.dimmed(""),d&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await yt("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),vt({relativeTestPath:n.relativePath,steps:m,schemaVersion:d??e.schemaVersion,project:t.project}),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as zt}from"crypto";import{z as fb}from"zod";var st=" ".repeat(6);import hb from"chalk";import{Argument as uo,InvalidArgumentError as la,Option as ve}from"@commander-js/extra-typings";import{validateHeaderValue as dL}from"http";import{z as Xy}from"zod";var Yy=58888,ol=30*60*1e3;function Wn(n){let e=parseInt(n,10);if(isNaN(e))throw new la("Not a number.");return e}function il(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);dL(o,i),e[o]=i}return e}var un=new ve("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new la("API key is required.");return n}).makeOptionMandatory(),mn=new ve("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(n=>{try{return Xy.string().url().parse(n),n}catch{throw new la("Not a valid URL.")}}),yr=new ve("-y, --yes","Skip all confirmation prompts.").env("CI"),ou=new ve("-w, --wait","Wait for tests to finish running before exiting."),iu=new ve("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${ol/1e3} seconds.`).default(ol/1e3).implies({wait:!0}).argParser(Wn),al=new ve("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),Jy=new ve("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(za)),Qy=new ve("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),au=new ve("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zy=new ve("--upload-results","Upload test results to Momentic Cloud.").default(!1),su=new ve("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),lu=new ve("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),cu=new ve("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(Wn),eb=new ve("--port <port>",`Port to run the app on. Defaults to ${Yy}.`).default(Yy).argParser(Wn),du=new ve("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),sl=new ve("--env <env>","Name of the environment to use when running tests."),ll=new ve("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(n=>{try{return Xy.string().url().parse(n),n}catch{throw new la("Not a valid URL.")}}),tb=new ve("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=Wn(n);if(e<1)throw new la("Shard index must be greater than 0.");return e}),nb=new ve("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Wn),Ht=new ve("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),ri=new ve("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),rb=new ve("--fix","Attempt to fix any issues found."),uu=new ve("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),mu=new ve("--disable-cache","Disable caching of test results."),ob=new ve("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),ib=new ve("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),ab=new ve("--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}),sb=new ve("--ignore-failed-setup","Set the status of tests that failed during setup to 'cancelled' instead of failed, in order to not fail the entire pipeline."),lb=new uo("<tests...>","One or more test paths to queue on Momentic Cloud."),cb=new uo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),pu=new uo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),db=new uo("<suites...>","One or more suite paths that exist on Momentic Cloud."),ub=new uo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),mb=new uo("<results>","Path to the results archive.").argRequired(),gu=new ve("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),hu=new uo("<test>","Name of the test to quarantine.").argOptional();async function fu(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(y.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return y.debug("Got auth info from API"),r}import{Console as pb}from"console";import{format as ca}from"util";var Su=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},cl=class n extends pb{_buffer=[];_groupDepth=0;Console=pb;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new Su(void 0,n.write).stack;if(!i)return e;let a=i.split(`
3986
3986
  `).slice(o).filter(Boolean).join(`
3987
3987
  `);return e.push({message:r,origin:a,type:t}),e}_log(e,t){n.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",ca(e,...t))}error(e,...t){this._log("error",ca(e,...t))}info(e,...t){this._log("info",ca(e,...t))}log(e,...t){this._log("log",ca(e,...t))}warn(e,...t){this._log("warn",ca(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function gb(n){let e=globalThis.console,t=new cl;globalThis.console=t;try{n()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
3988
3988
  `);process.stderr.write(`${o}
@@ -4000,4 +4000,4 @@ ${n.map(m=>`${st}- ${m}`).join(`
4000
4000
  `),y.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),xl.existsSync(Ho)&&(y.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:n.name??await qy("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Wc};zo(t,Ho),y.success(`Initialized Momentic project file at ${Al.resolve(Ho)}`)});bt.command("app").addOption(un).addOption(mn).addOption(yr).addOption(cu).addOption(eb).addOption(Ht).addOption(uu).addOption(mu).action(async n=>{let{apiKey:e,port:t,yes:r,server:o,pixelRatio:i,disableCache:a,saveCache:s}=n,l=it({configFilePath:n.config,nameFilter:void 0}),{errors:c}=await ml({project:l,fix:!1});c>0&&(y.error(`Found ${c} errors`),y.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let d=new Xe({baseUrl:o,apiKey:e,logger:K});await fu({client:d,skipPrompts:r});let u=gO(import.meta.url),m=Al.dirname(u),g=Al.resolve(m,"..","static"),p=Al.resolve(m,"..","assets"),h=i??eu();tu(h),await By({momenticServerUrl:o,apiKey:e,serverPort:t,appPort:t,staticDir:g,assetsDir:p,devicePixelRatio:h,version:On,noCache:a,alwaysSaveCache:s,initialProject:l});let f=`http://localhost:${t}`;await pO(f)});var uw=bt.command("queue").description("Queue tests or suites to run on Momentic Cloud");uw.command("suites").description("Run one or more suites on Momentic Cloud").addOption(un).addOption(mn).addOption(ou).addOption(iu).addOption(yr).addArgument(db).addOption(ll).addOption(sl).addOption(al).action(async(n,e)=>{let{apiKey:t,server:r,wait:o,waitTimeout:i,env:a,urlOverride:s}=e,l=il(e.customHeaders),c=new Xe({baseUrl:r,apiKey:t,logger:K});(!n||!Array.isArray(n)||!n.length)&&(y.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await Db({client:c,orgId:d,wait:o,suitePaths:n,waitTimeout:i,env:a,urlOverride:s,customHeaders:l})});uw.command("tests").description("Run one or more tests on Momentic Cloud").addOption(un).addOption(mn).addOption(yr).addOption(al).addOption(du).addOption(ll).addOption(sl).addOption(new kt("--all","Run all tests.").default(!1)).addOption(ou).addOption(iu).addArgument(lb).action(async(n,e)=>{let{all:t,apiKey:r,env:o,server:i,inputCsv:a,urlOverride:s,wait:l,waitTimeout:c,yes:d}=e,u=il(e.customHeaders);for(let h of n)(h.endsWith(".yaml")||xl.existsSync(h))&&y.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let m=new Xe({baseUrl:i,apiKey:r,logger:K}),{orgId:g}=await m.getAuthInfo(),p;a&&(p=await nu(a)),await Fb({client:m,orgId:g,tests:n,all:t,customHeaders:u,env:o,urlOverride:s,wait:l,waitTimeout:c,testInputMatrix:p,yes:d}),process.exit(0)});var fO=bt.command("list").description("List test paths");fO.addOption(Ht).addOption(ri).addOption(su).addOption(lu).addOption(new kt("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(pu).action(async(n,e)=>{let t=it({configFilePath:e.config,nameFilter:e.filter}),r=J(t,y),o=await wl({tests:n,momenticFiles:r,yes:!0,project:t,include:e.include,exclude:e.exclude,labels:e.labels,logger:new Di(2,{})});y.info(o.map(i=>i.relativeFilePath).join(`
4001
4001
  `)),process.exit(0)});var SO=bt.command("run").alias("test").description("Run tests on the local machine");SO.addOption(un).addOption(mn).addOption(Ht).addOption(ri).addOption(yr).addOption(al).addOption(du).addOption(uu).addOption(mu).addOption(sb).addOption(ob).addOption(ib).addOption(ab).addOption(sl).addOption(ll).addOption(cu).addOption(new kt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new kt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new kt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(Wn)).addOption(new kt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(Wn)).addOption(new kt("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.").argParser(Wn)).addOption(new kt("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new kt("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(Jy).addOption(Qy).addOption(au).addOption(Zy).addOption(nb).addOption(tb).addOption(su).addOption(lu).addArgument(pu).action(async(n,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let t=il(e.customHeaders),r=it({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??r.config.parallel??1;cw().length<o*2&&y.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${cw().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),y.debug({projectName:r.config.name},"Identified project config");let{errors:i}=await ml({project:r,fix:!1});i>0&&(y.error(`Found ${i} errors`),y.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let a=new Xe({baseUrl:e.server,apiKey:e.apiKey,logger:K});y.debug("Checking API key and dependencies");let{orgId:s,userId:l}=await fu({client:a,skipPrompts:e.yes});y.debug("API key check and browser installation complete");let c=new ws(a),d=new nn,u=e.outputDir??r.config.outputDir,m=e.reporterDir??r.config.reporterDir,g=uO(),p=K.child({runGroupId:g,orgId:s,userId:l,cliVersion:On,trigger:"CLI"}),h=await cr(K,a,r);p.info(h,"Got local git metadata");let f=new lr(r.config),S;e.inputCsv&&(S=await nu(e.inputCsv));let b=e.pixelRatio??eu();tu(b);try{(await iw({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:b,tests:n,project:r,client:a,debugDataStorage:d,billingReporter:c,flagStore:f,outputDir:u,uploadResults:e.uploadResults,reporterDir:m,customHeaders:t,envName:e.env,orgId:s,testInputMatrix:S,logger:p,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:h,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:g})).failed>0?process.exit(1):process.exit(0)}catch(T){y.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),y.error(T),process.exit(1)}});var yO=bt.command("apply").description("Apply an operation to local resources");yO.command("patch").addOption(un).addOption(mn).addOption(Ht).addOption(ri).addOption(yr).addOption(new kt("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new kt("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async n=>{let{apiKey:e,server:t,config:r,yes:o}=n,i=it({configFilePath:r}),a=K,s=new Xe({baseUrl:t,apiKey:e,logger:a}),l=J(i,y),c=l.tests[n.to]??Object.values(l.tests).find(u=>Ce(u.name)===n.to.trim());c||(y.error(`No test matching '${n.to}' could be found in the current project.`),process.exit(1));let d=await s.fetchTestFragment(n.from);await Ky({client:s,test:c,fragment:d,yes:o,entities:l,logger:K}),process.exit(0)});var mw=bt.command("results").description("Merge and upload test results.");mw.command("merge").description("Merge test results files.").addOption(au).addArgument(ub).action(async(n,e)=>{let{outputDir:t}=e;t||(y.error("Output directory is required."),process.exit(1)),xl.existsSync(n)||(y.warn("Results path does not exist, skipping merge."),process.exit(0)),xl.existsSync(t)&&y.warn(`Output directory ${t} already exists, removing before merging...`),lw(K,t,n)});mw.command("upload").description("Upload test results to Momentic cloud.").addOption(un).addOption(mn).addArgument(mb).action(async(n,e)=>{let{apiKey:t,server:r}=e,o=K,i=new Xe({baseUrl:r,apiKey:t,logger:o});await Rl({consoleLogger:y,resultsPath:n,client:i}),process.exit(0)});var pw=bt.command("quarantine").description("Manage test quarantines");pw.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(un).addOption(mn).addOption(Ht).addOption(ri).addOption(gu).addArgument(hu).action(async(n,e)=>{let{apiKey:t,server:r,config:o,reason:i}=e,a=K,s=it({configFilePath:o}),l=new Xe({baseUrl:r,apiKey:t,logger:a}),c=await cr(K,l,s);await Nb({test:n,reason:i,apiClient:l,project:s,logger:a,identity:c})});pw.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(un).addOption(mn).addOption(Ht).addOption(ri).addOption(gu).addArgument(hu).action(async(n,e)=>{let{apiKey:t,server:r,config:o,reason:i}=e,a=K,s=it({configFilePath:o}),l=new Xe({baseUrl:r,apiKey:t,logger:a}),c=await cr(K,l,s);await kb({test:n,reason:i,apiClient:l,project:s,logger:a,identity:c})});async function bO(){Lu("Main program started"),await Gy(K),Lu("CLI version check complete");try{await bt.parseAsync(process.argv)}catch(n){let e={};try{e.playwrightVersion=dO("npx playwright --version").toString()}catch(t){K.error({err:t},"Error fetching debug information")}K.error({err:n,debugInfo:e},"Uncaught error in CLI"),K.flush(),pi(n,e),y.error(n),process.exit(1)}}mO.setMaxListeners(50);process.on("warning",n=>{K.warn({err:n},`Node warning received on CLI: ${n.message}`)});Lu("CLI parsing setup complete");bO();
4002
4002
  //# sourceMappingURL=cli.js.map
4003
- //# debugId=9bdda1b7-c45e-54b1-847b-1d7e69d70cce
4003
+ //# debugId=ff32955f-eefb-5136-87fc-4c324742bd12
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "momentic",
3
- "version": "2.12.0",
3
+ "version": "2.12.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "momentic",
9
- "version": "2.12.0",
9
+ "version": "2.12.1",
10
10
  "dependencies": {
11
11
  "@actions/exec": "^1.1.1",
12
12
  "@actions/io": "^1.1.3",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "momentic",
3
- "version": "2.12.0",
3
+ "version": "2.12.1",
4
4
  "bin": {
5
5
  "momentic": "./bin/cli.js"
6
6
  },