momentic 2.16.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,39 +1,39 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5ae4a21c-85ec-580b-8627-11d5337ee5e5")}catch(e){}}();
4
- var wa=(t,e)=>{},ic=!1;try{let t=await import("@sentry/node");wa=t.captureException,t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),ic=!0}catch{}import{Command as eN,Option as Ut}from"@commander-js/extra-typings";import{execSync as tN}from"child_process";var Ea=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{existsSync as mv,statSync as pv}from"fs";import{z as bm}from"zod";var gN=bm.object({input:bm.string()});import{z as Ze}from"zod";var SN=Ze.object({srcs:Ze.array(Ze.string()),urls:Ze.array(Ze.string()),desiredSrc:Ze.string().optional(),desiredUrl:Ze.string().optional()}),Tm=Ze.object({srcRegex:Ze.string().optional(),urlRegex:Ze.string().optional()}),wm=Ze.object({x:Ze.number(),y:Ze.number(),correlation:Ze.number()}),yN=Ze.object({searchImageBase64String:Ze.string(),pageImageBase64String:Ze.string(),id:Ze.string().uuid(),timeoutMs:Ze.number().max(1e4).min(0).optional()});import{z as F}from"zod";import*as B from"zod";import{extendZodWithOpenApi as ow}from"zod-openapi";ow(B);var tr=(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))(tr||{}),aw=B.object({mPathSelectorTokens:B.string().array(),frameSrcRegex:B.string().optional(),frameUrlRegex:B.string().optional(),indices:B.number().array()}),sc=B.object({result:B.number(),traceId:B.string()}).array(),Eo=B.object({type:B.literal("GCS_TRACES"),traces:sc}),nr=B.object({id:B.number().int(),dataMomenticId:B.number().int().optional(),selector:B.string().optional(),hybridSelector:B.object({textContent:B.string().nullish(),attributes:B.record(B.string(),B.string()),tagName:B.string(),expandShadowRoot:B.boolean().optional(),classNames:B.string().array(),nthChild:B.number()}).array().optional(),generatedSelectors:B.string().array().optional(),role:B.string().optional(),name:B.string().optional(),numChildren:B.number().optional(),content:B.string().optional(),pathFromRoot:B.string().optional(),serializedHtml:B.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:B.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:B.string().url().optional(),boundingBox:B.object({x:B.number().optional(),y:B.number().optional(),width:B.number(),height:B.number()}).describe("css pixel bounding box").optional(),frameCache:aw.optional(),inputDescription:B.string().optional().describe("the description that generated this cache"),targetSource:B.nativeEnum(tr).optional(),targetUpdateTime:B.string().optional(),targetUpdateLoggerTags:B.record(B.string(),B.string()).optional(),cacheResolutionUpdateSource:B.string().optional(),cacheResolutionUpdateTime:B.string().optional(),cacheResolutionUpdateLoggerTags:B.record(B.string(),B.string()).optional(),memory:Eo.optional()}).openapi({ref:"ElementTargetCache"});function Em(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var iw=B.object({type:B.literal("description"),elementDescriptor:B.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),sw=B.object({x:B.number(),y:B.number()}),lw=B.object({type:B.literal("coordinates"),pixels:sw}).openapi({ref:"CoordinatesTarget"});function rr(t){return t.type==="description"}function bn(t){return t.type==="coordinates"}var gt=B.discriminatedUnion("type",[iw,lw]).openapi({ref:"ElementTarget"});function lc(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function ht(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function ki(t){return Eo.safeParse(t).success}import{v4 as he}from"uuid";import*as E from"zod";import{extendZodWithOpenApi as fw}from"zod-openapi";import{z as Z}from"zod";import{extendZodWithOpenApi as cw}from"zod-openapi";import{z as Ro}from"zod";var cc=Ro.object({result:Ro.boolean(),traceId:Ro.string()}).array(),dc=Ro.object({type:Ro.literal("GCS_TRACES"),traces:cc}),uc=Ro.object({memory:dc.optional()});cw(Z);var Rm=Z.object({plan:Z.string().optional(),evidence:Z.string().optional(),thoughts:Z.string(),result:Z.boolean(),relevantElements:Z.array(Z.number()).optional(),updatedMemory:cc.optional()}),or=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(or||{});var dw=Z.object({type:Z.literal("ELEMENT_NAME"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),value:Z.string()}).openapi({ref:"ElementNameAssertion"}),uw=Z.object({type:Z.literal("ELEMENT_STYLE"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),property:Z.string(),value:Z.string()}).openapi({ref:"ElementStyleAssertion"}),mw=Z.object({type:Z.literal("ELEMENT_CONTENT"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),value:Z.string()}).openapi({ref:"ElementContentAssertion"}),pw=Z.object({type:Z.literal("ELEMENT_ATTRIBUTE"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),attr:Z.string(),value:Z.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Co=(a=>(a.EXISTS="EXISTS",a.VISIBLE="VISIBLE",a.ENABLED="ENABLED",a.EDITABLE="EDITABLE",a.FOCUSED="FOCUSED",a))(Co||{}),gw=Z.object({type:Z.literal("ELEMENT_EXISTENCE"),negated:Z.boolean().optional(),condition:Z.nativeEnum(Co).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Cm=Z.discriminatedUnion("type",[mw,pw,gw,dw,uw]).openapi({ref:"ManualElementAssertion"});var hw=Z.object({type:Z.literal("CONTENT"),negated:Z.boolean().optional(),value:Z.string()}).openapi({ref:"PageContentAssertion"}),vm=Z.discriminatedUnion("type",[hw]).openapi({ref:"ManualPageAssertion"});import Rt from"zod";var mc=Rt.discriminatedUnion("type",[Rt.object({type:Rt.literal("SUBSTRING"),url:Rt.string()}),Rt.object({type:Rt.literal("GLOB"),glob:Rt.string()}),Rt.object({type:Rt.literal("REGEX"),regex:Rt.string()}),Rt.object({type:Rt.literal("DOMAIN"),domain:Rt.string()})]),Ra=Rt.object({urlMatcher:mc,method:Rt.string().optional()});import{z as ge}from"zod";var _i=ge.object({url:ge.string(),method:ge.union([ge.literal("GET"),ge.literal("POST"),ge.literal("PUT"),ge.literal("DELETE"),ge.literal("PATCH")]),headers:ge.record(ge.string(),ge.string()).optional(),params:ge.record(ge.string(),ge.string()).optional(),body:ge.string().optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),Am=ge.object({url:ge.string(),headers:ge.record(ge.string(),ge.string()).optional(),query:ge.string(),variables:ge.string().optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),Di=ge.object({code:ge.string(),fragment:ge.boolean().optional(),environment:ge.union([ge.literal("NODE"),ge.literal("BROWSER")]).optional().describe("default NODE"),timeout:ge.number().int().max(60).optional().describe("Max seconds for the code to complete")});var je=($=>($.AI_EXTRACT="AI_EXTRACT",$.AI_ASSERTION="AI_ASSERTION",$.AUTH_LOAD="AUTH_LOAD",$.AUTH_SAVE="AUTH_SAVE",$.BLUR="BLUR",$.CAPTCHA="CAPTCHA",$.CLICK="CLICK",$.COOKIE="COOKIE",$.COPY="COPY",$.DIALOG="DIALOG",$.DRAG="DRAG",$.ELEMENT_CHECK="ELEMENT_CHECK",$.FILE_UPLOAD="FILE_UPLOAD",$.FOCUS="FOCUS",$.GO_BACK="GO_BACK",$.GO_FORWARD="GO_FORWARD",$.HOVER="HOVER",$.JAVASCRIPT="JAVASCRIPT",$.LOCAL_STORAGE="LOCAL_STORAGE",$.MOUSE_DRAG="MOUSE_DRAG",$.NAVIGATE="NAVIGATE",$.NEW_TAB="NEW_TAB",$.PAGE_CHECK="PAGE_CHECK",$.PASTE="PASTE",$.PRESS="PRESS",$.KEY_DOWN="KEY_DOWN",$.KEY_UP="KEY_UP",$.REFRESH="REFRESH",$.REQUEST="REQUEST",$.GRAPHQL_REQUEST="GRAPHQL_REQUEST",$.SCROLL_DOWN="SCROLL_DOWN",$.SCROLL_UP="SCROLL_UP",$.SCROLL_LEFT="SCROLL_LEFT",$.SCROLL_RIGHT="SCROLL_RIGHT",$.SELECT_OPTION="SELECT_OPTION",$.SWITCH_TAB="TAB",$.TYPE="TYPE",$.VISUAL_DIFF="VISUAL_DIFF",$.WAIT="WAIT",$.WAIT_FOR_URL="WAIT_FOR_URL",$.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",$.AWAIT_LISTENER="AWAIT_LISTENER",$.RECORD_REQUESTS="RECORD_REQUESTS",$.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",$.SET_HEADER="SET_HEADER",$.MOCK_ROUTE="MOCK_ROUTE",$.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",$.OFFLINE_MODE="OFFLINE_MODE",$.SUCCESS="SUCCESS",$))(je||{});fw(E);var V=E.object({thoughts:E.string().optional(),id:E.string().uuid().describe("unique identifier to this step, used for step cache")}),Vt=E.object({useSelector:E.boolean().optional(),force:E.boolean().optional(),disableCache:E.boolean().optional().describe("disable element caching for this step"),iframeUrl:E.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),zt=E.object({target:nr}).optional().openapi({ref:"SingleTargetCache"});function xm(t){return zt.safeParse(t).success}var Ui=E.object({loadTimeout:E.number().int().max(60).optional().describe("Max seconds for the page to load")}),gc=V.merge(Ui).merge(E.object({type:E.literal("NAVIGATE"),url:E.string()})).openapi({ref:"NavigateCommand"}),Bi=Vt.merge(E.object({cache:zt})),ar=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_UP"),deltaY:E.number().optional()}))).openapi({ref:"ScrollUpCommand"}),ir=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_DOWN"),deltaY:E.number().optional()}))).openapi({ref:"ScrollDownCommand"}),vo=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_LEFT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ao=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_RIGHT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollRightCommand"}),jN=E.discriminatedUnion("type",[ar,ir,vo,Ao]).openapi({ref:"AllScrollCommands"}),Sw=V.merge(E.object({type:E.literal("DIALOG"),action:E.union([E.literal("ACCEPT"),E.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),yw=V.merge(E.object({type:E.literal("WAIT"),delay:E.number()})).openapi({ref:"WaitCommand"}),bw=E.object({caseInsensitive:E.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:E.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:E.number().int().optional().describe("Max seconds to wait for the URL to match")}),hc=V.extend({type:E.literal("WAIT_FOR_URL"),matcher:mc}).merge(bw).openapi({ref:"WaitUrlCommand"}),Tw=V.merge(Ui).merge(E.object({type:E.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),ww=V.merge(E.object({type:E.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Ew=V.merge(E.object({type:E.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Rw=V.extend({type:E.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Cw=V.extend({type:E.literal("AUTH_LOAD"),storageState:E.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),fc=V.merge(Vt).extend({type:E.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),vw=V.extend({type:E.literal("COPY"),value:E.string()}).openapi({ref:"CopyCommand"}),Aw=V.extend({type:E.literal("PASTE")}).openapi({ref:"PasteCommand"}),xw=V.merge(Di).extend({type:E.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Or=V.merge(Vt).extend({type:E.literal("CLICK"),target:gt,doubleClick:E.boolean().optional(),rightClick:E.boolean().optional(),waitForDownload:E.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:E.number().optional(),downloadTimeoutMs:E.number().optional(),cache:zt,relativePosition:E.object({x:E.number(),y:E.number()}).optional()}).openapi({ref:"ClickCommand"}),Sc=E.object({fromTarget:nr.optional(),toTarget:nr.optional()}),Ca=V.merge(Vt).merge(E.object({type:E.literal("DRAG"),fromTarget:gt,toTarget:gt,steps:E.number().optional(),hoverSeconds:E.number().optional().describe("Seconds to hover the object before dropping"),cache:Sc.optional()})).openapi({ref:"DragCommand"}),va=V.merge(Vt).merge(E.object({type:E.literal("MOUSE_DRAG"),target:gt.optional(),deltaX:E.string().describe("pixels to move horizontally, can be template"),deltaY:E.string().describe("pixels to move vertically, can be template"),steps:E.number().optional(),cache:zt})).openapi({ref:"MouseDragCommand"}),Nr=V.merge(Vt).merge(E.object({type:E.literal("HOVER"),target:gt,cache:zt})).openapi({ref:"HoverCommand"}),Aa=V.merge(Vt).merge(E.object({type:E.literal("FOCUS"),target:gt,cache:zt})).openapi({ref:"FocusCommand"}),xa=V.merge(Vt).extend({type:E.literal("BLUR"),target:gt.optional(),cache:zt}).openapi({ref:"BlurCommand"}),Iw=E.object({type:E.literal("URL"),url:E.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Pw=E.object({type:E.literal("USER_FILE"),name:E.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Mw=V.extend({type:E.literal("FILE_UPLOAD"),fileSource:E.discriminatedUnion("type",[Iw,Pw]),filename:E.string().optional()}).openapi({ref:"FileUploadCommand"}),Lw=E.discriminatedUnion("type",[E.object({type:E.literal("VALUE"),value:E.string()}),E.object({type:E.literal("LABEL"),label:E.string()}),E.object({type:E.literal("INDEX"),index:E.coerce.string()})]),kr=V.merge(Vt).extend({type:E.literal("SELECT_OPTION"),target:gt,cache:zt,choice:Lw.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),yc=E.union([E.literal("MULTIMODAL"),E.literal("VISION_ONLY")]),xo=V.merge(E.object({type:E.literal("AI_ASSERTION"),assertion:E.string(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional(),contextChoice:yc.optional(),timeout:E.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:uc.optional()})).openapi({ref:"AIAssertionCommand"}),Tn=5,bc=600,_r=V.merge(Vt).extend({type:E.literal("ELEMENT_CHECK"),target:gt,assertion:Cm,cache:zt.or(uc).optional(),timeout:E.number().int().min(0).max(bc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Tc=V.extend({type:E.literal("PAGE_CHECK"),assertion:vm,iframeUrl:E.string().optional().describe("url or url regex for the iframe"),timeout:E.number().int().min(0).max(bc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Ow=V.merge(E.object({type:E.literal("AI_EXTRACT"),goal:E.string(),schema:E.string().optional(),envKey:E.string().optional(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional()})).openapi({ref:"AIExtractCommand"}),Nw=E.object({clearContent:E.boolean().optional(),forceClearContent:E.boolean().optional(),delay:E.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:E.boolean().optional(),pressEnter:E.boolean().optional()}),Im=25,Dr=V.merge(Vt).merge(Nw).extend({type:E.literal("TYPE"),target:gt.optional(),value:E.string(),cache:zt}).openapi({ref:"TypeCommand"}),wc=V.merge(E.object({type:E.literal("PRESS"),value:E.string(),repeat:E.number().optional(),convertMeta:E.boolean().optional(),delayMs:E.number().optional()})).openapi({ref:"PressCommand"}),kw=V.merge(E.object({type:E.literal("KEY_DOWN"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyDownCommand"}),_w=V.merge(E.object({type:E.literal("KEY_UP"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyUpCommand"}),Dw=E.object({type:E.literal("SUBSTRING"),substring:E.string()}),Fw=E.object({type:E.literal("REGEX"),pattern:E.string()}),Uw=E.object({type:E.literal("INDEX"),index:E.coerce.string()}),Bw=E.discriminatedUnion("type",[Dw,Fw,Uw]),zw=V.merge(Ui).merge(E.object({type:E.literal("TAB"),action:Bw})).openapi({ref:"TabCommand"}),Ec=V.merge(Ui).merge(E.object({type:E.literal("NEW_TAB"),url:E.string()})).openapi({ref:"NewTabCommand"}),Hw=V.merge(E.object({type:E.literal("COOKIE"),value:E.string()})).openapi({ref:"CookieCommand"}),$w=V.merge(E.object({type:E.literal("LOCAL_STORAGE"),key:E.string(),value:E.string()})).openapi({ref:"LocalStorageCommand"}),jw=V.extend({type:E.literal("REQUEST")}).merge(_i).openapi({ref:"RequestCommand"}),Gw=V.extend({type:E.literal("GRAPHQL_REQUEST")}).merge(Am).openapi({ref:"GraphQLRequestCommand"}),Ww=V.merge(E.object({type:E.literal("SUCCESS"),condition:xo.optional()})).openapi({ref:"SuccessCommand"}),Vw=V.merge(E.object({type:E.literal("FAILURE")})).openapi({ref:"FailureCommand"}),qw=E.object({data:E.string().describe("location at which to find a jpg"),width:E.number(),height:E.number()}),Ia=V.merge(Vt).merge(E.object({type:E.literal("VISUAL_DIFF"),threshold:E.number().optional().describe("default 0.1"),target:gt.optional(),screenshot:qw.optional(),cache:zt})).openapi({ref:"VisualDiffCommand"}),Kw=V.merge(E.object({type:E.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Ra,key:E.string()})).openapi({ref:"RegisterRequestListenerCommand"}),Yw=V.merge(E.object({type:E.literal("AWAIT_LISTENER"),key:E.string(),timeout:E.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Xw=V.merge(E.object({type:E.literal("RECORD_REQUESTS"),requestMatcher:Ra,key:E.string()})).openapi({ref:"RecordRequestsCommand"}),Jw=V.merge(E.object({type:E.literal("GET_RECORDED_REQUESTS"),key:E.string()})).openapi({ref:"GetRecordedRequestsCommand"}),Qw=V.merge(E.object({type:E.literal("SET_HEADER"),name:E.string(),value:E.string(),requestMatcher:Ra.optional()})).openapi({ref:"SetHeaderCommand"}),Zw=V.merge(E.object({type:E.literal("MOCK_ROUTE"),requestMatcher:Ra,responseGenerator:E.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:E.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:E.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),eE=V.merge(E.object({type:E.literal("REMOVE_ROUTE_MOCK"),key:E.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),tE=V.merge(E.object({type:E.literal("OFFLINE_MODE"),enable:E.boolean()})).openapi({ref:"OfflineModeCommand"}),Pm=E.discriminatedUnion("type",[Or,Dr,wc,kw,_w,kr,gc,ir,ar,xo,Nr,yw,Ww]),nE=E.discriminatedUnion("type",[Ow,Cw,Rw,fc,Hw,vw,Sw,Ca,_r,Mw,ww,Ew,xw,$w,va,Ec,Tc,Aw,Tw,jw,Gw,vo,Ao,zw,Ia,Aa,xa,hc,Kw,Yw,Xw,Jw,Qw,Zw,eE,tE]),Io=E.discriminatedUnion("type",[...Pm.options,...nE.options]).openapi({ref:"Command"}),zi=E.discriminatedUnion("type",[...Pm.options,Vw]);function Un(t){let e;switch(t){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:he(),type:t};break;case"AUTH_LOAD":{e={id:he(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:he(),type:t,goal:""};break;case"DIALOG":e={id:he(),type:t,action:"DISMISS"};break;case"DRAG":e={id:he(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:he(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:he(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:he(),type:t,delay:1};break;case"BLUR":e={id:he(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:he(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:he(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:he(),type:t,value:""};break;case"SELECT_OPTION":e={id:he(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:he(),type:t,url:""};case"TAB":e={id:he(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:he(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:he(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:he(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:he(),type:t,code:""};break;case"AI_ASSERTION":e={id:he(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:he(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:he(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:he(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:he(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:he(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:he(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:he(),type:t,key:""};break}case"SET_HEADER":{e={id:he(),type:t,name:"",value:""};break}case"MOCK_ROUTE":{e={id:he(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:he(),type:t};break}case"OFFLINE_MODE":{e={id:he(),type:t,enable:!0};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Mm(t){switch(t.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{z as rE}from"zod";var KN=rE.discriminatedUnion("type",[xa,fc,Or,Ca,Aa,Nr,va,ar,ir,vo,Ao,kr,Dr,Ia,_r]);function Lm(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as oE}from"zod";import{z as sr}from"zod";function Pa(t){return sr.object({key:sr.string(),testId:sr.string().optional(),moduleId:sr.string().optional(),organizationId:sr.string(),value:t})}function Ma(t){return Pa(t).extend({uniqueKey:sr.string()})}function Hi(t){return sr.record(sr.string(),Ma(t))}var Ct={type:!0,cache:!0},Bn=oE.discriminatedUnion("type",[xo.pick(Ct),xa.pick(Ct),Or.pick(Ct),Ca.pick(Ct),_r.pick(Ct),Aa.pick(Ct),Nr.pick(Ct),va.pick(Ct),ar.pick(Ct),ir.pick(Ct),vo.pick(Ct),Ao.pick(Ct),kr.pick(Ct),Dr.pick(Ct),Ia.pick(Ct)]),$i=Object.values(je).filter(t=>Bn.options.some(e=>e.shape.type.safeParse(t).success));Io.options.forEach(t=>{if("target"in t.shape&&!$i.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function Om(t){return $i.includes(t.type)}var Nm=Pa(Bn),km=Ma(Bn),nk=Hi(Bn);import{z as Rc}from"zod";import{extendZodWithOpenApi as sE}from"zod-openapi";import{z as _m}from"zod";import{extendZodWithOpenApi as aE}from"zod-openapi";import{z as Fr}from"zod";var qt=Fr.object({index:Fr.number().optional().describe("global index within a test (in-order traversal)"),id:Fr.string(),skipped:Fr.boolean().optional(),envKey:Fr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Fr.boolean().optional(),retries:Fr.number().optional()});aE(_m);var iE=qt.extend({type:_m.literal("PRESET_ACTION")}),Ht=iE.extend({command:Io}).openapi({ref:"PresetAction"});sE(Rc);var Ur=qt.extend({type:Rc.literal("AI_ACTION"),text:Rc.string(),steps:Ht.array().optional()}).openapi({ref:"AIAction"});import{z as vt}from"zod";import{z as ji}from"zod";import{extendZodWithOpenApi as lE}from"zod-openapi";lE(ji);var Po=qt.extend({type:ji.literal("AI_ACTION_DYNAMIC"),text:ji.string(),retries:ji.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Dm}from"zod";var Cc=qt.extend({type:Dm.literal("CONDITIONAL"),skipped:Dm.boolean().optional()});import{z as ie}from"zod";var cE=ie.object({cacheKey:ie.string(),cacheExpiryMs:ie.number()}),vc=qt.extend({id:ie.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ie.record(ie.string()).optional(),cacheConfig:cE.optional()}),sn=vc.extend({type:ie.literal("MODULE"),moduleId:ie.string().uuid()}),dE=ie.union([sn.pick({type:!0,moduleId:!0}),ie.record(ie.unknown())]),uE=ie.object({type:ie.literal("URL_REGEX"),regex:ie.string()}),mE=ie.object({type:ie.literal("PAGE_CHECK"),substring:ie.string()}),Ac=ie.object({cacheInvalidation:ie.discriminatedUnion("type",[mE,uE]).optional()}),Ot=ie.object({moduleId:ie.string().uuid(),name:ie.string(),description:ie.string().nullish(),enabled:ie.boolean().nullish(),parameters:ie.string().array().nullish(),defaultParameters:ie.record(ie.string(),ie.string()).nullish(),parameterEnums:ie.record(ie.string(),ie.string().array()).nullish(),defaultCacheKey:ie.string().nullish(),defaultCacheTtl:ie.number().nullish(),defaultCacheAllInvocations:ie.boolean().nullish(),autoAuth:ie.boolean().nullish(),advanced:Ac.nullish()});import{z as Kt}from"zod";var xc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(xc||{});var pE=Kt.discriminatedUnion("type",[Kt.object({type:Kt.literal("NAVIGATE_URL"),url:Kt.string().url()}),Kt.object({type:Kt.literal("GO_TO_SECTION_START")})]),gE=Kt.object({trigger:Kt.nativeEnum(xc).optional(),attempts:Kt.number().int().optional(),restartBehavior:pE}),La=qt.extend({type:Kt.literal("SECTION"),description:Kt.string().describe("user provided goal of what the section should accomplish"),plan:Kt.string().array().optional(),autohealingConfig:gE.optional()});var Fm=Ot.merge(vc).extend({type:vt.literal("RESOLVED_MODULE"),steps:vt.lazy(()=>Ge.array())}),Oa=Ot.extend({steps:vt.lazy(()=>Ge.array())}),Ic=La.extend({steps:vt.lazy(()=>Me.array())}),hE=La.extend({steps:vt.lazy(()=>Ge.array())}),Br=Cc.extend({blocks:vt.object({assertion:vt.lazy(()=>Ht),steps:vt.lazy(()=>Me.array())}).array(),elseSteps:vt.lazy(()=>Me.array().optional())}),fE=Cc.extend({blocks:vt.object({assertion:vt.lazy(()=>Ht),steps:vt.lazy(()=>Ge.array())}).array(),elseSteps:vt.lazy(()=>Ge.array().optional())}),Me=vt.discriminatedUnion("type",[Ht,Ur,Po,sn,Br,Ic]),Ge=vt.discriminatedUnion("type",[Ht,Ur,Po,Fm,fE,hE]);import{z as Yt}from"zod";var SE=Yt.object({steps:Me.array(),beforeSteps:Me.array().nullish(),afterSteps:Me.array().nullish()}),Mo=Yt.object({steps:Ge.array(),beforeSteps:Ge.array().nullish(),afterSteps:Ge.array().nullish()}),zr=Yt.object({steps:Yt.record(Yt.string(),Yt.unknown()).array(),beforeSteps:Yt.record(Yt.string(),Yt.unknown()).array().nullish(),afterSteps:Yt.record(Yt.string(),Yt.unknown()).array().nullish()});var se="1.0.21";var Um=F.object({phrase:F.string()}),Pc=F.object({thoughts:F.string().optional(),result:F.union([F.literal("NOT_FOUND"),F.string(),F.number(),F.array(F.unknown()),F.record(F.unknown(),F.unknown()),F.unknown()])}),H_=F.object({text:F.string()}),Bm=F.object({thoughts:F.string(),review:F.string().optional(),id:F.number().int(),updatedMemory:sc.optional()});var Gi=(p=>(p.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",p.FEW_WORDS="FEW_WORDS",p.STYLE_TAG="STYLE_TAG",p.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",p.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",p.NONE="NONE",p.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",p.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",p.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",p.PREFER_ASSERTION="PREFER_ASSERTION",p.HTML_ELEMENTS="HTML_ELEMENTS",p.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",p.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",p))(Gi||{});var zm=F.object({thoughts:F.string(),category:F.nativeEnum(Gi)}),yE=F.discriminatedUnion("op",[F.object({op:F.literal("replace"),path:F.string(),value:F.string()}),F.object({op:F.literal("add"),path:F.string(),value:F.string()}),F.object({op:F.literal("remove"),path:F.string()})]),$_=F.object({thoughts:F.string(),patches:yE.array()}),bE=[F.literal("add"),F.literal("replace"),F.literal("remove")],TE=F.object({op:F.union(bE),path:F.string(),value:Ge.optional()}),Hm=F.object({patches:TE.array(),thoughts:F.string()}),Mc=(r=>(r.LEGITIMATE="LEGITIMATE",r.RECOVERABLE="RECOVERABLE",r.INELIGIBLE="INELIGIBLE",r))(Mc||{}),$m=F.object({thoughts:F.string(),scenario:F.nativeEnum(Mc),instructions:F.string().nullish()}),jm=F.object({reasoning:F.string(),scenario:F.string(),patch:F.null().optional()}),j_=F.object({thoughts:F.string(),evaluation:F.number().min(1).max(10)}),G_=F.object({observations:F.string(),reasoning:F.string(),command:zi});var Lc=F.object({summary:F.string(),reasoning:F.string(),evaluation:F.discriminatedUnion("type",[F.object({type:F.literal("DONE")}),F.object({type:F.literal("RIGHT_TRACK")}),F.object({type:F.literal("WRONG_TRACK"),feedback:F.string()}),F.object({type:F.literal("IMPOSSIBLE")})])});import{z as N}from"zod";import*as ee from"zod";var X_=ee.object({thoughts:ee.string().optional().describe("only provided if a description was provided"),target:nr.optional().describe("only provided if a description was provided"),pageState:ee.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ee.object({label:ee.string(),value:ee.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ee.object({data:ee.string(),height:ee.number().int(),width:ee.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Wi=ee.union([ee.literal("ELEMENT_CHECK"),ee.literal("NEGATED_CHECK"),ee.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ee.literal("SELECT_OPTION"),ee.literal("TYPE")]);function Hr(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Na=(i=>(i.USER_SELECTOR="USER_SELECTOR",i.CSS_SELECTOR="CSS_SELECTOR",i.HYBRID_SELECTOR="HYBRID_SELECTOR",i.HTML_DISTANCE="HTML_DISTANCE",i.TEMPLATE_MATCHING="TEMPLATE_MATCHING",i.AUTO_FRAME="AUTO_FRAME",i))(Na||{}),Lo=ee.object({matched:ee.boolean(),reason:ee.string().optional().describe("Human understandable description"),logs:ee.string().array().optional().describe("Logs for debugging")}),wE=Lo.extend({type:ee.literal("USER_SELECTOR")}),EE=Lo.extend({type:ee.literal("CSS_SELECTOR"),selectors:ee.string().array()}),RE=Lo.extend({type:ee.literal("HYBRID_SELECTOR")}),CE=Lo.extend({type:ee.literal("HTML_DISTANCE"),distance:ee.number().optional(),closestElement:ee.string().optional(),savedElement:ee.string().optional()}),vE=Lo.extend({type:ee.literal("TEMPLATE_MATCHING"),elementImageUrl:ee.string().url()}),AE=Lo.extend({type:ee.literal("AUTO_FRAME"),logs:ee.string().array().optional()}),Gm=ee.discriminatedUnion("type",[wE,EE,RE,CE,vE,AE]);import{z as Fa}from"zod";import{z as BE}from"zod";import*as j from"zod";import{extendZodWithOpenApi as LE}from"zod-openapi";import{cloneDeep as ka}from"lodash-es";import Xm from"truncate-json";import*as Gr from"zod";import{extendZodWithOpenApi as xE}from"zod-openapi";import{z as ft}from"zod";import{z as Fe}from"zod";var Oc=Fe.object({autoFollowNewTabs:Fe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Fe.union([Fe.boolean(),Fe.literal("inputs-only")]).optional(),ignoreHrefForCaching:Fe.boolean().optional(),disableSecondaryCacheResolution:Fe.boolean().optional(),hybridSelectorMode:Fe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Fe.boolean().optional(),visualActions:Fe.boolean().optional(),autoExpandIframes:Fe.boolean().optional(),disableHtmlSnapshots:Fe.boolean().optional()});var Wm=1e4,Vm=6e4,$r=Oc.extend({pageLoadTimeoutMs:Fe.number().optional().refine(t=>t===void 0||t<=Vm&&t>=-1,{message:`Page load timeout must be between 0 and ${Vm/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Fe.number().optional().refine(t=>t===void 0||t<=Wm&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${Wm/1e3} seconds`}),localChromeExtensionPaths:Fe.string().array().optional(),extraHeaders:Fe.record(Fe.string(),Fe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Fe.string().optional(),disableGpu:Fe.boolean().optional(),bustCacheOnBoundingBoxChange:Fe.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:Fe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Fe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var at="BASE_URL",Vi="CURRENT_URL",jr="ENV_NAME",Oo="TEST_NAME",nD={[at]:"https://www.google.com"},qm=ft.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Km=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.string().describe("variable value"))}),Ym=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.unknown().describe("variable value")),browser:$r.optional()});var rD=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.unknown().describe("variable value"))});xE(Gr);var Nc=Gr.object({env:Gr.record(Gr.unknown())}).openapi({ref:"TestContextSnapshot"}),IE="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",PE=[at,jr,Oo],Jm=[Vi,at,jr,Oo],Xt=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,n=void 0,r={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:n,variablesFromEnvironment:r})}static fromSnapshot({snapshot:e,environmentVariables:n}){let r=e.env[at]??"about:blank",o=e.env[Vi]??"about:blank",a=e.env[jr],i=e.env[Oo],s={};for(let[c,d]of Object.entries(e.env))Jm.includes(c)||(n??{})[c]===void 0&&(s[c]=d);return new t({baseUrl:r,currentUrl:o,dynamicVariables:s,envName:a,testName:i,variablesFromEnvironment:n??{}})}setEnvVariables(e){let n=ka(e);this.env=Object.assign(this.env,n)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,n){this.varsFromMomenticEnvironment[e]=n}getVariable(e){return this.env[e]}setVariable(e,n){PE.includes(e)||(this.env[e]=n)}getEnvName(){return this.env[jr]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ka(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>Jm.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,IE]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:a}=Xm(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(a)}catch{e.env[r]=void 0}}let{jsonString:n}=Xm(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(n)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Vi]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=ka(e.variablesFromEnvironment),this.setMomenticSystemVariable(at,e.baseUrl),e.envName&&this.setMomenticSystemVariable(jr,e.envName),e.testName&&this.setMomenticSystemVariable(Oo,e.testName)}getDynamicVariablesCopy(){return ka(this.env)}getVariablesFromEnvironmentCopy(){return ka(this.varsFromMomenticEnvironment)}};var Ee=(a=>(a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.RUNNING="RUNNING",a.IDLE="IDLE",a.CANCELLED="CANCELLED",a))(Ee||{}),qi=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))(qi||{});import{z as wn}from"zod";import{extendZodWithOpenApi as ME}from"zod-openapi";ME(wn);var me=(d=>(d.AI_PROVIDER="AIProviderError",d.USER_INFRA="UserInfrastructureError",d.ACTION_FAILURE="ActionFailureError",d.ASSERTION_FAILURE="AssertionFailureError",d.CONFIG_ERROR="UserConfigurationError",d.WEB_AGENT_PLATFORM="InternalWebAgentError",d.UNKNOWN_PLATFORM="InternalPlatformError",d.JOB_TIMEOUT="JobTimeoutError",d.CONCURRENCY_ERROR="ConcurrencyError",d.UNKNOWN="UnknownError",d))(me||{});var Qm=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Ki={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",ConcurrencyError:"Concurrency error"},No={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.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},kc=wn.object({reason:wn.nativeEnum(me),previousStepsDescription:wn.array(wn.string()).optional(),summary:wn.string(),rootCause:wn.string().optional()}).openapi({ref:"TestResultClassification"}),Yi=wn.object({errorMessage:wn.string(),errorStack:wn.string().optional(),classification:kc.optional()}).openapi({ref:"TestFailureDetails"});LE(j);var _c=j.object({beforeUrl:j.string().optional(),afterUrl:j.string().optional(),message:j.string().optional(),beforeSnapshot:j.string().optional(),afterSnapshot:j.string().optional(),startedAt:j.coerce.date(),finishedAt:j.coerce.date()}),OE=_c.extend({viewport:j.object({height:j.number(),width:j.number()}).nullish(),status:j.nativeEnum(qi),message:j.string().optional(),elementInteracted:j.string().optional()}),Wr=_c.extend({status:j.nativeEnum(Ee),message:j.string().optional(),data:j.unknown().optional(),beforeTestContext:Nc.optional(),afterTestContext:Nc.optional(),failureReason:j.nativeEnum(me).optional(),details:j.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),Dc=(n=>(n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.ATTEMPTED="ATTEMPTED",n))(Dc||{}),Xi=Wr.merge(Ht).extend({results:OE.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:j.lazy(()=>et.array()).optional(),failureRecoveryStatus:j.object({type:j.nativeEnum(Dc),message:j.string()}).optional()}),NE=Wr.merge(Ur).extend({results:j.lazy(()=>Xi.array()),previousAttempts:j.lazy(()=>et.array()).optional()}),kE=Wr.merge(Po).extend({results:j.lazy(()=>Xi.array()),previousAttempts:j.lazy(()=>et.array()).optional()}),_E=Wr.merge(sn).extend({moduleName:j.string().optional(),results:j.lazy(()=>et.array()),previousAttempts:j.lazy(()=>et.array()).optional()}),DE=Wr.merge(Br).extend({assertion:Xi.optional(),results:j.lazy(()=>et.array()).describe("results for the block actually executed"),previousAttempts:j.lazy(()=>et.array()).optional()}),FE=Wr.merge(La).extend({results:j.lazy(()=>et.array()),healingAttempts:j.lazy(()=>et.array().array()).optional(),previousAttempts:j.lazy(()=>et.array()).optional()}),et=j.discriminatedUnion("type",[NE,kE,Xi,_E,DE,FE]),Ji=Wr.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),UE=_c.extend({index:j.number().optional(),description:j.string(),pageState:j.string().optional(),elementInteracted:j.string().optional(),startedAt:j.coerce.date().or(j.string()).optional().catch(void 0),finishedAt:j.coerce.date().or(j.string()).optional().catch(void 0)}),Qi=UE.extend({beforeScreenshot:j.string().optional(),afterScreenshot:j.string().optional()});var Fc=BE.object({results:et.array().describe("main results"),beforeResults:et.array().optional(),afterResults:et.array().optional()}),_a=Fc.partial();import{z as U}from"zod";import{extendZodWithOpenApi as WE}from"zod-openapi";var ko=(n=>(n.WEB="WEB",n.ANDROID="ANDROID",n))(ko||{});import{isValidCron as zE}from"cron-validator";import{z as re}from"zod";import{z as Uc}from"zod";var zn=(r=>(r.CHROMIUM="Chromium",r.GOOGLE_CHROME="Google Chrome",r.CHROME_FOR_TESTING="Chrome for Testing",r))(zn||{});var Zi=Uc.object({width:Uc.number().min(200).max(1e4),height:Uc.number().min(200).max(1e4)}),Zm={"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}},LD=Object.keys(Zm);var Nt=Zm["Desktop Large"],_o="en-us",Do="America/Los_Angeles";var Fo={latitude:37.7749,longitude:-122.4194};var ep=["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 tp=2e3,es=$r.extend({browserType:re.nativeEnum(zn).optional(),slowMoMs:re.number().optional().refine(t=>t===void 0||t<=tp&&t>=-1,{message:`Slow motion must be between 0 and ${tp} milliseconds`}),basicAuthorization:re.object({username:re.string().optional(),password:re.string().optional()}).optional(),geolocation:re.object({latitude:re.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:re.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:re.boolean().optional(),locale:re.string().optional(),timezone:re.enum(ep).optional(),colorScheme:re.enum(["light","dark"]).optional()}),np=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],Bc=re.object({useMemory:re.boolean().optional(),failureRecovery:re.boolean().optional().describe("undefined means inherit org settings")}),HE=Bc.extend({disableAICaching:re.boolean().optional(),failureRecoveryInstructions:re.string().optional()}),$E=re.object({viewport:Zi.optional()}),Vr=$E.merge(HE).merge(es),Uo=re.object({cron:re.string().refine(t=>zE(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:re.boolean().default(!1),env:re.string().optional(),timeZone:re.string().default("America/Los_Angeles"),jobKey:re.string().optional()}),Bo=re.object({onSuccess:re.boolean().default(!1),failureMessage:re.string().optional(),onFailure:re.boolean().default(!0),successMessage:re.string().optional()}),jE=re.object({name:re.string(),required:re.boolean().optional(),defaultValue:re.string().describe("this is not optional because we need a value when the editor is first loaded")}),ts=jE.array(),GE=re.object({name:re.string(),value:re.string()}),rp=GE.array(),ns=re.object({name:re.string(),default:re.boolean().optional(),fixtures:qm.array().optional()});WE(U);var Jt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},le=(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))(le||{}),rs=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(rs||{});var Ye=U.string().pipe(U.coerce.date()).or(U.date()),Da=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(ko).optional().default("WEB"),createdAt:Ye,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:Ye.or(U.null()),startedAt:Ye.or(U.null()),updatedAt:Ye.nullish(),finishedAt:Ye.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(rs).nullish(),status:U.nativeEnum(le),trigger:U.nativeEnum(Jt),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(le),startedAt:Ye.or(U.null()),finishedAt:Ye.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(me).nullish(),failureDetails:Yi.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),VE={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},os=Da.pick({...VE,test:!0}),op=Da.omit({failureReason:!0,failureDetails:!0,test:!0}),zc=Da.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:Vr.nullish()}).nullish()}).merge(Fc),ap=t=>t.includes("PASSED")&&t.includes("FAILED");var qE=Fa.object({id:Fa.string().uuid(),startedAt:Ye.or(Fa.null()),finishedAt:Ye.or(Fa.null()),status:Fa.nativeEnum(le)}).merge(_a),ZD=qE.array();var as=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(as||{});import{z as Xe}from"zod";var KE=Xe.object({id:Xe.string(),status:Xe.nativeEnum(le),trigger:Xe.nativeEnum(Jt),createdAt:Ye,startedAt:Ye.nullish(),finishedAt:Ye.nullish(),gitCommitSha:Xe.string().nullish(),gitCommitShaShort:Xe.string().nullish(),gitCommitTimestamp:Ye.nullish(),gitBranchName:Xe.string().nullish(),gitOriginUrl:Xe.string().nullish(),gitCommitMessage:Xe.string().nullish(),gitCommitAuthorName:Xe.string().nullish(),githubRepository:Xe.string().nullish(),gitlabProjectPath:Xe.string().nullish(),pipelineId:Xe.string().nullish(),cliVersion:Xe.string().nullish(),labels:Xe.string().array().optional(),suite:Xe.object({id:Xe.string(),name:Xe.string()}).nullish(),runs:Xe.object({status:Xe.nativeEnum(le)}).array()}).openapi({ref:"RunGroup"}),ip=KE.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:os.array()});import{z as it}from"zod";var YE=it.object({type:it.literal("TARGETING"),name:it.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Gm.array(),pageState:it.string().optional(),targetSource:it.nativeEnum(tr).optional(),targetUpdateTime:it.string().optional()}),XE=it.object({type:it.literal("AI_LOCATION"),matched:it.boolean(),pageState:it.string().optional(),ragUsed:it.boolean().optional(),thoughts:it.string().optional()}),JE=it.object({type:it.literal("ASSERTION"),relevantElementsSerialized:it.string().array().optional(),pageState:it.string().optional(),ragUsed:it.boolean().optional()}),sp=it.discriminatedUnion("type",[YE,XE,JE]);function is(){return{details:[]}}import{z as Ve}from"zod";var QE=Ve.object({id:Ve.string(),name:Ve.string()}),pF=QE.merge(Ve.object({createdAt:Ye,createdBy:Ve.string(),schedule:Uo,notification:Bo,environment:Ve.object({name:Ve.string()}).nullish(),beforeTests:Ve.object({id:Ve.string()}).array().nullish(),afterTests:Ve.object({id:Ve.string()}).array().nullish()})),lp=Ve.object({id:Ve.string().uuid(),orgId:Ve.string(),createdAt:Ye,startedAt:Ye.or(Ve.null()),finishedAt:Ye.or(Ve.null()),status:Ve.nativeEnum(le),trigger:Ve.nativeEnum(Jt),suite:Ve.object({id:Ve.string(),name:Ve.string()}).nullish(),runs:Da.array()}),gF=lp.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),cp=lp.extend({runs:os.array()});import{z as Qt}from"zod";import{cloneDeep as SF}from"lodash-es";import{z as fe}from"zod";var RF=fe.object({thoughts:fe.string(),subGoals:fe.object({instruction:fe.string()}).array()}),CF=fe.object({thoughts:fe.string(),newPlanMarkdown:fe.string()}),vF=fe.object({thoughts:fe.string(),correct:fe.boolean(),failedActionIndex:fe.number().optional()}),ZE=fe.object({type:fe.literal("PLANNING"),beforePlan:fe.string(),goalDecision:fe.string(),thoughts:fe.string()}),eR=fe.object({type:fe.literal("RUNNING"),stepDisplayName:fe.string(),status:fe.nativeEnum(Ee),results:et.array()}),tR=fe.object({type:fe.literal("REVISING"),beforePlan:fe.string(),afterPlan:fe.string(),errString:fe.string(),diffs:fe.string(),thoughts:fe.string()}),nR=fe.object({type:fe.literal("SYSTEM"),message:fe.string()}),rR=fe.discriminatedUnion("type",[ZE,eR,tR,nR]),dp=rR.array();var MF=Qt.object({id:Qt.string(),scheduledAt:Qt.coerce.date().nullable(),startedAt:Qt.coerce.date().nullable(),finishedAt:Qt.coerce.date().nullable(),status:Qt.nativeEnum(le),history:dp.nullable(),testPlan:Qt.object({id:Qt.string(),name:Qt.string()}).nullable(),test:Qt.object({id:Qt.string(),name:Qt.string()}).nullable()});import{z as At}from"zod";var Hc=At.object({content:At.string(),ids:At.string().array(),tokenLength:At.number()}),oR=At.object({chunks:Hc.array()}),qF=At.object({ids:At.string().array(),score:At.number(),tokenLength:At.number()}),KF=oR.extend({description:At.string().describe("Input to pass to RAG engine"),tokenLimit:At.number()}),up=At.object({ids:At.number().array()}),mp=At.object({indices:At.number().array()});var kt=N.object({disableCache:N.boolean().optional(),useMemory:N.boolean().optional(),loggerTags:N.record(N.string(),N.string()).optional(),langfuseSessionId:N.string().optional(),agentConfigVersion:N.string().optional()}),n0=kt.extend({chunks:Hc.array(),description:N.string().describe("Input to pass to AI"),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),softTokenLimit:N.number(),hardTokenLimit:N.number()}),aR=N.object({screenshotBase64AfterCommand:N.string(),urlAfterCommand:N.string(),serializedCommand:N.string(),elementInteracted:N.string().optional(),thoughts:N.string().optional()}),pp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),source:Wi.optional().catch(void 0),memory:N.discriminatedUnion("type",[Eo,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional()}),gp=N.object({target:N.string().or(N.number()),browserState:N.string().optional(),screenshot:N.string().optional(),boundingBox:N.object({x:N.number(),y:N.number(),height:N.number(),width:N.number()}).optional()}),hp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string().optional(),returnSchema:N.string().optional()}),iR=N.literal("NEGATED_CHECK"),fp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),url:N.string(),contextChoice:yc.optional(),memory:N.discriminatedUnion("type",[dc,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional(),source:iR.optional()}),Sp=N.object({command:Io}),$c=N.object({goal:N.string(),browserState:N.string(),startingScreenshot:N.string().optional(),screenshot:N.string(),url:N.string(),history:aR.array(),actionHint:N.string().optional(),lastError:N.string().optional()}),yp=N.object({results:Qi.array(),errorMessage:N.string(),errorStack:N.string().optional()}),bp=N.object({results:Qi.array(),goal:N.string(),errorMessage:N.string()}),Tp=N.object({failedResults:Qi.array(),nextStepsSerialized:N.string().array(),currentUrl:N.string(),currentPageState:N.string(),currentScreenshot:N.string(),customInstructions:N.string().optional(),testDescription:N.string().optional()}),r0=N.object({description:N.string(),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),excerpt:N.string()});import{z as Ua}from"zod";var i0=Ua.object({goal:Ua.string()}),wp=Ua.object({keywords:Ua.array(Ua.string())});import{z as jc}from"zod";var ss=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(ss||{}),c0=jc.nativeEnum(ss),sR=jc.enum(["v1","v2"]),d0=sR.or(jc.string().describe("for people with special configurations"));import{z as Ue}from"zod";var Ep=Ue.object({attributesRequired:Ue.array(Ue.string()).optional(),textRequired:Ue.boolean().optional(),boundsRequired:Ue.boolean().optional()}),lR=Ue.object({id:Ue.number(),thoughts:Ue.string(),requirements:Ep.optional(),additionalElements:Ue.object({id:Ue.number(),requirements:Ep}).array().optional()}),Rp=Ue.object({description:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),Cp=Ue.object({assertion:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),cR=Ue.object({thoughts:Ue.string(),result:Ue.boolean(),relevantElements:Ue.array(Ue.number()).optional()});var vp=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as qr}from"zod";var Ap=qr.object({id:qr.string().uuid(),skipped:qr.boolean().optional(),envKey:qr.string().optional().describe("key in the environment to save the result of this step to")}),Gc=Ap.merge(_i).extend({type:qr.literal("REQUEST")}),Wc=Ap.merge(Di).extend({type:qr.literal("JAVASCRIPT")}),Vc=qr.discriminatedUnion("type",[Wc,Gc]);import{z as Zt}from"zod";import{z as Kr}from"zod";var dR=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,ve=t=>{let e=t.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var ls=Kr.string().min(1).max(255).superRefine((t,e)=>{try{Yr(t)}catch(n){return e.addIssue({code:Kr.ZodIssueCode.custom,message:n.message,fatal:!0}),Kr.NEVER}});function Yr(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(dR))throw new Error("Name cannot be a UUID. Please choose a different name.")}var cs=Kr.preprocess(t=>t===null?"":t,Kr.union([Kr.string().url(),Kr.literal("")])).optional();var xp=Zt.object({id:Zt.string(),name:ls,description:Zt.string().optional().nullish(),baseUrl:cs.nullish(),schemaVersion:Zt.string(),advanced:Zt.unknown().optional(),retries:Zt.number(),envs:Zt.array(ns).nullish(),parameters:ts.nullish()}),uR=Zt.object({createdAt:Zt.coerce.date(),updatedAt:Zt.coerce.date(),schedule:Uo.nullish(),notification:Bo.nullish(),createdBy:Zt.string(),organizationId:Zt.string()}),mR=xp.merge(uR),D0=mR.extend({steps:Vc.array()}),F0=xp.extend({steps:Vc.array()});import{z as _t}from"zod";var Ip=_t.object({startedAt:_t.coerce.date(),finishedAt:_t.coerce.date(),status:_t.nativeEnum(Ee),message:_t.string().optional(),data:_t.unknown().optional()}),pR=Ip.merge(Wc).extend({type:_t.literal("JAVASCRIPT")}),gR=Ip.merge(Gc).extend({type:_t.literal("REQUEST")}),hR=_t.discriminatedUnion("type",[pR,gR]),Pp=_t.object({startedAt:_t.coerce.date(),finishedAt:_t.coerce.date().nullish(),status:_t.nativeEnum(le),results:hR.array(),failureReason:_t.string().nullish(),failureDetails:Yi.nullish()});import{z as Dt}from"zod";var fR=Dt.object({id:Dt.string(),organizationId:Dt.string(),createdAt:Dt.coerce.date(),updatedAt:Dt.coerce.date(),createdBy:Dt.string(),scheduledAt:Dt.coerce.date().nullish(),startedAt:Dt.coerce.date().nullish(),finishedAt:Dt.coerce.date().nullish(),status:Dt.nativeEnum(le),trigger:Dt.nativeEnum(Jt),results:Pp.array().nullish(),apiTestName:Dt.string().nullish(),apiTestPath:Dt.string().nullish(),apiTestId:Dt.string().nullish()}),q0=fR.pick({status:!0,startedAt:!0,finishedAt:!0});var Ba=(n=>(n.TestRun="test-run",n.CreditsUsed="credits-used",n))(Ba||{}),Mp=3;function SR(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function qc(t){if(!SR(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Kc(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return Mp;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var zo=class{async reportBillableEvent(e,n,r){}async reportCreditsUsed(e,n,r,o){}};function Yc(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as yR,splitCookiesString as bR}from"set-cookie-parser";import{z as Te}from"zod";var Xc=Te.object({name:Te.string(),value:Te.string(),url:Te.string().optional(),domain:Te.string().optional(),path:Te.string().optional(),expires:Te.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Te.boolean().optional(),secure:Te.boolean().default(!0),sameSite:Te.union([Te.literal("Strict"),Te.literal("Lax"),Te.literal("None")]).default("None")});function ds(t,e){let n=[],r=bR(t);for(let o of r){let a=yR(o,{decodeValues:!1});if(!a.name)throw new Error("Name missing from cookie");if(!a.value)continue;let i;if(a.sameSite){let d=a.sameSite.trim().toLowerCase();if(d==="strict")i="Strict";else if(d==="lax")i="Lax";else if(d==="none")i="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}a.httpOnly===void 0&&(a.httpOnly=!1),!a.path&&a.domain&&(a.path="/"),!a.domain&&e&&(a.domain=e);let s=Xc.parse({...a,expires:a.expires?a.expires.getTime()/1e3:void 0,sameSite:i});n.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())||n.push({...s,name:u,value:m})}}return n}var TR=Te.object({origin:Te.string(),localStorage:Te.array(Te.object({name:Te.string(),value:Te.string()}))}),wR=Te.object({entries:Te.record(Te.string(),Te.array(Te.tuple([Te.unknown(),Te.unknown()]))),version:Te.number().optional()}),us=Te.object({cookies:Xc.array().optional(),origins:TR.array().optional(),idb:Te.record(Te.string(),wR).optional().describe("key is db name")});function Lp(t,e){let n=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=Xc.safeParse({name:r.key,...r});if(!o.success)return;let a=o.data;!a.domain&&!a.url&&(a.domain=e),n.push(a)}),n}import OR from"zod";import{v4 as hU}from"uuid";import{z as Se}from"zod";import*as Le from"zod";var Op=Le.object({requiredText:Le.string().optional(),requiredAttributes:Le.record(Le.string(),Le.string()).optional(),requiredBounds:Le.boolean().optional()}),ER=Le.object({xPath:Le.string(),requirements:Op.optional()}),RR=Le.object({type:Le.literal("NATIVE"),bounds:Le.number().array(),resolvedDescription:Le.string(),xPath:Le.string(),elementOnlySerializedXml:Le.string(),requirements:Op.optional(),requiredRelatedElements:ER.array().optional()}),CR=Le.object({type:Le.literal("WEBVIEW"),resolvedDescription:Le.string(),xPath:Le.string(),browserCache:nr.optional()}),Np=Le.discriminatedUnion("type",[RR,CR]);var Ho=(c=>(c.AI_CHECK="AI_CHECK",c.TAP="TAP",c.TYPE="TYPE",c.PRESS="PRESS",c.OPEN_APP="OPEN_APP",c.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",c.JAVASCRIPT="JAVASCRIPT",c.ADB="ADB",c.STATE="STATE",c))(Ho||{}),kp=(l=>(l.BACK="BACK",l.HOME="HOME",l.APP_SWITCHER="APP_SWITCHER",l.POWER="POWER",l.SEARCH="SEARCH",l.VOLUME_UP="VOLUME_UP",l.VOLUME_DOWN="VOLUME_DOWN",l.VOLUME_MUTE="VOLUME_MUTE",l))(kp||{}),_p=Se.discriminatedUnion("type",[Se.object({type:Se.literal("description"),description:Se.string()}),Se.object({type:Se.literal("coordinates"),xPercent:Se.number(),yPercent:Se.number()})]),Hn=Se.object({id:Se.string().uuid(),disableCache:Se.boolean().optional()}),vR=Hn.extend({type:Se.literal("STATE")}),Dp=Se.object({target:Np}),Jc=Hn.extend({type:Se.literal("TAP"),target:_p,cache:Dp.optional()}),Qc=Hn.extend({type:Se.literal("TYPE"),target:_p.optional(),cache:Dp.optional(),text:Se.string()}),AR=Hn.extend({type:Se.literal("OPEN_NOTIFICATION_DRAWER")}),xR=Hn.extend({type:Se.literal("PRESS"),key:Se.nativeEnum(kp)}),IR=Hn.extend({type:Se.literal("OPEN_APP"),packageName:Se.string(),activityName:Se.string().optional()}),PR=Hn.extend({type:Se.literal("AI_CHECK"),assertion:Se.string(),timeoutSecs:Se.number().optional()}),MR=Hn.extend({type:Se.literal("JAVASCRIPT"),code:Se.string(),timeout:Se.number().int().max(60).optional().describe("Max seconds for the code to complete")}),LR=Hn.extend({type:Se.literal("ADB"),command:Se.string()}),Fp=Se.discriminatedUnion("type",[Jc,Qc,xR,IR,AR,PR,MR,LR,vR]);var Up={type:!0,cache:!0},$o=OR.discriminatedUnion("type",[Jc.pick(Up),Qc.pick(Up)]),RU=Object.values(Ho).filter(t=>$o.options.some(e=>e.shape.type.safeParse(t).success));var Bp=Pa($o),zp=Ma($o),CU=Hi($o);import{cloneDeep as xU}from"lodash-es";import PU from"truncate-json";import lr from"zod";import za from"zod";var NR=za.object({id:za.string().uuid(),envKey:za.string().optional()}),$n=NR.extend({type:za.literal("MOBILE_PRESET_STEP"),command:Fp}),kU=za.discriminatedUnion("type",[$n]);import Be from"zod";var jo=Be.object({startTime:Be.number(),endTime:Be.number().optional(),error:Be.string().optional()});var Zc=jo.extend({type:Be.literal("SECTION"),name:Be.string(),subSpans:Be.lazy(()=>BR.array())}),kR=jo.extend({type:Be.literal("AI_LOCATOR_CALL"),result:Be.object({serializedElement:Be.string(),id:Be.number(),thoughts:Be.string()}).optional()}),_R=jo.extend({type:Be.literal("AI_ASSERTION_CALL"),result:Be.object({thoughts:Be.string(),result:Be.boolean()}).optional()}),DR=jo.extend({type:Be.literal("WAIT_FOR_STABILITY"),reason:Be.string().optional()}),FR=jo.extend({type:Be.literal("RESOLVE_TARGET_CACHE"),result:Be.object({serializedElement:Be.string()}).optional()}),UR=jo.extend({type:Be.literal("GET_EMULATOR_STATE")}),BR=Be.discriminatedUnion("type",[Zc,kR,_R,DR,FR,UR]);var zR=lr.object({message:lr.string().optional(),startTime:lr.number(),endTime:lr.number(),status:lr.nativeEnum(Ee),trace:Zc.optional().catch(void 0),beforeSnapshot:lr.string().optional(),afterSnapshot:lr.string().optional()}),HR=$n.merge(zR).extend({data:lr.unknown().optional().describe("output data from the step")}),ms=HR;import tt from"zod";import{z as ln}from"zod";import{z as _e}from"zod";var St=_e.object({id:_e.string(),name:ls,baseUrl:cs,description:_e.string().optional().nullish(),schemaVersion:_e.string(),advanced:Vr,retries:_e.number(),envs:_e.array(ns).nullish(),parameters:ts.nullish(),disabled:_e.boolean().optional(),labels:_e.array(_e.string()).optional().catch([])}),qU=_e.enum(["INHERIT","ENABLED","DISABLED"]);var $R=Vr.extend({failureRecovery:_e.boolean().or(_e.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:_e.boolean().or(_e.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var KU=St.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:$R}),YU=St.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),jR=_e.object({labels:_e.array(_e.string()).optional(),outputs:rp.nullish()}),en=St.merge(jR),GR=_e.object({createdAt:_e.coerce.date(),updatedAt:_e.coerce.date(),updatedBy:_e.string().nullable(),schedule:Uo,notification:Bo,createdBy:_e.string(),organizationId:_e.string(),folderId:_e.string().nullable().optional()}),WR=St.merge(GR),XU=WR.merge(Mo),ps=St.merge(Mo),JU=St.merge(zr);var Hp="test",$p="module",VR="mobile-test",st=(n=>(n.TEST=`${Hp}.yaml`,n.MODULE=`${$p}.yaml`,n))(st||{}),pe=(r=>(r.TEST=`momentic/${Hp}`,r.MODULE=`momentic/${$p}`,r.MOBILE_TEST=`momentic/${VR}`,r))(pe||{}),oB=St.merge(zr),ed=Ot.extend({steps:ln.array(ln.record(ln.string(),ln.unknown())),schemaVersion:ln.string()}),aB=ed.extend({fileType:ln.literal(pe.MODULE)}),iB=ln.object({test:ln.string().describe("YAML for the test, including metadata and steps"),modules:ln.record(ln.string(),ln.string()).describe("Map of module name to YAML for the module")});var qR=tt.object({disableDefaultWebviewAccessibilityTree:tt.boolean().optional(),autoGrantPermissions:tt.boolean().optional()}),KR=qR,Ha=tt.object({retries:tt.number().optional().describe("number of retries to run"),defaultChannel:tt.string().optional().describe("default channel to use"),defaultTag:tt.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:tt.string().optional(),emulator:KR.optional()}),td=tt.object({id:tt.string().uuid(),description:tt.string(),schemaVersion:tt.string(),settings:Ha}),YR=td.merge(tt.object({steps:tt.array($n)})),jp=tt.object({fileType:tt.literal(pe.MOBILE_TEST)}).merge(YR),uB=tt.object({name:tt.string(),steps:tt.array($n).optional(),settings:Ha.optional()});var IB=new Set(Object.values(je));var XR={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},PB={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},MB={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},LB={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},OB={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import JR from"semver";import{z as QR}from"zod";var DB=QR.string().refine(t=>JR.valid(t),{message:"must be a valid semver string"});import{Faker as BB,en as zB}from"@faker-js/faker";import{z as O}from"zod";var gs=55555,$B=O.object({body:O.string(),to:O.string(),from:O.string()}),jB=O.object({from:O.string().optional(),to:O.string(),timeout:O.number().optional(),beforeDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional()}),GB=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),WB=O.object({inbox:O.string().transform(t=>t.toLowerCase()),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),timeout:O.number().optional(),trimWhitespace:O.boolean().optional()}),VB=O.object({inbox:O.string(),limit:O.number().optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),trimWhitespace:O.boolean().optional()});var hs=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(hs||{}),Gp=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),ZR=O.object({url:O.string(),options:O.object({method:O.string(),body:O.string().nullish(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),eC=O.object({body:O.string().nullish(),options:O.object({status:O.number(),statusText:O.string().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),Wp=O.object({result:O.unknown(),variableUpdates:O.record(O.string(),O.unknown()).optional(),persistentVariableUpdates:O.record(O.string(),O.unknown()).optional(),error:O.string().optional(),success:O.boolean()}),qB=O.object({id:O.string().optional(),orgId:O.string(),momenticLambdaAuthHash:O.string(),code:O.string(),fragment:O.boolean(),state:O.object({env:O.record(O.string(),O.unknown()),request:ZR,response:eC,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(hs).optional()}),cr=15e3;import*as yt from"zod";import{extendZodWithOpenApi as tC}from"zod-openapi";tC(yt);var nC=yt.object({url:yt.string(),lineNumber:yt.number(),columnNumber:yt.number()}).openapi({ref:"CodeLocation"}),fs=yt.object({timestamp:yt.number(),text:yt.string(),type:yt.string(),tabIndex:yt.number(),args:yt.unknown().array().optional(),url:yt.string().optional(),location:nC.optional()}).openapi({ref:"ConsoleLog"}),Vp=fs.array(),rC=Vp.array();import*as rd from"zod";import{extendZodWithOpenApi as RC}from"zod-openapi";import{z as I}from"zod";var oC=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),aC=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),iC=I.object({onContentLoad:I.number().optional(),onLoad:I.number().optional(),comment:I.string().optional()}),Kp=I.object({startedDateTime:I.string(),id:I.string(),title:I.string().optional(),pageTimings:iC,comment:I.string().optional()}),sC=I.array(Kp),lC=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()}),Yp=I.array(lC),cC=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),Xp=I.array(cC),dC=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),uC=I.array(dC),mC=I.object({name:I.string(),value:I.string().optional(),fileName:I.string().optional(),contentType:I.string().optional(),comment:I.string().optional()}),pC=I.array(mC),gC=I.object({mimeType:I.string(),params:pC,text:I.string(),comment:I.string().optional()}),hC=I.object({method:I.string(),url:I.string(),httpVersion:I.string().optional(),cookies:Yp,headers:Xp,queryString:uC,postData:gC.optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),fC=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()}),SC=I.object({status:I.number(),statusText:I.string(),httpVersion:I.string().optional(),cookies:Yp,headers:Xp,content:fC,redirectURL:I.string().optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),qp=I.object({expires:I.string().optional(),lastAccess:I.string(),eTag:I.string(),hitCount:I.number(),comment:I.string().optional()}),yC=I.object({beforeRequest:qp.optional(),afterRequest:qp.optional(),comment:I.string().optional()}),bC=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()}),Jp=I.object({pageref:I.string().optional(),startedDateTime:I.string(),time:I.number().optional(),request:hC,response:SC.optional(),cache:yC.optional(),timings:bC,serverIPAddress:I.string().optional(),connection:I.string().optional(),comment:I.string().optional(),_resourceType:I.string().optional()}),TC=I.array(Jp),wC=I.object({version:I.string().default("1.1"),creator:oC.optional(),browser:aC.optional(),pages:sC.optional(),entries:TC,comment:I.string().optional()}),EC=I.object({log:wC}),Qp=I.record(I.string(),Kp),Zp=I.record(I.string(),Jp);function nd(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime()),entries:Object.values(e).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime())}}}RC(rd);var CC=rd.object({logsPerPage:fs.array().array(),harPages:Qp.optional(),harEntries:Zp.optional()}).openapi({ref:"DebugData"});var $a=class{async getConsoleLogsForRunAttempt(e,n,r){}async getNetworkLogsForRunAttempt(e,n,r){}async getHtmlSnapshot(e,n){}async getA11yTreeSnapshot(e,n){}async getScreenshot(e,n){}async storeConsoleLogsForRunAttempt(e,n,r,o){}async storeNetworkLogsForRunAttempt(e,n,r,o){}async storeScreenshot(e,n,r){}async storeHtmlSnapshot(e,n,r){}};var Ss=class extends Error{constructor(e,n,r,o={}){super(`The ${r} with id ${n} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function eg(t){for(let e of Object.values(me))if(t.includes(e))return e}var A=class extends Error{reason;constructor(e,n,r){let o=!1;for(let a of Object.values(me))if(n.startsWith(a)){o=!0,e=a;break}if(r?.errOptions?.cause)super(o?n:`${e}: ${n}`,r?.errOptions);else{let a=o?n:`${e}${n?`: ${n}`:""}`;super(a,r?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},Go=class extends Error{updatedLocatorMemory;constructor(e,n,r={}){super(e,r),this.updatedLocatorMemory=n,this.name="NoElementsFoundUsingAIError"}},En=class extends Error{decisions;constructor(e,n,r={}){super(e,r),this.decisions=n,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c9cae857-4881-55a6-b917-3c68fc9296b3")}catch(e){}}();
4
+ var wa=(t,e)=>{},rc=!1;try{let t=await import("@sentry/node");wa=t.captureException,t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),rc=!0}catch{}import{Command as iN,Option as Ut}from"@commander-js/extra-typings";import{execSync as sN}from"child_process";var Ea=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{existsSync as hv,statSync as fv}from"fs";import{z as ym}from"zod";var TN=ym.object({input:ym.string()});import{z as nt}from"zod";var RN=nt.object({srcs:nt.array(nt.string()),urls:nt.array(nt.string()),desiredSrc:nt.string().optional(),desiredUrl:nt.string().optional()}),bm=nt.object({srcRegex:nt.string().optional(),urlRegex:nt.string().optional()}),Tm=nt.object({x:nt.number(),y:nt.number(),correlation:nt.number()}),CN=nt.object({searchImageBase64String:nt.string(),pageImageBase64String:nt.string(),id:nt.string().uuid(),timeoutMs:nt.number().max(1e4).min(0).optional()});import{z as F}from"zod";import*as B from"zod";import{extendZodWithOpenApi as lw}from"zod-openapi";lw(B);var er=(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))(er||{}),cw=B.object({mPathSelectorTokens:B.string().array(),frameSrcRegex:B.string().optional(),frameUrlRegex:B.string().optional(),indices:B.number().array()}),oc=B.object({result:B.number(),traceId:B.string()}).array(),Eo=B.object({type:B.literal("GCS_TRACES"),traces:oc}),tr=B.object({id:B.number().int(),dataMomenticId:B.number().int().optional(),selector:B.string().optional(),hybridSelector:B.object({textContent:B.string().nullish(),attributes:B.record(B.string(),B.string()),tagName:B.string(),expandShadowRoot:B.boolean().optional(),classNames:B.string().array(),nthChild:B.number()}).array().optional(),generatedSelectors:B.string().array().optional(),role:B.string().optional(),name:B.string().optional(),numChildren:B.number().optional(),content:B.string().optional(),pathFromRoot:B.string().optional(),serializedHtml:B.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:B.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:B.string().url().optional(),boundingBox:B.object({x:B.number().optional(),y:B.number().optional(),width:B.number(),height:B.number()}).describe("css pixel bounding box").optional(),frameCache:cw.optional(),inputDescription:B.string().optional().describe("the description that generated this cache"),targetSource:B.nativeEnum(er).optional(),targetUpdateTime:B.string().optional(),targetUpdateLoggerTags:B.record(B.string(),B.string()).optional(),cacheResolutionUpdateSource:B.string().optional(),cacheResolutionUpdateTime:B.string().optional(),cacheResolutionUpdateLoggerTags:B.record(B.string(),B.string()).optional(),memory:Eo.optional()}).openapi({ref:"ElementTargetCache"});function wm(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var dw=B.object({type:B.literal("description"),elementDescriptor:B.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),uw=B.object({x:B.number(),y:B.number()}),mw=B.object({type:B.literal("coordinates"),pixels:uw}).openapi({ref:"CoordinatesTarget"});function nr(t){return t.type==="description"}function bn(t){return t.type==="coordinates"}var ht=B.discriminatedUnion("type",[dw,mw]).openapi({ref:"ElementTarget"});function ac(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function ft(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function ki(t){return Eo.safeParse(t).success}import{v4 as fe}from"uuid";import*as w from"zod";import{extendZodWithOpenApi as Tw}from"zod-openapi";import{z as ee}from"zod";import{extendZodWithOpenApi as pw}from"zod-openapi";import{z as Ro}from"zod";var ic=Ro.object({result:Ro.boolean(),traceId:Ro.string()}).array(),sc=Ro.object({type:Ro.literal("GCS_TRACES"),traces:ic}),lc=Ro.object({memory:sc.optional()});pw(ee);var Em=ee.object({plan:ee.string().optional(),evidence:ee.string().optional(),thoughts:ee.string(),result:ee.boolean(),relevantElements:ee.array(ee.number()).optional(),updatedMemory:ic.optional()}),rr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(rr||{});var gw=ee.object({type:ee.literal("ELEMENT_NAME"),negated:ee.boolean().optional(),operation:ee.nativeEnum(rr),value:ee.string()}).openapi({ref:"ElementNameAssertion"}),hw=ee.object({type:ee.literal("ELEMENT_STYLE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(rr),property:ee.string(),value:ee.string()}).openapi({ref:"ElementStyleAssertion"}),fw=ee.object({type:ee.literal("ELEMENT_CONTENT"),negated:ee.boolean().optional(),operation:ee.nativeEnum(rr),value:ee.string()}).openapi({ref:"ElementContentAssertion"}),Sw=ee.object({type:ee.literal("ELEMENT_ATTRIBUTE"),negated:ee.boolean().optional(),operation:ee.nativeEnum(rr),attr:ee.string(),value:ee.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Co=(a=>(a.EXISTS="EXISTS",a.VISIBLE="VISIBLE",a.ENABLED="ENABLED",a.EDITABLE="EDITABLE",a.FOCUSED="FOCUSED",a))(Co||{}),yw=ee.object({type:ee.literal("ELEMENT_EXISTENCE"),negated:ee.boolean().optional(),condition:ee.nativeEnum(Co).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Rm=ee.discriminatedUnion("type",[fw,Sw,yw,gw,hw]).openapi({ref:"ManualElementAssertion"});var bw=ee.object({type:ee.literal("CONTENT"),negated:ee.boolean().optional(),value:ee.string()}).openapi({ref:"PageContentAssertion"}),Cm=ee.discriminatedUnion("type",[bw]).openapi({ref:"ManualPageAssertion"});import Rt from"zod";var cc=Rt.discriminatedUnion("type",[Rt.object({type:Rt.literal("SUBSTRING"),url:Rt.string()}),Rt.object({type:Rt.literal("GLOB"),glob:Rt.string()}),Rt.object({type:Rt.literal("REGEX"),regex:Rt.string()}),Rt.object({type:Rt.literal("DOMAIN"),domain:Rt.string()})]),Ra=Rt.object({urlMatcher:cc,method:Rt.string().optional()});import{z as he}from"zod";var _i=he.object({url:he.string(),method:he.union([he.literal("GET"),he.literal("POST"),he.literal("PUT"),he.literal("DELETE"),he.literal("PATCH")]),headers:he.record(he.string(),he.string()).optional(),params:he.record(he.string(),he.string()).optional(),body:he.string().optional(),timeout:he.number().int().optional().describe("Max seconds to wait for the request to complete")}),vm=he.object({url:he.string(),headers:he.record(he.string(),he.string()).optional(),query:he.string(),variables:he.string().optional(),timeout:he.number().int().optional().describe("Max seconds to wait for the request to complete")}),Di=he.object({code:he.string(),fragment:he.boolean().optional(),environment:he.union([he.literal("NODE"),he.literal("BROWSER")]).optional().describe("default NODE"),timeout:he.number().int().max(60).optional().describe("Max seconds for the code to complete")});var Ge=(G=>(G.AI_EXTRACT="AI_EXTRACT",G.AI_ASSERTION="AI_ASSERTION",G.AUTH_LOAD="AUTH_LOAD",G.AUTH_SAVE="AUTH_SAVE",G.BLUR="BLUR",G.CAPTCHA="CAPTCHA",G.CLICK="CLICK",G.COOKIE="COOKIE",G.COPY="COPY",G.DIALOG="DIALOG",G.DRAG="DRAG",G.ELEMENT_CHECK="ELEMENT_CHECK",G.FILE_UPLOAD="FILE_UPLOAD",G.FOCUS="FOCUS",G.GO_BACK="GO_BACK",G.GO_FORWARD="GO_FORWARD",G.HOVER="HOVER",G.JAVASCRIPT="JAVASCRIPT",G.LOCAL_STORAGE="LOCAL_STORAGE",G.MOUSE_DRAG="MOUSE_DRAG",G.NAVIGATE="NAVIGATE",G.NEW_TAB="NEW_TAB",G.PAGE_CHECK="PAGE_CHECK",G.PASTE="PASTE",G.PRESS="PRESS",G.KEY_DOWN="KEY_DOWN",G.KEY_UP="KEY_UP",G.REFRESH="REFRESH",G.REQUEST="REQUEST",G.GRAPHQL_REQUEST="GRAPHQL_REQUEST",G.SCROLL_DOWN="SCROLL_DOWN",G.SCROLL_UP="SCROLL_UP",G.SCROLL_LEFT="SCROLL_LEFT",G.SCROLL_RIGHT="SCROLL_RIGHT",G.SELECT_OPTION="SELECT_OPTION",G.SWITCH_TAB="TAB",G.TYPE="TYPE",G.VISUAL_DIFF="VISUAL_DIFF",G.WAIT="WAIT",G.WAIT_FOR_URL="WAIT_FOR_URL",G.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",G.AWAIT_LISTENER="AWAIT_LISTENER",G.RECORD_REQUESTS="RECORD_REQUESTS",G.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",G.SET_HEADER="SET_HEADER",G.MOCK_ROUTE="MOCK_ROUTE",G.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",G.OFFLINE_MODE="OFFLINE_MODE",G.SUCCESS="SUCCESS",G))(Ge||{});Tw(w);var V=w.object({thoughts:w.string().optional(),id:w.string().uuid().describe("unique identifier to this step, used for step cache")}),qt=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"}),zt=w.object({target:tr}).optional().openapi({ref:"SingleTargetCache"});function Am(t){return zt.safeParse(t).success}var Ui=w.object({loadTimeout:w.number().int().max(60).optional().describe("Max seconds for the page to load")}),uc=V.merge(Ui).merge(w.object({type:w.literal("NAVIGATE"),url:w.string()})).openapi({ref:"NavigateCommand"}),Bi=qt.merge(w.object({cache:zt})),or=V.merge(Bi.merge(w.object({target:ht.optional(),type:w.literal("SCROLL_UP"),deltaY:w.number().optional()}))).openapi({ref:"ScrollUpCommand"}),ar=V.merge(Bi.merge(w.object({target:ht.optional(),type:w.literal("SCROLL_DOWN"),deltaY:w.number().optional()}))).openapi({ref:"ScrollDownCommand"}),vo=V.merge(Bi.merge(w.object({target:ht.optional(),type:w.literal("SCROLL_LEFT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ao=V.merge(Bi.merge(w.object({target:ht.optional(),type:w.literal("SCROLL_RIGHT"),deltaX:w.number().optional()}))).openapi({ref:"ScrollRightCommand"}),YN=w.discriminatedUnion("type",[or,ar,vo,Ao]).openapi({ref:"AllScrollCommands"}),ww=V.merge(w.object({type:w.literal("DIALOG"),action:w.union([w.literal("ACCEPT"),w.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Ew=V.merge(w.object({type:w.literal("WAIT"),delay:w.number()})).openapi({ref:"WaitCommand"}),Rw=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")}),mc=V.extend({type:w.literal("WAIT_FOR_URL"),matcher:cc}).merge(Rw).openapi({ref:"WaitUrlCommand"}),Cw=V.merge(Ui).merge(w.object({type:w.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),vw=V.merge(w.object({type:w.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Aw=V.merge(w.object({type:w.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),xw=V.extend({type:w.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Iw=V.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"}),pc=V.merge(qt).extend({type:w.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),Pw=V.extend({type:w.literal("COPY"),value:w.string()}).openapi({ref:"CopyCommand"}),Mw=V.extend({type:w.literal("PASTE")}).openapi({ref:"PasteCommand"}),Lw=V.merge(Di).extend({type:w.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Or=V.merge(qt).extend({type:w.literal("CLICK"),target:ht,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:zt,relativePosition:w.object({x:w.number(),y:w.number()}).optional()}).openapi({ref:"ClickCommand"}),gc=w.object({fromTarget:tr.optional(),toTarget:tr.optional()}),Ca=V.merge(qt).merge(w.object({type:w.literal("DRAG"),fromTarget:ht,toTarget:ht,steps:w.number().optional(),hoverSeconds:w.number().optional().describe("Seconds to hover the object before dropping"),cache:gc.optional()})).openapi({ref:"DragCommand"}),va=V.merge(qt).merge(w.object({type:w.literal("MOUSE_DRAG"),target:ht.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:zt})).openapi({ref:"MouseDragCommand"}),Nr=V.merge(qt).merge(w.object({type:w.literal("HOVER"),target:ht,cache:zt})).openapi({ref:"HoverCommand"}),Aa=V.merge(qt).merge(w.object({type:w.literal("FOCUS"),target:ht,cache:zt})).openapi({ref:"FocusCommand"}),xa=V.merge(qt).extend({type:w.literal("BLUR"),target:ht.optional(),cache:zt}).openapi({ref:"BlurCommand"}),Ow=w.object({type:w.literal("URL"),url:w.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Nw=w.object({type:w.literal("USER_FILE"),name:w.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),kw=V.extend({type:w.literal("FILE_UPLOAD"),fileSource:w.discriminatedUnion("type",[Ow,Nw]),filename:w.string().optional()}).openapi({ref:"FileUploadCommand"}),_w=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()})]),kr=V.merge(qt).extend({type:w.literal("SELECT_OPTION"),target:ht,cache:zt,choice:_w.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),hc=w.union([w.literal("MULTIMODAL"),w.literal("VISION_ONLY")]),xo=V.merge(w.object({type:w.literal("AI_ASSERTION"),assertion:w.string(),disableCache:w.boolean().optional(),iframeUrl:w.string().optional(),contextChoice:hc.optional(),timeout:w.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:lc.optional()})).openapi({ref:"AIAssertionCommand"}),Tn=5,fc=600,_r=V.merge(qt).extend({type:w.literal("ELEMENT_CHECK"),target:ht,assertion:Rm,cache:zt.or(lc).optional(),timeout:w.number().int().min(0).max(fc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Sc=V.extend({type:w.literal("PAGE_CHECK"),assertion:Cm,iframeUrl:w.string().optional().describe("url or url regex for the iframe"),timeout:w.number().int().min(0).max(fc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Dw=V.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"}),Fw=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()}),xm=25,Dr=V.merge(qt).merge(Fw).extend({type:w.literal("TYPE"),target:ht.optional(),value:w.string(),cache:zt}).openapi({ref:"TypeCommand"}),yc=V.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"}),Uw=V.merge(w.object({type:w.literal("KEY_DOWN"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyDownCommand"}),Bw=V.merge(w.object({type:w.literal("KEY_UP"),value:w.string(),convertMeta:w.boolean().optional()})).openapi({ref:"KeyUpCommand"}),zw=w.object({type:w.literal("SUBSTRING"),substring:w.string()}),Hw=w.object({type:w.literal("REGEX"),pattern:w.string()}),$w=w.object({type:w.literal("INDEX"),index:w.coerce.string()}),jw=w.discriminatedUnion("type",[zw,Hw,$w]),Gw=V.merge(Ui).merge(w.object({type:w.literal("TAB"),action:jw})).openapi({ref:"TabCommand"}),bc=V.merge(Ui).merge(w.object({type:w.literal("NEW_TAB"),url:w.string()})).openapi({ref:"NewTabCommand"}),Ww=V.merge(w.object({type:w.literal("COOKIE"),value:w.string()})).openapi({ref:"CookieCommand"}),Vw=V.merge(w.object({type:w.literal("LOCAL_STORAGE"),key:w.string(),value:w.string()})).openapi({ref:"LocalStorageCommand"}),qw=V.extend({type:w.literal("REQUEST")}).merge(_i).openapi({ref:"RequestCommand"}),Kw=V.extend({type:w.literal("GRAPHQL_REQUEST")}).merge(vm).openapi({ref:"GraphQLRequestCommand"}),Yw=V.merge(w.object({type:w.literal("SUCCESS"),condition:xo.optional()})).openapi({ref:"SuccessCommand"}),Xw=V.merge(w.object({type:w.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Jw=w.object({data:w.string().describe("location at which to find a jpg"),width:w.number(),height:w.number()}),Ia=V.merge(qt).merge(w.object({type:w.literal("VISUAL_DIFF"),threshold:w.number().optional().describe("default 0.1"),target:ht.optional(),screenshot:Jw.optional(),cache:zt})).openapi({ref:"VisualDiffCommand"}),Qw=V.merge(w.object({type:w.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Ra,key:w.string()})).openapi({ref:"RegisterRequestListenerCommand"}),Zw=V.merge(w.object({type:w.literal("AWAIT_LISTENER"),key:w.string(),timeout:w.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),eE=V.merge(w.object({type:w.literal("RECORD_REQUESTS"),requestMatcher:Ra,key:w.string()})).openapi({ref:"RecordRequestsCommand"}),tE=V.merge(w.object({type:w.literal("GET_RECORDED_REQUESTS"),key:w.string()})).openapi({ref:"GetRecordedRequestsCommand"}),nE=V.merge(w.object({type:w.literal("SET_HEADER"),name:w.string(),value:w.string(),requestMatcher:Ra.optional()})).openapi({ref:"SetHeaderCommand"}),rE=V.merge(w.object({type:w.literal("MOCK_ROUTE"),requestMatcher:Ra,responseGenerator:w.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:w.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:w.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),oE=V.merge(w.object({type:w.literal("REMOVE_ROUTE_MOCK"),key:w.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),aE=V.merge(w.object({type:w.literal("OFFLINE_MODE"),enable:w.boolean()})).openapi({ref:"OfflineModeCommand"}),Im=w.discriminatedUnion("type",[Or,Dr,yc,Uw,Bw,kr,uc,ar,or,xo,Nr,Ew,Yw]),iE=w.discriminatedUnion("type",[Dw,Iw,xw,pc,Ww,Pw,ww,Ca,_r,kw,vw,Aw,Lw,Vw,va,bc,Sc,Mw,Cw,qw,Kw,vo,Ao,Gw,Ia,Aa,xa,mc,Qw,Zw,eE,tE,nE,rE,oE,aE]),Io=w.discriminatedUnion("type",[...Im.options,...iE.options]).openapi({ref:"Command"}),zi=w.discriminatedUnion("type",[...Im.options,Xw]);function Fn(t){let e;switch(t){case"PASTE":case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:fe(),type:t};break;case"AUTH_LOAD":{e={id:fe(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:fe(),type:t,goal:""};break;case"DIALOG":e={id:fe(),type:t,action:"DISMISS"};break;case"DRAG":e={id:fe(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:fe(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:fe(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:fe(),type:t,delay:1};break;case"BLUR":e={id:fe(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:fe(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:fe(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:fe(),type:t,value:""};break;case"SELECT_OPTION":e={id:fe(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:fe(),type:t,url:""};case"TAB":e={id:fe(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:fe(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:fe(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:fe(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:fe(),type:t,code:""};break;case"AI_ASSERTION":e={id:fe(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:fe(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:fe(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:fe(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:fe(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:fe(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:fe(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:fe(),type:t,key:""};break}case"SET_HEADER":{e={id:fe(),type:t,name:"",value:""};break}case"MOCK_ROUTE":{e={id:fe(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:fe(),type:t};break}case"OFFLINE_MODE":{e={id:fe(),type:t,enable:!0};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Pm(t){switch(t.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{z as sE}from"zod";var ek=sE.discriminatedUnion("type",[xa,pc,Or,Ca,Aa,Nr,va,or,ar,vo,Ao,kr,Dr,Ia,_r]);function Mm(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as lE}from"zod";import{z as ir}from"zod";function Pa(t){return ir.object({key:ir.string(),testId:ir.string().optional(),moduleId:ir.string().optional(),organizationId:ir.string(),value:t})}function Ma(t){return Pa(t).extend({uniqueKey:ir.string()})}function Hi(t){return ir.record(ir.string(),Ma(t))}var Ct={type:!0,cache:!0},Un=lE.discriminatedUnion("type",[xo.pick(Ct),xa.pick(Ct),Or.pick(Ct),Ca.pick(Ct),_r.pick(Ct),Aa.pick(Ct),Nr.pick(Ct),va.pick(Ct),or.pick(Ct),ar.pick(Ct),vo.pick(Ct),Ao.pick(Ct),kr.pick(Ct),Dr.pick(Ct),Ia.pick(Ct)]),$i=Object.values(Ge).filter(t=>Un.options.some(e=>e.shape.type.safeParse(t).success));Io.options.forEach(t=>{if("target"in t.shape&&!$i.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function Lm(t){return $i.includes(t.type)}var Om=Pa(Un),Nm=Ma(Un),lk=Hi(Un);import{z as Tc}from"zod";import{extendZodWithOpenApi as uE}from"zod-openapi";import{z as km}from"zod";import{extendZodWithOpenApi as cE}from"zod-openapi";import{z as Fr}from"zod";var Kt=Fr.object({index:Fr.number().optional().describe("global index within a test (in-order traversal)"),id:Fr.string(),skipped:Fr.boolean().optional(),envKey:Fr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Fr.boolean().optional(),retries:Fr.number().optional()});cE(km);var dE=Kt.extend({type:km.literal("PRESET_ACTION")}),Ht=dE.extend({command:Io}).openapi({ref:"PresetAction"});uE(Tc);var Ur=Kt.extend({type:Tc.literal("AI_ACTION"),text:Tc.string(),steps:Ht.array().optional()}).openapi({ref:"AIAction"});import{z as vt}from"zod";import{z as ji}from"zod";import{extendZodWithOpenApi as mE}from"zod-openapi";mE(ji);var Po=Kt.extend({type:ji.literal("AI_ACTION_DYNAMIC"),text:ji.string(),retries:ji.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as _m}from"zod";var wc=Kt.extend({type:_m.literal("CONDITIONAL"),skipped:_m.boolean().optional()});import{z as se}from"zod";var pE=se.object({cacheKey:se.string(),cacheExpiryMs:se.number()}),Ec=Kt.extend({id:se.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:se.record(se.string()).optional(),cacheConfig:pE.optional()}),cn=Ec.extend({type:se.literal("MODULE"),moduleId:se.string().uuid()}),gE=se.union([cn.pick({type:!0,moduleId:!0}),se.record(se.unknown())]),hE=se.object({type:se.literal("URL_REGEX"),regex:se.string()}),fE=se.object({type:se.literal("PAGE_CHECK"),substring:se.string()}),Rc=se.object({cacheInvalidation:se.discriminatedUnion("type",[fE,hE]).optional()}),Ot=se.object({moduleId:se.string().uuid(),name:se.string(),description:se.string().nullish(),enabled:se.boolean().nullish(),parameters:se.string().array().nullish(),defaultParameters:se.record(se.string(),se.string()).nullish(),parameterEnums:se.record(se.string(),se.string().array()).nullish(),defaultCacheKey:se.string().nullish(),defaultCacheTtl:se.number().nullish(),defaultCacheAllInvocations:se.boolean().nullish(),autoAuth:se.boolean().nullish(),advanced:Rc.nullish()});import{z as Yt}from"zod";var Cc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(Cc||{});var SE=Yt.discriminatedUnion("type",[Yt.object({type:Yt.literal("NAVIGATE_URL"),url:Yt.string().url()}),Yt.object({type:Yt.literal("GO_TO_SECTION_START")})]),yE=Yt.object({trigger:Yt.nativeEnum(Cc).optional(),attempts:Yt.number().int().optional(),restartBehavior:SE}),La=Kt.extend({type:Yt.literal("SECTION"),description:Yt.string().describe("user provided goal of what the section should accomplish"),plan:Yt.string().array().optional(),autohealingConfig:yE.optional()});var Dm=Ot.merge(Ec).extend({type:vt.literal("RESOLVED_MODULE"),steps:vt.lazy(()=>We.array())}),Oa=Ot.extend({steps:vt.lazy(()=>We.array())}),vc=La.extend({steps:vt.lazy(()=>Ie.array())}),bE=La.extend({steps:vt.lazy(()=>We.array())}),Br=wc.extend({blocks:vt.object({assertion:vt.lazy(()=>Ht),steps:vt.lazy(()=>Ie.array())}).array(),elseSteps:vt.lazy(()=>Ie.array().optional())}),TE=wc.extend({blocks:vt.object({assertion:vt.lazy(()=>Ht),steps:vt.lazy(()=>We.array())}).array(),elseSteps:vt.lazy(()=>We.array().optional())}),Ie=vt.discriminatedUnion("type",[Ht,Ur,Po,cn,Br,vc]),We=vt.discriminatedUnion("type",[Ht,Ur,Po,Dm,TE,bE]);import{z as Xt}from"zod";var wE=Xt.object({steps:Ie.array(),beforeSteps:Ie.array().nullish(),afterSteps:Ie.array().nullish()}),Mo=Xt.object({steps:We.array(),beforeSteps:We.array().nullish(),afterSteps:We.array().nullish()}),zr=Xt.object({steps:Xt.record(Xt.string(),Xt.unknown()).array(),beforeSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish(),afterSteps:Xt.record(Xt.string(),Xt.unknown()).array().nullish()});var le="1.0.21";var Fm=F.object({phrase:F.string()}),Ac=F.object({thoughts:F.string().optional(),result:F.union([F.literal("NOT_FOUND"),F.string(),F.number(),F.array(F.unknown()),F.record(F.unknown(),F.unknown()),F.unknown()])}),q_=F.object({text:F.string()}),Um=F.object({thoughts:F.string(),review:F.string().optional(),id:F.number().int(),updatedMemory:oc.optional()});var Gi=(p=>(p.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",p.FEW_WORDS="FEW_WORDS",p.STYLE_TAG="STYLE_TAG",p.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",p.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",p.NONE="NONE",p.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",p.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",p.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",p.PREFER_ASSERTION="PREFER_ASSERTION",p.HTML_ELEMENTS="HTML_ELEMENTS",p.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",p.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",p))(Gi||{});var Bm=F.object({thoughts:F.string(),category:F.nativeEnum(Gi)}),EE=F.discriminatedUnion("op",[F.object({op:F.literal("replace"),path:F.string(),value:F.string()}),F.object({op:F.literal("add"),path:F.string(),value:F.string()}),F.object({op:F.literal("remove"),path:F.string()})]),K_=F.object({thoughts:F.string(),patches:EE.array()}),RE=[F.literal("add"),F.literal("replace"),F.literal("remove")],CE=F.object({op:F.union(RE),path:F.string(),value:We.optional()}),zm=F.object({patches:CE.array(),thoughts:F.string()}),xc=(r=>(r.LEGITIMATE="LEGITIMATE",r.RECOVERABLE="RECOVERABLE",r.INELIGIBLE="INELIGIBLE",r))(xc||{}),Hm=F.object({thoughts:F.string(),scenario:F.nativeEnum(xc),instructions:F.string().nullish()}),$m=F.object({reasoning:F.string(),scenario:F.string(),patch:F.null().optional()}),Y_=F.object({thoughts:F.string(),evaluation:F.number().min(1).max(10)}),X_=F.object({observations:F.string(),reasoning:F.string(),command:zi});var Ic=F.object({summary:F.string(),reasoning:F.string(),evaluation:F.discriminatedUnion("type",[F.object({type:F.literal("DONE")}),F.object({type:F.literal("RIGHT_TRACK")}),F.object({type:F.literal("WRONG_TRACK"),feedback:F.string()}),F.object({type:F.literal("IMPOSSIBLE")})])});import{z as N}from"zod";import*as te from"zod";var nD=te.object({thoughts:te.string().optional().describe("only provided if a description was provided"),target:tr.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")}),Wi=te.union([te.literal("ELEMENT_CHECK"),te.literal("NEGATED_CHECK"),te.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),te.literal("SELECT_OPTION"),te.literal("TYPE")]);function Hr(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Na=(i=>(i.USER_SELECTOR="USER_SELECTOR",i.CSS_SELECTOR="CSS_SELECTOR",i.HYBRID_SELECTOR="HYBRID_SELECTOR",i.HTML_DISTANCE="HTML_DISTANCE",i.TEMPLATE_MATCHING="TEMPLATE_MATCHING",i.AUTO_FRAME="AUTO_FRAME",i))(Na||{}),Lo=te.object({matched:te.boolean(),reason:te.string().optional().describe("Human understandable description"),logs:te.string().array().optional().describe("Logs for debugging")}),vE=Lo.extend({type:te.literal("USER_SELECTOR")}),AE=Lo.extend({type:te.literal("CSS_SELECTOR"),selectors:te.string().array()}),xE=Lo.extend({type:te.literal("HYBRID_SELECTOR")}),IE=Lo.extend({type:te.literal("HTML_DISTANCE"),distance:te.number().optional(),closestElement:te.string().optional(),savedElement:te.string().optional()}),PE=Lo.extend({type:te.literal("TEMPLATE_MATCHING"),elementImageUrl:te.string().url()}),ME=Lo.extend({type:te.literal("AUTO_FRAME"),logs:te.string().array().optional()}),jm=te.discriminatedUnion("type",[vE,AE,xE,IE,PE,ME]);import{z as Fa}from"zod";import{z as jE}from"zod";import*as W from"zod";import{extendZodWithOpenApi as _E}from"zod-openapi";import{cloneDeep as ka}from"lodash-es";import Ym from"truncate-json";import*as Gr from"zod";import{extendZodWithOpenApi as LE}from"zod-openapi";import{z as St}from"zod";import{z as Pe}from"zod";var Pc=Pe.object({autoFollowNewTabs:Pe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Pe.union([Pe.boolean(),Pe.literal("inputs-only")]).optional(),ignoreHrefForCaching:Pe.boolean().optional(),disableSecondaryCacheResolution:Pe.boolean().optional(),hybridSelectorMode:Pe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Pe.boolean().optional(),visualActions:Pe.boolean().optional(),autoExpandIframes:Pe.boolean().optional(),disableHtmlSnapshots:Pe.boolean().optional(),importantAttributes:Pe.string().array().optional(),importantClasses:Pe.string().array().optional(),importantStyles:Pe.string().array().optional()});var Gm=1e4,Wm=6e4,$r=Pc.extend({pageLoadTimeoutMs:Pe.number().optional().refine(t=>t===void 0||t<=Wm&&t>=-1,{message:`Page load timeout must be between 0 and ${Wm/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Pe.number().optional().refine(t=>t===void 0||t<=Gm&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${Gm/1e3} seconds`}),localChromeExtensionPaths:Pe.string().array().optional(),extraHeaders:Pe.record(Pe.string(),Pe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Pe.string().optional(),disableGpu:Pe.boolean().optional(),bustCacheOnBoundingBoxChange:Pe.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:Pe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Pe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var it="BASE_URL",Vi="CURRENT_URL",jr="ENV_NAME",Oo="TEST_NAME",lD={[it]:"https://www.google.com"},Vm=St.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),qm=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.string().describe("variable value"))}),Km=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.unknown().describe("variable value")),browser:$r.optional()});var cD=St.object({name:St.string(),variables:St.record(St.string().describe("variable name"),St.unknown().describe("variable value"))});LE(Gr);var Mc=Gr.object({env:Gr.record(Gr.unknown())}).openapi({ref:"TestContextSnapshot"}),OE="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",NE=[it,jr,Oo],Xm=[Vi,it,jr,Oo],Jt=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,n=void 0,r={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:n,variablesFromEnvironment:r})}static fromSnapshot({snapshot:e,environmentVariables:n}){let r=e.env[it]??"about:blank",o=e.env[Vi]??"about:blank",a=e.env[jr],i=e.env[Oo],s={};for(let[l,d]of Object.entries(e.env))Xm.includes(l)||(n??{})[l]===void 0&&(s[l]=d);return new t({baseUrl:r,currentUrl:o,dynamicVariables:s,envName:a,testName:i,variablesFromEnvironment:n??{}})}setEnvVariables(e){let n=ka(e);this.env=Object.assign(this.env,n)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,n){this.varsFromMomenticEnvironment[e]=n}getVariable(e){return this.env[e]}setVariable(e,n){NE.includes(e)||(this.env[e]=n)}getEnvName(){return this.env[jr]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ka(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>Xm.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,OE]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:a}=Ym(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(a)}catch{e.env[r]=void 0}}let{jsonString:n}=Ym(JSON.stringify(e.env),25e3);try{e.env=JSON.parse(n)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Vi]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=ka(e.variablesFromEnvironment),this.setMomenticSystemVariable(it,e.baseUrl),e.envName&&this.setMomenticSystemVariable(jr,e.envName),e.testName&&this.setMomenticSystemVariable(Oo,e.testName)}getDynamicVariablesCopy(){return ka(this.env)}getVariablesFromEnvironmentCopy(){return ka(this.varsFromMomenticEnvironment)}};var we=(a=>(a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.RUNNING="RUNNING",a.IDLE="IDLE",a.CANCELLED="CANCELLED",a))(we||{}),qi=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))(qi||{});import{z as wn}from"zod";import{extendZodWithOpenApi as kE}from"zod-openapi";kE(wn);var pe=(d=>(d.AI_PROVIDER="AIProviderError",d.USER_INFRA="UserInfrastructureError",d.ACTION_FAILURE="ActionFailureError",d.ASSERTION_FAILURE="AssertionFailureError",d.CONFIG_ERROR="UserConfigurationError",d.WEB_AGENT_PLATFORM="InternalWebAgentError",d.UNKNOWN_PLATFORM="InternalPlatformError",d.JOB_TIMEOUT="JobTimeoutError",d.CONCURRENCY_ERROR="ConcurrencyError",d.UNKNOWN="UnknownError",d))(pe||{});var Jm=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Ki={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",ConcurrencyError:"Concurrency error"},No={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.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},Lc=wn.object({reason:wn.nativeEnum(pe),previousStepsDescription:wn.array(wn.string()).optional(),summary:wn.string(),rootCause:wn.string().optional()}).openapi({ref:"TestResultClassification"}),Yi=wn.object({errorMessage:wn.string(),errorStack:wn.string().optional(),classification:Lc.optional()}).openapi({ref:"TestFailureDetails"});_E(W);var Oc=W.object({beforeUrl:W.string().optional(),afterUrl:W.string().optional(),message:W.string().optional(),beforeSnapshot:W.string().optional(),afterSnapshot:W.string().optional(),startedAt:W.coerce.date(),finishedAt:W.coerce.date()}),DE=Oc.extend({viewport:W.object({height:W.number(),width:W.number()}).nullish(),status:W.nativeEnum(qi),message:W.string().optional(),elementInteracted:W.string().optional()}),Wr=Oc.extend({status:W.nativeEnum(we),message:W.string().optional(),data:W.unknown().optional(),beforeTestContext:Mc.optional(),afterTestContext:Mc.optional(),failureReason:W.nativeEnum(pe).optional(),details:W.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"}),Nc=(n=>(n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.ATTEMPTED="ATTEMPTED",n))(Nc||{}),Xi=Wr.merge(Ht).extend({results:DE.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:W.lazy(()=>rt.array()).optional(),failureRecoveryStatus:W.object({type:W.nativeEnum(Nc),message:W.string()}).optional()}),FE=Wr.merge(Ur).extend({results:W.lazy(()=>Xi.array()),previousAttempts:W.lazy(()=>rt.array()).optional()}),UE=Wr.merge(Po).extend({results:W.lazy(()=>Xi.array()),previousAttempts:W.lazy(()=>rt.array()).optional()}),BE=Wr.merge(cn).extend({moduleName:W.string().optional(),results:W.lazy(()=>rt.array()),previousAttempts:W.lazy(()=>rt.array()).optional()}),zE=Wr.merge(Br).extend({assertion:Xi.optional(),results:W.lazy(()=>rt.array()).describe("results for the block actually executed"),previousAttempts:W.lazy(()=>rt.array()).optional()}),HE=Wr.merge(La).extend({results:W.lazy(()=>rt.array()),healingAttempts:W.lazy(()=>rt.array().array()).optional(),previousAttempts:W.lazy(()=>rt.array()).optional()}),rt=W.discriminatedUnion("type",[FE,UE,Xi,BE,zE,HE]),Ji=Wr.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),$E=Oc.extend({index:W.number().optional(),description:W.string(),pageState:W.string().optional(),elementInteracted:W.string().optional(),startedAt:W.coerce.date().or(W.string()).optional().catch(void 0),finishedAt:W.coerce.date().or(W.string()).optional().catch(void 0)}),Qi=$E.extend({beforeScreenshot:W.string().optional(),afterScreenshot:W.string().optional()});var kc=jE.object({results:rt.array().describe("main results"),beforeResults:rt.array().optional(),afterResults:rt.array().optional()}),_a=kc.partial();import{z as U}from"zod";import{extendZodWithOpenApi as YE}from"zod-openapi";var ko=(n=>(n.WEB="WEB",n.ANDROID="ANDROID",n))(ko||{});import{isValidCron as GE}from"cron-validator";import{z as ae}from"zod";import{z as _c}from"zod";var Bn=(r=>(r.CHROMIUM="Chromium",r.GOOGLE_CHROME="Google Chrome",r.CHROME_FOR_TESTING="Chrome for Testing",r))(Bn||{});var Zi=_c.object({width:_c.number().min(200).max(1e4),height:_c.number().min(200).max(1e4)}),Qm={"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}},FD=Object.keys(Qm);var Nt=Qm["Desktop Large"],_o="en-us",Do="America/Los_Angeles";var Fo={latitude:37.7749,longitude:-122.4194};var Zm=["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 ep=2e3,es=$r.extend({browserType:ae.nativeEnum(Bn).optional(),slowMoMs:ae.number().optional().refine(t=>t===void 0||t<=ep&&t>=-1,{message:`Slow motion must be between 0 and ${ep} milliseconds`}),basicAuthorization:ae.object({username:ae.string().optional(),password:ae.string().optional()}).optional(),geolocation:ae.object({latitude:ae.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:ae.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:ae.boolean().optional(),locale:ae.string().optional(),timezone:ae.enum(Zm).optional(),colorScheme:ae.enum(["light","dark"]).optional()}),tp=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],Dc=ae.object({useMemory:ae.boolean().optional(),failureRecovery:ae.boolean().optional().describe("undefined means inherit org settings")}),WE=Dc.extend({disableAICaching:ae.boolean().optional(),failureRecoveryInstructions:ae.string().optional()}),VE=ae.object({viewport:Zi.optional()}),Vr=VE.merge(WE).merge(es),Uo=ae.object({cron:ae.string().refine(t=>GE(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:ae.boolean().default(!1),env:ae.string().optional(),timeZone:ae.string().default("America/Los_Angeles"),jobKey:ae.string().optional()}),Bo=ae.object({onSuccess:ae.boolean().default(!1),failureMessage:ae.string().optional(),onFailure:ae.boolean().default(!0),successMessage:ae.string().optional()}),qE=ae.object({name:ae.string(),required:ae.boolean().optional(),defaultValue:ae.string().describe("this is not optional because we need a value when the editor is first loaded")}),ts=qE.array(),KE=ae.object({name:ae.string(),value:ae.string()}),np=KE.array(),ns=ae.object({name:ae.string(),default:ae.boolean().optional(),fixtures:Vm.array().optional()});YE(U);var Qt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ce=(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))(ce||{}),rs=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(rs||{});var Xe=U.string().pipe(U.coerce.date()).or(U.date()),Da=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(ko).optional().default("WEB"),createdAt:Xe,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:Xe.or(U.null()),startedAt:Xe.or(U.null()),updatedAt:Xe.nullish(),finishedAt:Xe.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(rs).nullish(),status:U.nativeEnum(ce),trigger:U.nativeEnum(Qt),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(ce),startedAt:Xe.or(U.null()),finishedAt:Xe.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(pe).nullish(),failureDetails:Yi.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),XE={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},os=Da.pick({...XE,test:!0}),rp=Da.omit({failureReason:!0,failureDetails:!0,test:!0}),Fc=Da.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:Vr.nullish()}).nullish()}).merge(kc),op=t=>t.includes("PASSED")&&t.includes("FAILED");var JE=Fa.object({id:Fa.string().uuid(),startedAt:Xe.or(Fa.null()),finishedAt:Xe.or(Fa.null()),status:Fa.nativeEnum(ce)}).merge(_a),aF=JE.array();var as=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(as||{});import{z as Je}from"zod";var QE=Je.object({id:Je.string(),status:Je.nativeEnum(ce),trigger:Je.nativeEnum(Qt),createdAt:Xe,startedAt:Xe.nullish(),finishedAt:Xe.nullish(),gitCommitSha:Je.string().nullish(),gitCommitShaShort:Je.string().nullish(),gitCommitTimestamp:Xe.nullish(),gitBranchName:Je.string().nullish(),gitOriginUrl:Je.string().nullish(),gitCommitMessage:Je.string().nullish(),gitCommitAuthorName:Je.string().nullish(),githubRepository:Je.string().nullish(),gitlabProjectPath:Je.string().nullish(),pipelineId:Je.string().nullish(),cliVersion:Je.string().nullish(),labels:Je.string().array().optional(),suite:Je.object({id:Je.string(),name:Je.string()}).nullish(),runs:Je.object({status:Je.nativeEnum(ce)}).array()}).openapi({ref:"RunGroup"}),ap=QE.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:os.array()});import{z as st}from"zod";var ZE=st.object({type:st.literal("TARGETING"),name:st.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:jm.array(),pageState:st.string().optional(),targetSource:st.nativeEnum(er).optional(),targetUpdateTime:st.string().optional()}),eR=st.object({type:st.literal("AI_LOCATION"),matched:st.boolean(),pageState:st.string().optional(),ragUsed:st.boolean().optional(),thoughts:st.string().optional()}),tR=st.object({type:st.literal("ASSERTION"),relevantElementsSerialized:st.string().array().optional(),pageState:st.string().optional(),ragUsed:st.boolean().optional()}),ip=st.discriminatedUnion("type",[ZE,eR,tR]);function is(){return{details:[]}}import{z as qe}from"zod";var nR=qe.object({id:qe.string(),name:qe.string()}),bF=nR.merge(qe.object({createdAt:Xe,createdBy:qe.string(),schedule:Uo,notification:Bo,environment:qe.object({name:qe.string()}).nullish(),beforeTests:qe.object({id:qe.string()}).array().nullish(),afterTests:qe.object({id:qe.string()}).array().nullish()})),sp=qe.object({id:qe.string().uuid(),orgId:qe.string(),createdAt:Xe,startedAt:Xe.or(qe.null()),finishedAt:Xe.or(qe.null()),status:qe.nativeEnum(ce),trigger:qe.nativeEnum(Qt),suite:qe.object({id:qe.string(),name:qe.string()}).nullish(),runs:Da.array()}),TF=sp.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),lp=sp.extend({runs:os.array()});import{z as Zt}from"zod";import{cloneDeep as RF}from"lodash-es";import{z as Se}from"zod";var PF=Se.object({thoughts:Se.string(),subGoals:Se.object({instruction:Se.string()}).array()}),MF=Se.object({thoughts:Se.string(),newPlanMarkdown:Se.string()}),LF=Se.object({thoughts:Se.string(),correct:Se.boolean(),failedActionIndex:Se.number().optional()}),rR=Se.object({type:Se.literal("PLANNING"),beforePlan:Se.string(),goalDecision:Se.string(),thoughts:Se.string()}),oR=Se.object({type:Se.literal("RUNNING"),stepDisplayName:Se.string(),status:Se.nativeEnum(we),results:rt.array()}),aR=Se.object({type:Se.literal("REVISING"),beforePlan:Se.string(),afterPlan:Se.string(),errString:Se.string(),diffs:Se.string(),thoughts:Se.string()}),iR=Se.object({type:Se.literal("SYSTEM"),message:Se.string()}),sR=Se.discriminatedUnion("type",[rR,oR,aR,iR]),cp=sR.array();var DF=Zt.object({id:Zt.string(),scheduledAt:Zt.coerce.date().nullable(),startedAt:Zt.coerce.date().nullable(),finishedAt:Zt.coerce.date().nullable(),status:Zt.nativeEnum(ce),history:cp.nullable(),testPlan:Zt.object({id:Zt.string(),name:Zt.string()}).nullable(),test:Zt.object({id:Zt.string(),name:Zt.string()}).nullable()});import{z as At}from"zod";var Uc=At.object({content:At.string(),ids:At.string().array(),tokenLength:At.number()}),lR=At.object({chunks:Uc.array()}),ZF=At.object({ids:At.string().array(),score:At.number(),tokenLength:At.number()}),e0=lR.extend({description:At.string().describe("Input to pass to RAG engine"),tokenLimit:At.number()}),dp=At.object({ids:At.number().array()}),up=At.object({indices:At.number().array()});var kt=N.object({disableCache:N.boolean().optional(),useMemory:N.boolean().optional(),loggerTags:N.record(N.string(),N.string()).optional(),langfuseSessionId:N.string().optional(),agentConfigVersion:N.string().optional()}),l0=kt.extend({chunks:Uc.array(),description:N.string().describe("Input to pass to AI"),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),softTokenLimit:N.number(),hardTokenLimit:N.number()}),cR=N.object({screenshotBase64AfterCommand:N.string(),urlAfterCommand:N.string(),serializedCommand:N.string(),elementInteracted:N.string().optional(),thoughts:N.string().optional()}),mp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),source:Wi.optional().catch(void 0),memory:N.discriminatedUnion("type",[Eo,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional()}),pp=N.object({target:N.string().or(N.number()),browserState:N.string().optional(),screenshot:N.string().optional(),boundingBox:N.object({x:N.number(),y:N.number(),height:N.number(),width:N.number()}).optional()}),gp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string().optional(),returnSchema:N.string().optional()}),dR=N.literal("NEGATED_CHECK"),hp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),url:N.string(),contextChoice:hc.optional(),memory:N.discriminatedUnion("type",[sc,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional(),source:dR.optional()}),fp=N.object({command:Io}),Bc=N.object({goal:N.string(),browserState:N.string(),startingScreenshot:N.string().optional(),screenshot:N.string(),url:N.string(),history:cR.array(),actionHint:N.string().optional(),lastError:N.string().optional()}),Sp=N.object({results:Qi.array(),errorMessage:N.string(),errorStack:N.string().optional()}),yp=N.object({results:Qi.array(),goal:N.string(),errorMessage:N.string()}),bp=N.object({failedResults:Qi.array(),nextStepsSerialized:N.string().array(),currentUrl:N.string(),currentPageState:N.string(),currentScreenshot:N.string(),customInstructions:N.string().optional(),testDescription:N.string().optional()}),c0=N.object({description:N.string(),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),excerpt:N.string()});import{z as Ua}from"zod";var m0=Ua.object({goal:Ua.string()}),Tp=Ua.object({keywords:Ua.array(Ua.string())});import{z as zc}from"zod";var ss=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(ss||{}),h0=zc.nativeEnum(ss),uR=zc.enum(["v1","v2"]),f0=uR.or(zc.string().describe("for people with special configurations"));import{z as Ue}from"zod";var wp=Ue.object({attributesRequired:Ue.array(Ue.string()).optional(),textRequired:Ue.boolean().optional(),boundsRequired:Ue.boolean().optional()}),mR=Ue.object({id:Ue.number(),thoughts:Ue.string(),requirements:wp.optional(),additionalElements:Ue.object({id:Ue.number(),requirements:wp}).array().optional()}),Ep=Ue.object({description:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),Rp=Ue.object({assertion:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),pR=Ue.object({thoughts:Ue.string(),result:Ue.boolean(),relevantElements:Ue.array(Ue.number()).optional()});var Cp=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as qr}from"zod";var vp=qr.object({id:qr.string().uuid(),skipped:qr.boolean().optional(),envKey:qr.string().optional().describe("key in the environment to save the result of this step to")}),Hc=vp.merge(_i).extend({type:qr.literal("REQUEST")}),$c=vp.merge(Di).extend({type:qr.literal("JAVASCRIPT")}),jc=qr.discriminatedUnion("type",[$c,Hc]);import{z as en}from"zod";import{z as Kr}from"zod";var gR=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Ce=t=>{let e=t.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var ls=Kr.string().min(1).max(255).superRefine((t,e)=>{try{Yr(t)}catch(n){return e.addIssue({code:Kr.ZodIssueCode.custom,message:n.message,fatal:!0}),Kr.NEVER}});function Yr(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(gR))throw new Error("Name cannot be a UUID. Please choose a different name.")}var cs=Kr.preprocess(t=>t===null?"":t,Kr.union([Kr.string().url(),Kr.literal("")])).optional();var Ap=en.object({id:en.string(),name:ls,description:en.string().optional().nullish(),baseUrl:cs.nullish(),schemaVersion:en.string(),advanced:en.unknown().optional(),retries:en.number(),envs:en.array(ns).nullish(),parameters:ts.nullish()}),hR=en.object({createdAt:en.coerce.date(),updatedAt:en.coerce.date(),schedule:Uo.nullish(),notification:Bo.nullish(),createdBy:en.string(),organizationId:en.string()}),fR=Ap.merge(hR),$0=fR.extend({steps:jc.array()}),j0=Ap.extend({steps:jc.array()});import{z as _t}from"zod";var xp=_t.object({startedAt:_t.coerce.date(),finishedAt:_t.coerce.date(),status:_t.nativeEnum(we),message:_t.string().optional(),data:_t.unknown().optional()}),SR=xp.merge($c).extend({type:_t.literal("JAVASCRIPT")}),yR=xp.merge(Hc).extend({type:_t.literal("REQUEST")}),bR=_t.discriminatedUnion("type",[SR,yR]),Ip=_t.object({startedAt:_t.coerce.date(),finishedAt:_t.coerce.date().nullish(),status:_t.nativeEnum(ce),results:bR.array(),failureReason:_t.string().nullish(),failureDetails:Yi.nullish()});import{z as Dt}from"zod";var TR=Dt.object({id:Dt.string(),organizationId:Dt.string(),createdAt:Dt.coerce.date(),updatedAt:Dt.coerce.date(),createdBy:Dt.string(),scheduledAt:Dt.coerce.date().nullish(),startedAt:Dt.coerce.date().nullish(),finishedAt:Dt.coerce.date().nullish(),status:Dt.nativeEnum(ce),trigger:Dt.nativeEnum(Qt),results:Ip.array().nullish(),apiTestName:Dt.string().nullish(),apiTestPath:Dt.string().nullish(),apiTestId:Dt.string().nullish()}),Z0=TR.pick({status:!0,startedAt:!0,finishedAt:!0});var Ba=(n=>(n.TestRun="test-run",n.CreditsUsed="credits-used",n))(Ba||{}),Pp=3;function wR(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function Gc(t){if(!wR(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Wc(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return Pp;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var zo=class{async reportBillableEvent(e,n,r){}async reportCreditsUsed(e,n,r,o){}};function Vc(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as ER,splitCookiesString as RR}from"set-cookie-parser";import{z as Te}from"zod";var qc=Te.object({name:Te.string(),value:Te.string(),url:Te.string().optional(),domain:Te.string().optional(),path:Te.string().optional(),expires:Te.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Te.boolean().optional(),secure:Te.boolean().default(!0),sameSite:Te.union([Te.literal("Strict"),Te.literal("Lax"),Te.literal("None")]).default("None")});function ds(t,e){let n=[],r=RR(t);for(let o of r){let a=ER(o,{decodeValues:!1});if(!a.name)throw new Error("Name missing from cookie");if(!a.value)continue;let i;if(a.sameSite){let d=a.sameSite.trim().toLowerCase();if(d==="strict")i="Strict";else if(d==="lax")i="Lax";else if(d==="none")i="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}a.httpOnly===void 0&&(a.httpOnly=!1),!a.path&&a.domain&&(a.path="/"),!a.domain&&e&&(a.domain=e);let s=qc.parse({...a,expires:a.expires?a.expires.getTime()/1e3:void 0,sameSite:i});n.push(s);let c=[s.name,...Object.keys(s)].map(d=>d.toLowerCase()),l=o.match(/\b(\S+)=([^;]*)/g);if(l)for(let d of l){let[u,m]=d.split("=");if(!u||!m)throw new Error(`Invalid key-value pair in cookie: ${d}`);c.includes(u.toLowerCase())||n.push({...s,name:u,value:m})}}return n}var CR=Te.object({origin:Te.string(),localStorage:Te.array(Te.object({name:Te.string(),value:Te.string()}))}),vR=Te.object({entries:Te.record(Te.string(),Te.array(Te.tuple([Te.unknown(),Te.unknown()]))),version:Te.number().optional()}),us=Te.object({cookies:qc.array().optional(),origins:CR.array().optional(),idb:Te.record(Te.string(),vR).optional().describe("key is db name")});function Mp(t,e){let n=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=qc.safeParse({name:r.key,...r});if(!o.success)return;let a=o.data;!a.domain&&!a.url&&(a.domain=e),n.push(a)}),n}import DR from"zod";import{v4 as wU}from"uuid";import{z as ye}from"zod";import*as Me from"zod";var Lp=Me.object({requiredText:Me.string().optional(),requiredAttributes:Me.record(Me.string(),Me.string()).optional(),requiredBounds:Me.boolean().optional()}),AR=Me.object({xPath:Me.string(),requirements:Lp.optional()}),xR=Me.object({type:Me.literal("NATIVE"),bounds:Me.number().array(),resolvedDescription:Me.string(),xPath:Me.string(),elementOnlySerializedXml:Me.string(),requirements:Lp.optional(),requiredRelatedElements:AR.array().optional()}),IR=Me.object({type:Me.literal("WEBVIEW"),resolvedDescription:Me.string(),xPath:Me.string(),browserCache:tr.optional()}),Op=Me.discriminatedUnion("type",[xR,IR]);var Ho=(l=>(l.AI_CHECK="AI_CHECK",l.TAP="TAP",l.TYPE="TYPE",l.PRESS="PRESS",l.OPEN_APP="OPEN_APP",l.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",l.JAVASCRIPT="JAVASCRIPT",l.ADB="ADB",l.STATE="STATE",l))(Ho||{}),Np=(c=>(c.BACK="BACK",c.HOME="HOME",c.APP_SWITCHER="APP_SWITCHER",c.POWER="POWER",c.SEARCH="SEARCH",c.VOLUME_UP="VOLUME_UP",c.VOLUME_DOWN="VOLUME_DOWN",c.VOLUME_MUTE="VOLUME_MUTE",c))(Np||{}),kp=ye.discriminatedUnion("type",[ye.object({type:ye.literal("description"),description:ye.string()}),ye.object({type:ye.literal("coordinates"),xPercent:ye.number(),yPercent:ye.number()})]),zn=ye.object({id:ye.string().uuid(),disableCache:ye.boolean().optional()}),PR=zn.extend({type:ye.literal("STATE")}),_p=ye.object({target:Op}),Kc=zn.extend({type:ye.literal("TAP"),target:kp,cache:_p.optional()}),Yc=zn.extend({type:ye.literal("TYPE"),target:kp.optional(),cache:_p.optional(),text:ye.string()}),MR=zn.extend({type:ye.literal("OPEN_NOTIFICATION_DRAWER")}),LR=zn.extend({type:ye.literal("PRESS"),key:ye.nativeEnum(Np)}),OR=zn.extend({type:ye.literal("OPEN_APP"),packageName:ye.string(),activityName:ye.string().optional()}),NR=zn.extend({type:ye.literal("AI_CHECK"),assertion:ye.string(),timeoutSecs:ye.number().optional()}),kR=zn.extend({type:ye.literal("JAVASCRIPT"),code:ye.string(),timeout:ye.number().int().max(60).optional().describe("Max seconds for the code to complete")}),_R=zn.extend({type:ye.literal("ADB"),command:ye.string()}),Dp=ye.discriminatedUnion("type",[Kc,Yc,LR,OR,MR,NR,kR,_R,PR]);var Fp={type:!0,cache:!0},$o=DR.discriminatedUnion("type",[Kc.pick(Fp),Yc.pick(Fp)]),PU=Object.values(Ho).filter(t=>$o.options.some(e=>e.shape.type.safeParse(t).success));var Up=Pa($o),Bp=Ma($o),MU=Hi($o);import{cloneDeep as NU}from"lodash-es";import _U from"truncate-json";import sr from"zod";import za from"zod";var FR=za.object({id:za.string().uuid(),envKey:za.string().optional()}),Hn=FR.extend({type:za.literal("MOBILE_PRESET_STEP"),command:Dp}),zU=za.discriminatedUnion("type",[Hn]);import Be from"zod";var jo=Be.object({startTime:Be.number(),endTime:Be.number().optional(),error:Be.string().optional()});var Xc=jo.extend({type:Be.literal("SECTION"),name:Be.string(),subSpans:Be.lazy(()=>jR.array())}),UR=jo.extend({type:Be.literal("AI_LOCATOR_CALL"),result:Be.object({serializedElement:Be.string(),id:Be.number(),thoughts:Be.string()}).optional()}),BR=jo.extend({type:Be.literal("AI_ASSERTION_CALL"),result:Be.object({thoughts:Be.string(),result:Be.boolean()}).optional()}),zR=jo.extend({type:Be.literal("WAIT_FOR_STABILITY"),reason:Be.string().optional()}),HR=jo.extend({type:Be.literal("RESOLVE_TARGET_CACHE"),result:Be.object({serializedElement:Be.string()}).optional()}),$R=jo.extend({type:Be.literal("GET_EMULATOR_STATE")}),jR=Be.discriminatedUnion("type",[Xc,UR,BR,zR,HR,$R]);var GR=sr.object({message:sr.string().optional(),startTime:sr.number(),endTime:sr.number(),status:sr.nativeEnum(we),trace:Xc.optional().catch(void 0),beforeSnapshot:sr.string().optional(),afterSnapshot:sr.string().optional()}),WR=Hn.merge(GR).extend({data:sr.unknown().optional().describe("output data from the step")}),ms=WR;import Qe from"zod";import{z as dn}from"zod";import{z as De}from"zod";var yt=De.object({id:De.string(),name:ls,baseUrl:cs,description:De.string().optional().nullish(),schemaVersion:De.string(),advanced:Vr,retries:De.number(),envs:De.array(ns).nullish(),parameters:ts.nullish(),disabled:De.boolean().optional(),labels:De.array(De.string()).optional().catch([])}),ZU=De.enum(["INHERIT","ENABLED","DISABLED"]);var VR=Vr.extend({failureRecovery:De.boolean().or(De.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:De.boolean().or(De.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var eB=yt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:VR}),tB=yt.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),qR=De.object({labels:De.array(De.string()).optional(),outputs:np.nullish()}),tn=yt.merge(qR),KR=De.object({createdAt:De.coerce.date(),updatedAt:De.coerce.date(),updatedBy:De.string().nullable(),schedule:Uo,notification:Bo,createdBy:De.string(),organizationId:De.string(),folderId:De.string().nullable().optional()}),YR=yt.merge(KR),nB=YR.merge(Mo),ps=yt.merge(Mo),rB=yt.merge(zr);var zp="test",Hp="module",XR="mobile-test",lt=(n=>(n.TEST=`${zp}.yaml`,n.MODULE=`${Hp}.yaml`,n))(lt||{}),ge=(r=>(r.TEST=`momentic/${zp}`,r.MODULE=`momentic/${Hp}`,r.MOBILE_TEST=`momentic/${XR}`,r))(ge||{}),dB=yt.merge(zr),Jc=Ot.extend({steps:dn.array(dn.record(dn.string(),dn.unknown())),schemaVersion:dn.string()}),uB=Jc.extend({fileType:dn.literal(ge.MODULE)}),mB=dn.object({test:dn.string().describe("YAML for the test, including metadata and steps"),modules:dn.record(dn.string(),dn.string()).describe("Map of module name to YAML for the module")});var Ha=(n=>(n.USWest1="us-west1",n.EUNorth1="eu-north1",n))(Ha||{});var JR=Qe.object({disableDefaultWebviewAccessibilityTree:Qe.boolean().optional(),autoGrantPermissions:Qe.boolean().optional()}),Qc=JR.extend({region:Qe.nativeEnum(Ha).optional()}),$a=Qe.object({retries:Qe.number().optional().describe("number of retries to run"),defaultChannel:Qe.string().optional().describe("default channel to use"),defaultTag:Qe.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:Qe.string().optional(),emulator:Qc.optional()}),Zc=Qe.object({id:Qe.string().uuid(),description:Qe.string(),schemaVersion:Qe.string(),settings:$a.optional()}),QR=Zc.merge(Qe.object({steps:Qe.array(Hn)})),$p=Qe.object({fileType:Qe.literal(ge.MOBILE_TEST)}).merge(QR),bB=Qe.object({name:Qe.string(),steps:Qe.array(Hn).optional(),settings:$a.optional()});var FB=new Set(Object.values(Ge));var ZR={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},UB={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},BB={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session.",LOCAL_STORAGE:"Set a localStorage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},zB={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},HB={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import eC from"semver";import{z as tC}from"zod";var WB=tC.string().refine(t=>eC.valid(t),{message:"must be a valid semver string"});import{Faker as KB,en as YB}from"@faker-js/faker";import{z as O}from"zod";var gs=55555,JB=O.object({body:O.string(),to:O.string(),from:O.string()}),QB=O.object({from:O.string().optional(),to:O.string(),timeout:O.number().optional(),beforeDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional()}),ZB=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),ez=O.object({inbox:O.string().transform(t=>t.toLowerCase()),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),timeout:O.number().optional(),trimWhitespace:O.boolean().optional()}),tz=O.object({inbox:O.string(),limit:O.number().optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),trimWhitespace:O.boolean().optional()});var hs=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(hs||{}),jp=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),nC=O.object({url:O.string(),options:O.object({method:O.string(),body:O.string().nullish(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),rC=O.object({body:O.string().nullish(),options:O.object({status:O.number(),statusText:O.string().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),Gp=O.object({result:O.unknown(),variableUpdates:O.record(O.string(),O.unknown()).optional(),persistentVariableUpdates:O.record(O.string(),O.unknown()).optional(),error:O.string().optional(),success:O.boolean()}),nz=O.object({id:O.string().optional(),orgId:O.string(),momenticLambdaAuthHash:O.string(),code:O.string(),fragment:O.boolean(),state:O.object({env:O.record(O.string(),O.unknown()),request:nC,response:rC,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(hs).optional()}),lr=15e3;import*as bt from"zod";import{extendZodWithOpenApi as oC}from"zod-openapi";oC(bt);var aC=bt.object({url:bt.string(),lineNumber:bt.number(),columnNumber:bt.number()}).openapi({ref:"CodeLocation"}),fs=bt.object({timestamp:bt.number(),text:bt.string(),type:bt.string(),tabIndex:bt.number(),args:bt.unknown().array().optional(),url:bt.string().optional(),location:aC.optional()}).openapi({ref:"ConsoleLog"}),Wp=fs.array(),iC=Wp.array();import*as td from"zod";import{extendZodWithOpenApi as AC}from"zod-openapi";import{z as P}from"zod";var sC=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),lC=P.object({name:P.string(),version:P.string(),comment:P.string().optional()}),cC=P.object({onContentLoad:P.number().optional(),onLoad:P.number().optional(),comment:P.string().optional()}),qp=P.object({startedDateTime:P.string(),id:P.string(),title:P.string().optional(),pageTimings:cC,comment:P.string().optional()}),dC=P.array(qp),uC=P.object({name:P.string(),value:P.string(),path:P.string().optional(),domain:P.string().optional(),expires:P.string().optional(),httpOnly:P.boolean().optional(),secure:P.boolean().optional(),comment:P.string().optional()}),Kp=P.array(uC),mC=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),Yp=P.array(mC),pC=P.object({name:P.string(),value:P.string(),comment:P.string().optional()}),gC=P.array(pC),hC=P.object({name:P.string(),value:P.string().optional(),fileName:P.string().optional(),contentType:P.string().optional(),comment:P.string().optional()}),fC=P.array(hC),SC=P.object({mimeType:P.string(),params:fC,text:P.string(),comment:P.string().optional()}),yC=P.object({method:P.string(),url:P.string(),httpVersion:P.string().optional(),cookies:Kp,headers:Yp,queryString:gC,postData:SC.optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional()}),bC=P.object({size:P.number().optional(),compression:P.number().optional(),mimeType:P.string().optional(),text:P.string().optional(),encoding:P.string().optional(),comment:P.string().optional()}),TC=P.object({status:P.number(),statusText:P.string(),httpVersion:P.string().optional(),cookies:Kp,headers:Yp,content:bC,redirectURL:P.string().optional(),headersSize:P.number().optional(),bodySize:P.number().optional(),comment:P.string().optional(),_mocked:P.boolean().optional()}),Vp=P.object({expires:P.string().optional(),lastAccess:P.string(),eTag:P.string(),hitCount:P.number(),comment:P.string().optional()}),wC=P.object({beforeRequest:Vp.optional(),afterRequest:Vp.optional(),comment:P.string().optional()}),EC=P.object({blocked:P.number().optional(),dns:P.number().optional(),connect:P.number().optional(),send:P.number(),wait:P.number(),receive:P.number(),ssl:P.number().optional(),comment:P.string().optional()}),Xp=P.object({pageref:P.string().optional(),startedDateTime:P.string(),time:P.number().optional(),request:yC,response:TC.optional(),cache:wC.optional(),timings:EC,serverIPAddress:P.string().optional(),connection:P.string().optional(),comment:P.string().optional(),_resourceType:P.string().optional()}),RC=P.array(Xp),CC=P.object({version:P.string().default("1.1"),creator:sC.optional(),browser:lC.optional(),pages:dC.optional(),entries:RC,comment:P.string().optional()}),vC=P.object({log:CC}),Jp=P.record(P.string(),qp),Qp=P.record(P.string(),Xp);function ed(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime()),entries:Object.values(e).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime())}}}AC(td);var xC=td.object({logsPerPage:fs.array().array(),harPages:Jp.optional(),harEntries:Qp.optional()}).openapi({ref:"DebugData"});var ja=class{async getConsoleLogsForRunAttempt(e,n,r){}async getNetworkLogsForRunAttempt(e,n,r){}async getHtmlSnapshot(e,n){}async getA11yTreeSnapshot(e,n){}async getScreenshot(e,n){}async storeConsoleLogsForRunAttempt(e,n,r,o){}async storeNetworkLogsForRunAttempt(e,n,r,o){}async storeScreenshot(e,n,r){}async storeHtmlSnapshot(e,n,r){}};var Ss=class extends Error{constructor(e,n,r,o={}){super(`The ${r} with id ${n} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function Zp(t){for(let e of Object.values(pe))if(t.includes(e))return e}var A=class extends Error{reason;constructor(e,n,r){let o=!1;for(let a of Object.values(pe))if(n.startsWith(a)){o=!0,e=a;break}if(r?.errOptions?.cause)super(o?n:`${e}: ${n}`,r?.errOptions);else{let a=o?n:`${e}${n?`: ${n}`:""}`;super(a,r?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},Go=class extends Error{updatedLocatorMemory;constructor(e,n,r={}){super(e,r),this.updatedLocatorMemory=n,this.name="NoElementsFoundUsingAIError"}},En=class extends Error{decisions;constructor(e,n,r={}){super(e,r),this.decisions=n,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
5
5
  Decisions:
6
6
  ${this.decisions.map(e=>e.toString()).join(`
7
- `)}`}};function tg(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function od(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var Rn=class extends Error{retryableWithAI;constructor(e,n,r={}){super(e,r),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=n}},ys=class extends Rn{constructor(e,n={}){super(e,!0,n),this.name="BoundingBoxMovedError"}},bs=class extends Rn{constructor(e,n={}){super(e,!1,n),this.name="ZeroOpacityError"}};function ng(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}function Ga(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function ad(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var ja=class extends Error{constructor(e,n={}){super(e,n),this.name="InsufficientCacheDataError"}};import{cloneDeep as vC}from"lodash-es";import{z as Cn}from"zod";var dr=(p=>(p.DisableClickhouseCaches="disable_clickhouse_caches",p.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",p.IconKnowledgeBase="icon_knowledge_base",p.MiniModelInitialAssertion="mini_model_initial_assertion",p.MiniModelInitialLocator="mini_model_initial_locator",p.ShowTestPlans="show_test_plans",p.ShowZeroOpacityElements="show_zero_opacity_elements",p.VisualActions="visual_actions",p.RagV2="rag_v2",p.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",p.GlobalLocatorRedirect="global_locator_redirect",p.FakerConstantSeed="faker_constant_seed",p.AutoExpandIframes="auto_expand_iframes",p))(dr||{});var rg=Cn.union([Cn.string(),Cn.number(),Cn.boolean(),Cn.null(),Cn.record(Cn.string(),Cn.lazy(()=>rg)),Cn.array(Cn.lazy(()=>rg))]),Wa=class{flags;payloads;constructor(e,n){this.flags=e,this.payloads=n}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=vC(this.flags);return Object.entries(e).forEach(([n,r])=>{typeof r=="boolean"&&Object.values(dr).includes(n)&&(e[n]=this.isBooleanFlagEnabled(n))}),e}getFlagPayload(e){let n=this.payloads[e];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}},Dz=new Wa({},{});var id={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},og=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],Uz=Object.keys(id);import*as ag from"zod";var zz=ag.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."});import{z as ur}from"zod";var jz=ur.object({id:ur.string(),name:ur.string(),createdAt:ur.coerce.date(),createdBy:ur.string(),updatedAt:ur.coerce.date(),updatedBy:ur.string().nullable(),organizationId:ur.string()});import{z as L}from"zod";import mr from"zod";var Wo=mr.object({platformSep:mr.string(),fullPathSegments:mr.string().array(),relativePathSegments:mr.string().array(),relativePath:mr.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:mr.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:mr.coerce.date(),createdAt:mr.coerce.date()});var AC=L.array(Wo.extend({id:L.string(),name:L.string(),description:L.string().optional(),labels:L.string().array().optional()})),xC=L.array(Wo.extend({id:L.string(),name:L.string(),description:L.string().optional(),content:Oa})),nH=L.object({tests:AC,modules:xC,labels:L.string().array()}),rH=ps.merge(en),ig=L.object({schemaVersion:L.string(),stepLists:Mo}),sg=en.partial().merge(St.pick({id:!0})),lg=L.object({name:L.string(),description:L.string().optional(),baseUrl:L.string().url().optional(),environment:L.string().optional(),browserType:L.nativeEnum(zn).optional(),viewport:Zi.optional(),pathSegments:L.string().array().optional()}),oH=ps.merge(L.object({relativeFilePath:L.string().describe("relative to project root")})),cg=L.object({name:L.string()}),aH=L.object({relativeFilePath:L.string()}),dg=L.object({name:L.string()}),iH=L.object({relativeFilePath:L.string()}),ug=L.object({name:L.string(),description:L.string(),enabled:L.boolean(),steps:L.lazy(()=>Ge.array()),testFilePath:L.string().describe("relative to the project root"),folderPath:L.string().optional().describe("user selected folder path")}),mg=L.object({name:L.string(),description:L.string(),enabled:L.boolean()}).partial();var sH=L.array(Ym),pg=L.object({defaultEnv:L.string().optional().describe("name of the default env, or undefined to unset")}),gg=L.object({configFilePath:L.string().describe("full path on disk")}),lH=L.string().array(),cH=L.object({message:L.string(),newRelativeTestPath:L.string().optional()}),sd=L.object({name:L.string(),absolutePath:L.string(),relativePath:L.string(),pathSegments:L.array(L.string()),isDirectory:L.boolean(),size:L.number(),createdAt:L.coerce.date(),modifiedAt:L.coerce.date(),accessedAt:L.coerce.date()}),hg=L.object({pathSegments:L.array(L.string())}),dH=L.object({absolutePath:L.string(),pathSegments:L.array(L.string()),contents:L.array(sd)}),fg=L.object({pathSegments:L.array(L.string())}),Sg=L.object({pathSegments:L.array(L.string()),newPathSegments:L.array(L.string())}),yg=L.object({pathSegments:L.array(L.string()),recursive:L.boolean().optional()}),uH=L.object({success:L.boolean(),message:L.string(),pathSegments:L.array(L.string()).optional()});var Ts=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],ws=Ts.map(t=>`**/${t}/**`);import vn from"chalk";import IC from"safe-stable-stringify";import PC from"truncate-json";import MC from"zod";var Va=IC.configure({deterministic:!1});function bg(t){let e=Va(t),{jsonString:n}=PC(e,1e4);return n}var LC=["app","version","env","namespace","host"];function Oe(t){let e=t.bindings()??{},n={};for(let r of Object.keys(e)){let o=e[r];!LC.includes(r)&&typeof o=="string"&&(n[r]=o)}return n}var ld=MC.enum(["debug","info","warn","error"]);var qa={debug:20,info:30,warn:40,error:50},Rs={20:"debug",30:"info",40:"warn",50:"error"},Ka=class t{minLogLevel;logBindings;constructor(e,n){typeof e=="string"?this.minLogLevel=qa[e]:this.minLogLevel=e,this.logBindings=n}logWithLevel(e,n,...r){try{this.logWithLevelHelper(e,n,...r)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,n,...r){if(e<this.minLogLevel)return;let o;Array.isArray(r[0])?(o=r[0],r=r.slice(1)):typeof r[0]=="object"&&!(r[0]instanceof Error)&&Object.entries(r[0]).length&&(o={...r[0],...this.logBindings},r=r.slice(1));let a=[];if(a.push(...r),console.log(n(...a)),o&&!Array.isArray(o)){let i=Object.entries(o);for(let[s,l]of i){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=Va(l,void 0,2),c=c.split(`
7
+ `)}`}};function eg(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function nd(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var Rn=class extends Error{retryableWithAI;constructor(e,n,r={}){super(e,r),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=n}},ys=class extends Rn{constructor(e,n={}){super(e,!0,n),this.name="BoundingBoxMovedError"}},bs=class extends Rn{constructor(e,n={}){super(e,!1,n),this.name="ZeroOpacityError"}};function tg(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}function Wa(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function rd(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var Ga=class extends Error{constructor(e,n={}){super(e,n),this.name="InsufficientCacheDataError"}};import{cloneDeep as IC}from"lodash-es";import{z as Cn}from"zod";var cr=(p=>(p.DisableClickhouseCaches="disable_clickhouse_caches",p.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",p.IconKnowledgeBase="icon_knowledge_base",p.MiniModelInitialAssertion="mini_model_initial_assertion",p.MiniModelInitialLocator="mini_model_initial_locator",p.ShowTestPlans="show_test_plans",p.ShowZeroOpacityElements="show_zero_opacity_elements",p.VisualActions="visual_actions",p.RagV2="rag_v2",p.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",p.GlobalLocatorRedirect="global_locator_redirect",p.FakerConstantSeed="faker_constant_seed",p.AutoExpandIframes="auto_expand_iframes",p))(cr||{});var ng=Cn.union([Cn.string(),Cn.number(),Cn.boolean(),Cn.null(),Cn.record(Cn.string(),Cn.lazy(()=>ng)),Cn.array(Cn.lazy(()=>ng))]),Va=class{flags;payloads;constructor(e,n){this.flags=e,this.payloads=n}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=IC(this.flags);return Object.entries(e).forEach(([n,r])=>{typeof r=="boolean"&&Object.values(cr).includes(n)&&(e[n]=this.isBooleanFlagEnabled(n))}),e}getFlagPayload(e){let n=this.payloads[e];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}},Wz=new Va({},{});var od={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},rg=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],qz=Object.keys(od);import*as og from"zod";var Yz=og.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."});import{z as dr}from"zod";var Qz=dr.object({id:dr.string(),name:dr.string(),createdAt:dr.coerce.date(),createdBy:dr.string(),updatedAt:dr.coerce.date(),updatedBy:dr.string().nullable(),organizationId:dr.string()});import{z as L}from"zod";import ur from"zod";var Wo=ur.object({platformSep:ur.string(),fullPathSegments:ur.string().array(),relativePathSegments:ur.string().array(),relativePath:ur.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:ur.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:ur.coerce.date(),createdAt:ur.coerce.date()});var PC=L.array(Wo.extend({id:L.string(),name:L.string(),description:L.string().optional(),labels:L.string().array().optional()})),MC=L.array(Wo.extend({id:L.string(),name:L.string(),description:L.string().optional(),content:Oa})),uH=L.object({tests:PC,modules:MC,labels:L.string().array()}),mH=ps.merge(tn),ag=L.object({schemaVersion:L.string(),stepLists:Mo}),ig=tn.partial().merge(yt.pick({id:!0})),sg=L.object({name:L.string(),description:L.string().optional(),baseUrl:L.string().url().optional(),environment:L.string().optional(),browserType:L.nativeEnum(Bn).optional(),viewport:Zi.optional(),pathSegments:L.string().array().optional()}),pH=ps.merge(L.object({relativeFilePath:L.string().describe("relative to project root")})),lg=L.object({name:L.string()}),gH=L.object({relativeFilePath:L.string()}),cg=L.object({name:L.string()}),hH=L.object({relativeFilePath:L.string()}),dg=L.object({name:L.string(),description:L.string(),enabled:L.boolean(),steps:L.lazy(()=>We.array()),testFilePath:L.string().describe("relative to the project root"),folderPath:L.string().optional().describe("user selected folder path")}),ug=L.object({name:L.string(),description:L.string(),enabled:L.boolean()}).partial();var fH=L.array(Km),mg=L.object({defaultEnv:L.string().optional().describe("name of the default env, or undefined to unset")}),pg=L.object({configFilePath:L.string().describe("full path on disk")}),SH=L.string().array(),yH=L.object({message:L.string(),newRelativeTestPath:L.string().optional()}),ad=L.object({name:L.string(),absolutePath:L.string(),relativePath:L.string(),pathSegments:L.array(L.string()),isDirectory:L.boolean(),size:L.number(),createdAt:L.coerce.date(),modifiedAt:L.coerce.date(),accessedAt:L.coerce.date()}),gg=L.object({pathSegments:L.array(L.string())}),bH=L.object({absolutePath:L.string(),pathSegments:L.array(L.string()),contents:L.array(ad)}),hg=L.object({pathSegments:L.array(L.string())}),fg=L.object({pathSegments:L.array(L.string()),newPathSegments:L.array(L.string())}),Sg=L.object({pathSegments:L.array(L.string()),recursive:L.boolean().optional()}),TH=L.object({success:L.boolean(),message:L.string(),pathSegments:L.array(L.string()).optional()});var Ts=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],ws=Ts.map(t=>`**/${t}/**`);import vn from"chalk";import LC from"safe-stable-stringify";import OC from"truncate-json";import NC from"zod";var qa=LC.configure({deterministic:!1});function yg(t){let e=qa(t),{jsonString:n}=OC(e,1e4);return n}var kC=["app","version","env","namespace","host"];function Le(t){let e=t.bindings()??{},n={};for(let r of Object.keys(e)){let o=e[r];!kC.includes(r)&&typeof o=="string"&&(n[r]=o)}return n}var id=NC.enum(["debug","info","warn","error"]);var Ka={debug:20,info:30,warn:40,error:50},Rs={20:"debug",30:"info",40:"warn",50:"error"},Ya=class t{minLogLevel;logBindings;constructor(e,n){typeof e=="string"?this.minLogLevel=Ka[e]:this.minLogLevel=e,this.logBindings=n}logWithLevel(e,n,...r){try{this.logWithLevelHelper(e,n,...r)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,n,...r){if(e<this.minLogLevel)return;let o;Array.isArray(r[0])?(o=r[0],r=r.slice(1)):typeof r[0]=="object"&&!(r[0]instanceof Error)&&Object.entries(r[0]).length&&(o={...r[0],...this.logBindings},r=r.slice(1));let a=[];if(a.push(...r),console.log(n(...a)),o&&!Array.isArray(o)){let i=Object.entries(o);for(let[s,c]of i){let l=c;c instanceof Error?(l=c.message,console.log(n(` ${s}:`,l)),console.log(n(" stack:",c.stack))):typeof c=="object"&&(l=qa(c,void 0,2),l=l.split(`
8
8
  `).map((d,u)=>u>0?` ${d}`:d).join(`
9
- `)),console.log(n(` ${s}:`,c))}}else if(o)for(let i of o){let s=i;typeof i=="object"&&(s=Va(i,void 0,2),s=s.split(`
10
- `).map((l,c)=>c>0?` ${l}`:l).join(`
11
- `)),console.log(" ",n(s))}}getLevel(){return Rs[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=qa[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,vn.reset,...e)}info(...e){this.logWithLevel(30,vn.white,...e)}debug(...e){this.logWithLevel(20,vn.dim,...e)}warn(...e){this.logWithLevel(40,vn.yellow,...e)}error(...e){this.logWithLevel(50,vn.red,...e)}success(...e){this.logWithLevel(1/0,vn.green,...e)}dimmed(...e){this.logWithLevel(30,vn.dim,...e)}underline(...e){this.logWithLevel(40,vn.underline,...e)}bold(...e){this.logWithLevel(40,vn.bold,...e)}grey(...e){this.logWithLevel(20,vn.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},cd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},bH=new cd,OC=typeof window>"u"&&typeof process<"u"&&ld.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?ld.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,S=new Ka(OC,{}),Xr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Xr,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Es={},Cs=({logger:t,logKey:e,maxCount:n,intervalMs:r},o,a,...i)=>{let s=Es[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},Es[e]=s),s.totalCount++,s.count<n&&(s.count++,t.debug(o,a,...i)),s.timer=setTimeout(()=>{let l=Es[e];l?.totalCount!==l?.count&&t.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete Es[e]},r)};import{z as Re}from"zod";var NC=Re.array(Wo.extend({id:Re.string(),name:Re.string(),description:Re.string().optional(),labels:Re.string().array().optional()})),kC=Re.array(Wo.extend({id:Re.string(),name:Re.string(),description:Re.string().optional(),content:Oa})),vH=Re.object({name:Re.string(),description:Re.string().optional(),steps:Re.array($n).optional(),settings:Ha.optional(),pathSegments:Re.string().array()}),AH=Re.object({id:Re.string(),fileName:Re.string(),fullPath:Re.string(),relativeFilePath:Re.string().describe("relative to project root")});var xH=Re.object({steps:Re.array($n).optional(),settings:Ha.optional()}),IH=Re.object({message:Re.literal("ok")}),PH=Re.object({tag:Re.string(),channel:Re.string(),filePath:Re.string()}),MH=Re.object({tests:NC,modules:kC,labels:Re.string().array()});import{z as qe}from"zod";var Tg=qe.object({id:qe.string(),createdAt:qe.coerce.date(),createdBy:qe.string(),organizationId:qe.string(),name:qe.string(),description:qe.string().nullish(),enabled:qe.boolean(),schemaVersion:qe.string().describe("Schema version for steps"),parameters:qe.string().array().nullish().describe("Parameter list"),parameterEnums:qe.record(qe.string(),qe.string().array()).nullish(),defaultParameters:qe.record(qe.string(),qe.string()).nullish(),defaultCacheKey:qe.string().nullish(),defaultCacheTtl:qe.number().nullish(),defaultCacheAllInvocations:qe.boolean().nullish(),autoAuth:qe.boolean().nullish(),advanced:Ac.nullish()}),BH=Tg.extend({steps:qe.lazy(()=>Me.array())}),wg=5*60*1e3,dd=Ot.merge(Tg.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as $H}from"date-fns-tz";import{z as Ne}from"zod";var ud=Bc.extend({aiAction:Ne.boolean().optional(),stepLintSuggestions:Ne.boolean().optional(),agentConfig:Ne.record(Ne.string(),Ne.string()).optional(),aiFailureAnalysis:Ne.boolean().optional(),aiPageFiltering:Ne.boolean().optional().describe("rag v2 feature flag")}),md=Ne.object({fakerConstantSeed:Ne.boolean().optional()}),KH=Ne.object({ai:ud.optional(),githubAppInstallationId:Ne.number().nullish(),githubAppSummaryMessageEnabled:Ne.boolean().nullish(),githubReleaseAppInstallationId:Ne.number().nullish(),gitlabAppAccessToken:Ne.string().nullish(),gitlabAppBaseUrl:Ne.string().nullish(),qaseAccessToken:Ne.string().nullish(),testSuggestionsEnabled:Ne.boolean().nullish(),browser:Oc.optional(),advanced:md.optional()}),YH=Ne.object({globalOverrides:Ne.record(Ne.string()).optional(),agentConfig:Ne.record(Ne.string(),Ne.string()).optional()}),XH=Ne.record(Ne.string(),Ne.string()).nullish();import*as T from"zod";import{z as We}from"zod";var pd=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(pd||{});var _C=We.object({type:We.literal("DESCRIPTION_UPDATE"),thoughts:We.string()}),vs=We.discriminatedUnion("type",[_C]),DC=We.object({testId:We.string(),name:We.string(),orgId:We.string(),runId:We.string(),steps:Ge.array(),purpose:We.nativeEnum(pd),details:vs.or(vs.array()).optional()});var e1=DC.pick({name:!0,orgId:!0}),FC=We.object({id:We.string(),name:We.string().nullish(),createdAt:We.string().pipe(We.coerce.date()).or(We.date()),organizationId:We.string(),schemaVersion:We.string(),runId:We.string().nullish(),purpose:We.nativeEnum(pd),details:vs.or(vs.array()).optional(),applied:We.boolean().nullish(),appliedAt:We.coerce.date().nullish()}),Eg=FC.extend({steps:Ge.array()});var Rg="x-momentic-cli-version",UC="x-momentic-main-branch-name",BC="x-momentic-branch-name",zC="x-momentic-commit-timestamp",HC="x-momentic-last-commit-on-main",$C="x-momentic-last-commit-on-main-timestamp",f1=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),S1=kt.merge($c),Cg=zi,y1=kt.merge($c);var b1=kt.merge(fp).extend({useConsensus:T.boolean().optional(),attemptNumber:T.number().optional()}),gd=Rm,T1=kt.merge(Sp),vg=zm,w1=kt.merge(pp),Ag=Bm,E1=kt.merge(gp),xg=Um,R1=kt.merge(hp);var C1=T.object({testPaths:T.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:T.string().optional(),all:T.boolean().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional(),testInputMatrix:T.record(T.string(),T.string()).array().optional()}),Ig=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()});var v1=T.string().array(),A1=T.union([T.object({paths:T.string().array().describe("run specific test paths (e.g. todo-test)"),all:T.boolean().describe("run all tests").optional()}),T.object({path:T.string().describe("deprecated; present for backcompat")})]),Pg=T.object({tests:T.record(T.string().describe("Test name"),T.string().describe("Test YAML")),modules:T.record(T.string().describe("Module name"),T.string().describe("Module YAML"))}),jC=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),x1=jC.array(),I1=T.object({testId:T.string(),schemaVersion:T.string()}).merge(zr);function hd(t){let{gitMainBranch:e,gitBranchName:n,gitCommitTimestamp:r,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:a}=t,i={};return e&&(i[UC]=encodeURIComponent(e)),n&&(i[BC]=encodeURIComponent(n)),r&&(i[zC]=r.toISOString()),o&&(i[HC]=encodeURIComponent(o)),a&&(i[$C]=a.toISOString()),i}var P1=T.object({entries:T.array(Nm),testId:T.string()}),M1=T.object({entries:T.array(Bp),testId:T.string()}),L1=T.object({testId:T.string()});function Mg(t){return T.record(T.unknown()).transform(e=>{let n={};for(let[r,o]of Object.entries(e)){let a=t.safeParse(o);a.success&&(n[r]=a.data)}return n})}var Lg=Mg(km),Og=Mg(zp),Ng=T.object({trigger:T.nativeEnum(Jt),status:T.nativeEnum(le),startedAt:T.coerce.date().optional(),gitCommitSha:T.string().optional(),gitCommitShaShort:T.string().optional(),gitCommitTimestamp:T.coerce.date().optional(),gitBranchName:T.string().optional(),gitOriginUrl:T.string().optional(),gitCommitMessage:T.string().optional(),gitCommitAuthorName:T.string().optional(),githubRepository:T.string().optional(),gitlabProjectPath:T.string().optional(),pipelineId:T.string().optional(),cliVersion:T.string().optional()}),O1=T.object({id:T.string()}),kg=T.object({status:T.nativeEnum(le),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),_g=T.object({stepsSnapshot:T.array(T.record(T.unknown())).optional(),runGroupId:T.string().optional(),testId:T.string(),testName:T.string(),resolvedBaseUrl:T.string().optional(),environmentName:T.string().optional(),labels:T.array(T.string()).optional(),cliVersion:T.string().optional(),trigger:T.nativeEnum(Jt),schemaVersion:T.string().optional(),section:T.nativeEnum(rs).optional(),resolvedInputs:T.record(T.string(),T.string()).optional(),quarantined:T.boolean().optional().default(!1),quarantinedReason:T.string().optional()}),N1=T.object({id:T.string()}),GC=zc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Dg=GC.array(),Fg=zc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),k1=T.object({id:T.string()}),Ug=T.object({status:T.nativeEnum(le),finishedAt:T.coerce.date().optional(),schemaVersion:T.string().optional().default("1.0.19"),results:T.record(T.string(),T.unknown()).array().optional(),beforeResults:T.record(T.string(),T.unknown()).array().optional(),afterResults:T.record(T.string(),T.unknown()).array().optional()}),_1=T.object({screenshot:T.string()}),Bg=T.object({key:T.string()}),zg=T.object({orgId:T.string(),userId:T.string()}),Hg=T.array(Km),D1=T.record(T.string(),T.union([T.string(),T.boolean()])),F1=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),$g=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),U1=T.object({suiteRunIds:T.string().array()}),B1=cp.array(),z1=T.object({runGroupIds:T.string().array()}),WC=T.object({uploadUrl:T.string()}),H1=kt.merge(yp),$1=kt.merge(Tp),j1=kt.merge(bp),VC=T.object({testId:T.string().optional().default(""),testName:T.string().optional().default(""),suiteId:T.string().optional().default(""),suiteName:T.string().optional().default(""),creditsUsed:T.number().optional(),usedBy:T.string().optional()}),qC=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(Ba),properties:VC}),G1=qC.array(),jg=Eg.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),W1=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),Gg=op.array(),V1=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),Wg=WC.extend({id:T.string()}),q1=T.object({runGroupId:T.string().uuid().optional()}),Vg=T.object({runGroupId:T.string().uuid()}),qg=T.object({quarantined:T.object({testId:T.string().uuid(),quarantinedAt:T.coerce.date(),quarantinedBy:T.string().optional(),quarantinedReason:T.string()}).array()}),K1=T.object({testId:T.string().uuid(),testName:T.string().optional(),reason:T.string(),gitLocalUsername:T.string().optional(),gitLocalEmail:T.string().optional(),gitLocalName:T.string().optional()}),Y1=T.object({testName:T.string().optional(),reason:T.string().optional(),gitLocalUsername:T.string().optional(),gitLocalEmail:T.string().optional(),gitLocalName:T.string().optional()}),X1=kt.merge(Rp),J1=kt.merge(Cp),Q1=T.object({apkToInstall:T.object({channel:T.string(),tag:T.string().optional()}).optional(),hostname:T.string().optional()}),Kg=T.object({name:T.string(),webRtcUrl:T.string(),adbUrl:T.string(),token:T.string(),apkDownloadUrl:T.string().optional(),region:T.string().optional()}),Z1=T.object({channel:T.string(),tag:T.string(),md5:T.string()}),Yg=T.object({id:T.string(),uploadUrl:T.string().optional(),downloadUrl:T.string(),md5:T.string().optional()}),Xg=T.object({assets:T.array(T.object({channel:T.string(),tag:T.string(),md5:T.string(),createdAt:T.number().describe("Unix timestamp in milliseconds")}))});import{z as Y}from"zod";var n$=Y.object({localTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()}).or(Y.object({cloudTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()})),Jg=(n=>(n.QUARANTINE="QUARANTINE",n.UNQUARANTINE="UNQUARANTINE",n))(Jg||{});var fd=Y.object({name:Y.string(),description:Y.string().nullish(),effect:Y.nativeEnum(Jg),labels:Y.array(Y.string()),githubRepository:Y.string().nullish(),gitlabProjectPath:Y.string().nullish(),gitBranchName:Y.string().nullish()}),KC=Y.object({type:Y.literal("LAST_N_RUNS"),lastN:Y.number().min(1).max(10)}),YC=Y.object({type:Y.literal("LAST_N_HOURS"),lastN:Y.number().min(1).max(24)}),XC=Y.object({type:Y.literal("LAST_N_DAYS"),lastN:Y.number().min(1).max(7)}),Sd=Y.discriminatedUnion("type",[KC,YC,XC]),JC=Y.object({flakeRateThreshold:Y.number().min(1).max(100),evaluationWindow:Sd}),QC=fd.extend({type:Y.literal("FLAKE_RATE"),config:JC}),ZC=Y.object({passRateThreshold:Y.number().min(1).max(100),evaluationWindow:Sd}),ev=fd.extend({type:Y.literal("PASS_RATE"),config:ZC}),tv=Y.object({failureCountThreshold:Y.number().min(0),evaluationWindow:Sd}),nv=fd.extend({type:Y.literal("FAILURE_COUNT"),config:tv}),r$=Y.discriminatedUnion("type",[QC,ev,nv]);import{z as nt}from"zod";var i$=nt.object({repositoriesIndexed:nt.boolean(),indexingInProgress:nt.boolean(),indexesOutdated:nt.boolean()}),Qg=(i=>(i.Queued="queued",i.InProgress="in_progress",i.Completed="completed",i.Waiting="waiting",i.Requested="requested",i.Pending="pending",i))(Qg||{}),Zg=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(Zg||{}),s$=nt.object({name:nt.string(),status:nt.nativeEnum(Qg),conclusion:nt.nativeEnum(Zg).nullable()}),Ya=nt.object({sha:nt.string(),message:nt.string(),author:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()}),committer:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()})});import{z as De}from"zod";var eh=De.object({orgId:De.string(),cacheKeys:De.string().array()}),d$=De.object({keyParams:eh,clientMetadata:De.string(),lockAcquisitionTimeoutMs:De.number().optional()}),th=De.object({acquired:De.boolean(),acquiredByMetadata:De.string(),keyPrefix:De.string()}),u$=De.object({keyPrefix:De.string(),result:De.string(),ttlMs:De.number()}),m$=De.union([De.object({keyPrefix:De.string()}),eh]),rv=De.object({remainingTtlMs:De.number(),value:De.string().nullish()}),p$=De.object({results:De.record(De.string(),rv),activeLocks:De.string().array()}),nh=0,rh=5*60*1e3;var S$=90*24*60*60*1e3,y$=7*24*60*60*1e3;import{z as oh}from"zod";var w$=oh.object({quarantineNotifications:oh.string().nullish()});import{z as dt}from"zod";var ov=dt.object({version:dt.string(),json:dt.record(dt.unknown()),hash:dt.string()}),ah=dt.record(dt.unknown()),v$=dt.object({newSvgs:dt.array(ov),metadata:ah.optional()}),av=dt.object({version:dt.string(),json:dt.record(dt.unknown()).nullish(),hash:dt.string(),description:dt.string().nullish(),metadata:ah.nullish()}),ih=dt.record(dt.string().describe("icon hash"),av);import{z as ze}from"zod";var yd=ze.object({assertion:ze.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),iv=ze.object({instruction:ze.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:yd.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),sh=iv.extend({subSteps:ze.lazy(()=>sh.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),lh=ze.object({name:ze.string().describe("Short name describing the test plan"),description:ze.string().nullish().transform(t=>t??void 0).describe("Longer form description of the high level goal of the test plan")}),ch=lh.extend({id:ze.string(),createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string(),createdBy:ze.string(),test:ze.object({id:ze.string(),name:ze.string()}).nullish().transform(t=>t??void 0)}),P$=ch.extend({testGenRuns:ze.tuple([]).or(ze.tuple([ze.object({id:ze.string(),startedAt:ze.coerce.date(),status:ze.nativeEnum(le)})]))}),dh=ze.object({preConditions:yd.array().nullish().transform(t=>t??[]),postConditions:yd.array().nullish().transform(t=>t??[]),steps:sh.array().nullish().transform(t=>t??[])}),M$=ch.extend({plan:dh.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),sv=lh.extend({plan:dh.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),L$=sv.array().nullish().transform(t=>t??[]);import{validator as lv}from"@exodus/schemasafe";function uh(t){let e;try{e=JSON.parse(t)}catch(n){return`The schema is not valid JSON. ${n}`}try{lv(e)}catch(n){return`The schema is not a valid JSON schema. ${n}`}}var mh=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,n])=>e.trim()&&n.trim())))};import{z as K$}from"zod";var As=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};import{z as q}from"zod";var cv=q.object({step:Ge,status:q.nativeEnum(Ee),startedAt:q.coerce.date(),finishedAt:q.coerce.date().optional(),healMetadata:q.object({healType:q.nativeEnum(Na).or(q.literal("AI")),healedAt:q.coerce.date()}).optional(),beforeSnapshotId:q.string().uuid().optional(),afterSnapshotId:q.string().uuid().optional(),message:q.string().optional()}),mj=cv.extend({finishedAt:q.coerce.date().optional().transform(t=>t??new Date)}),ph="1.0.0",bd=Ug.extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),runAttemptSchemaVersion:q.string().optional(),schemaVersion:q.string().optional().default("1.0.19"),results:q.record(q.string(),q.unknown()).array().optional(),beforeResults:q.record(q.string(),q.unknown()).array().optional(),afterResults:q.record(q.string(),q.unknown()).array().optional()}),gh=bd.extend({finishedAt:q.coerce.date().optional().transform(t=>t??new Date)}),pj=bd.merge(_a),gj=gh.merge(_a),hh=q.object({results:q.array(ms),beforeResults:q.array(ms).optional(),afterResults:q.array(ms).optional()}),hj=bd.merge(hh),fj=gh.merge(hh),dv=Fg.merge(_g).extend({executionType:q.nativeEnum(ko).optional().default("WEB"),testId:q.string().uuid(),testDescription:q.string().optional(),runGroupId:q.string().uuid(),status:q.nativeEnum(le),startedAt:q.coerce.date(),attempts:q.number(),failureRecoveryDetails:q.record(q.unknown()).optional()}),Sj=dv.extend({finishedAt:q.coerce.date().optional().transform(t=>t??new Date)}),uv=Ng.merge(kg).extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),cliVersion:q.string(),labels:q.string().array().optional().default([])}),Xa=uv.extend({updatedAt:q.coerce.date().optional().transform(t=>t??new Date),finishedAt:q.coerce.date().optional().transform(t=>t??new Date)});function fh(t){try{return mv(t)&&pv(t).isDirectory()}catch(e){return S.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as vv,input as Av}from"@inquirer/prompts";import{existsSync as xv,mkdirSync as Iv,statSync as Pv}from"fs";import{dirname as Mv}from"path";import An,{supportsColor as Rv}from"chalk";import{Console as Sh}from"console";import{format as Ja}from"util";var Td=class extends Error{constructor(e,n,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,n),Error.stackTraceLimit=o}},xs=class t extends Sh{_buffer=[];_groupDepth=0;Console=Sh;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,n,r,o=2){let a=new Td(void 0,t.write).stack;if(!a)return e;let i=a.split(`
9
+ `),console.log(n(` ${s}:`,l)))}}else if(o)for(let i of o){let s=i;typeof i=="object"&&(s=qa(i,void 0,2),s=s.split(`
10
+ `).map((c,l)=>l>0?` ${c}`:c).join(`
11
+ `)),console.log(" ",n(s))}}getLevel(){return Rs[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=Ka[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,vn.reset,...e)}info(...e){this.logWithLevel(30,vn.white,...e)}debug(...e){this.logWithLevel(20,vn.dim,...e)}warn(...e){this.logWithLevel(40,vn.yellow,...e)}error(...e){this.logWithLevel(50,vn.red,...e)}success(...e){this.logWithLevel(1/0,vn.green,...e)}dimmed(...e){this.logWithLevel(30,vn.dim,...e)}underline(...e){this.logWithLevel(40,vn.underline,...e)}bold(...e){this.logWithLevel(40,vn.bold,...e)}grey(...e){this.logWithLevel(20,vn.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},sd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},IH=new sd,_C=typeof window>"u"&&typeof process<"u"&&id.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?id.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,S=new Ya(_C,{}),Xr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Xr,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Es={},Cs=({logger:t,logKey:e,maxCount:n,intervalMs:r},o,a,...i)=>{let s=Es[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},Es[e]=s),s.totalCount++,s.count<n&&(s.count++,t.debug(o,a,...i)),s.timer=setTimeout(()=>{let c=Es[e];c?.totalCount!==c?.count&&t.debug({logKey:e,totalCount:c?.totalCount,count:c?.count},`Debug logs were rate-limited for ${e}`),delete Es[e]},r)};import{z as Ee}from"zod";var DC=Ee.array(Wo.extend({id:Ee.string(),name:Ee.string(),description:Ee.string().optional(),labels:Ee.string().array().optional()})),FC=Ee.array(Wo.extend({id:Ee.string(),name:Ee.string(),description:Ee.string().optional(),content:Oa})),kH=Ee.object({name:Ee.string(),description:Ee.string().optional(),steps:Ee.array(Hn).optional(),settings:$a.optional(),pathSegments:Ee.string().array()}),_H=Ee.object({id:Ee.string(),fileName:Ee.string(),fullPath:Ee.string(),relativeFilePath:Ee.string().describe("relative to project root")});var DH=Ee.object({steps:Ee.array(Hn).optional(),settings:$a.optional()}),FH=Ee.object({message:Ee.literal("ok")}),UH=Ee.object({tag:Ee.string(),channel:Ee.string(),filePath:Ee.string()}),BH=Ee.object({tests:DC,modules:FC,labels:Ee.string().array()});import{z as Ke}from"zod";var bg=Ke.object({id:Ke.string(),createdAt:Ke.coerce.date(),createdBy:Ke.string(),organizationId:Ke.string(),name:Ke.string(),description:Ke.string().nullish(),enabled:Ke.boolean(),schemaVersion:Ke.string().describe("Schema version for steps"),parameters:Ke.string().array().nullish().describe("Parameter list"),parameterEnums:Ke.record(Ke.string(),Ke.string().array()).nullish(),defaultParameters:Ke.record(Ke.string(),Ke.string()).nullish(),defaultCacheKey:Ke.string().nullish(),defaultCacheTtl:Ke.number().nullish(),defaultCacheAllInvocations:Ke.boolean().nullish(),autoAuth:Ke.boolean().nullish(),advanced:Rc.nullish()}),KH=bg.extend({steps:Ke.lazy(()=>Ie.array())}),Tg=5*60*1e3,ld=Ot.merge(bg.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as JH}from"date-fns-tz";import{z as Oe}from"zod";var cd=Dc.extend({aiAction:Oe.boolean().optional(),stepLintSuggestions:Oe.boolean().optional(),agentConfig:Oe.record(Oe.string(),Oe.string()).optional(),aiFailureAnalysis:Oe.boolean().optional(),aiPageFiltering:Oe.boolean().optional().describe("rag v2 feature flag")}),dd=Oe.object({fakerConstantSeed:Oe.boolean().optional()}),r1=Oe.object({ai:cd.optional(),githubAppInstallationId:Oe.number().nullish(),githubAppSummaryMessageEnabled:Oe.boolean().nullish(),githubReleaseAppInstallationId:Oe.number().nullish(),gitlabAppAccessToken:Oe.string().nullish(),gitlabAppBaseUrl:Oe.string().nullish(),qaseAccessToken:Oe.string().nullish(),testSuggestionsEnabled:Oe.boolean().nullish(),browser:Pc.optional(),advanced:dd.optional()}),o1=Oe.object({globalOverrides:Oe.record(Oe.string()).optional(),agentConfig:Oe.record(Oe.string(),Oe.string()).optional()}),a1=Oe.record(Oe.string(),Oe.string()).nullish();import*as T from"zod";import{z as Ve}from"zod";var ud=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(ud||{});var UC=Ve.object({type:Ve.literal("DESCRIPTION_UPDATE"),thoughts:Ve.string()}),vs=Ve.discriminatedUnion("type",[UC]),BC=Ve.object({testId:Ve.string(),name:Ve.string(),orgId:Ve.string(),runId:Ve.string(),steps:We.array(),purpose:Ve.nativeEnum(ud),details:vs.or(vs.array()).optional()});var c1=BC.pick({name:!0,orgId:!0}),zC=Ve.object({id:Ve.string(),name:Ve.string().nullish(),createdAt:Ve.string().pipe(Ve.coerce.date()).or(Ve.date()),organizationId:Ve.string(),schemaVersion:Ve.string(),runId:Ve.string().nullish(),purpose:Ve.nativeEnum(ud),details:vs.or(vs.array()).optional(),applied:Ve.boolean().nullish(),appliedAt:Ve.coerce.date().nullish()}),wg=zC.extend({steps:We.array()});var Eg="x-momentic-cli-version",HC="x-momentic-main-branch-name",$C="x-momentic-branch-name",jC="x-momentic-commit-timestamp",GC="x-momentic-last-commit-on-main",WC="x-momentic-last-commit-on-main-timestamp",v1=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),A1=kt.merge(Bc),Rg=zi,x1=kt.merge(Bc);var I1=kt.merge(hp).extend({useConsensus:T.boolean().optional(),attemptNumber:T.number().optional()}),md=Em,P1=kt.merge(fp),Cg=Bm,M1=kt.merge(mp),vg=Um,L1=kt.merge(pp),Ag=Fm,O1=kt.merge(gp);var N1=T.object({testPaths:T.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:T.string().optional(),all:T.boolean().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional(),testInputMatrix:T.record(T.string(),T.string()).array().optional()}),xg=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()});var k1=T.string().array(),_1=T.union([T.object({paths:T.string().array().describe("run specific test paths (e.g. todo-test)"),all:T.boolean().describe("run all tests").optional()}),T.object({path:T.string().describe("deprecated; present for backcompat")})]),Ig=T.object({tests:T.record(T.string().describe("Test name"),T.string().describe("Test YAML")),modules:T.record(T.string().describe("Module name"),T.string().describe("Module YAML"))}),VC=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),D1=VC.array(),F1=T.object({testId:T.string(),schemaVersion:T.string()}).merge(zr);function pd(t){let{gitMainBranch:e,gitBranchName:n,gitCommitTimestamp:r,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:a}=t,i={};return e&&(i[HC]=encodeURIComponent(e)),n&&(i[$C]=encodeURIComponent(n)),r&&(i[jC]=r.toISOString()),o&&(i[GC]=encodeURIComponent(o)),a&&(i[WC]=a.toISOString()),i}var U1=T.object({entries:T.array(Om),testId:T.string()}),B1=T.object({entries:T.array(Up),testId:T.string()}),z1=T.object({testId:T.string()});function Pg(t){return T.record(T.unknown()).transform(e=>{let n={};for(let[r,o]of Object.entries(e)){let a=t.safeParse(o);a.success&&(n[r]=a.data)}return n})}var Mg=Pg(Nm),Lg=Pg(Bp),Og=T.object({trigger:T.nativeEnum(Qt),status:T.nativeEnum(ce),startedAt:T.coerce.date().optional(),gitCommitSha:T.string().optional(),gitCommitShaShort:T.string().optional(),gitCommitTimestamp:T.coerce.date().optional(),gitBranchName:T.string().optional(),gitOriginUrl:T.string().optional(),gitCommitMessage:T.string().optional(),gitCommitAuthorName:T.string().optional(),githubRepository:T.string().optional(),gitlabProjectPath:T.string().optional(),pipelineId:T.string().optional(),cliVersion:T.string().optional()}),H1=T.object({id:T.string()}),Ng=T.object({status:T.nativeEnum(ce),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),kg=T.object({stepsSnapshot:T.array(T.record(T.unknown())).optional(),runGroupId:T.string().optional(),testId:T.string(),testName:T.string(),resolvedBaseUrl:T.string().optional(),environmentName:T.string().optional(),labels:T.array(T.string()).optional(),cliVersion:T.string().optional(),trigger:T.nativeEnum(Qt),schemaVersion:T.string().optional(),section:T.nativeEnum(rs).optional(),resolvedInputs:T.record(T.string(),T.string()).optional(),quarantined:T.boolean().optional().default(!1),quarantinedReason:T.string().optional()}),$1=T.object({id:T.string()}),qC=Fc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),_g=qC.array(),Dg=Fc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),j1=T.object({id:T.string()}),Fg=T.object({status:T.nativeEnum(ce),finishedAt:T.coerce.date().optional(),schemaVersion:T.string().optional().default("1.0.19"),results:T.record(T.string(),T.unknown()).array().optional(),beforeResults:T.record(T.string(),T.unknown()).array().optional(),afterResults:T.record(T.string(),T.unknown()).array().optional()}),G1=T.object({screenshot:T.string()}),Ug=T.object({key:T.string()}),Bg=T.object({orgId:T.string(),userId:T.string()}),zg=T.array(qm),W1=T.record(T.string(),T.union([T.string(),T.boolean()])),V1=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),Hg=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),q1=T.object({suiteRunIds:T.string().array()}),K1=lp.array(),Y1=T.object({runGroupIds:T.string().array()}),KC=T.object({uploadUrl:T.string()}),X1=kt.merge(Sp),J1=kt.merge(bp),Q1=kt.merge(yp),YC=T.object({testId:T.string().optional().default(""),testName:T.string().optional().default(""),suiteId:T.string().optional().default(""),suiteName:T.string().optional().default(""),creditsUsed:T.number().optional(),usedBy:T.string().optional()}),XC=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(Ba),properties:YC}),Z1=XC.array(),$g=wg.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),e$=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),jg=rp.array(),t$=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),Gg=KC.extend({id:T.string()}),n$=T.object({runGroupId:T.string().uuid().optional()}),Wg=T.object({runGroupId:T.string().uuid()}),Vg=T.object({quarantined:T.object({testId:T.string().uuid(),quarantinedAt:T.coerce.date(),quarantinedBy:T.string().optional(),quarantinedReason:T.string()}).array()}),r$=T.object({testId:T.string().uuid(),testName:T.string().optional(),reason:T.string(),gitLocalUsername:T.string().optional(),gitLocalEmail:T.string().optional(),gitLocalName:T.string().optional()}),o$=T.object({testName:T.string().optional(),reason:T.string().optional(),gitLocalUsername:T.string().optional(),gitLocalEmail:T.string().optional(),gitLocalName:T.string().optional()}),a$=kt.merge(Ep),i$=kt.merge(Rp),s$=T.object({apkToInstall:T.object({channel:T.string(),tag:T.string().optional()}).optional(),hostname:T.string().optional(),region:T.nativeEnum(Ha).optional()}),qg=T.object({name:T.string(),webRtcUrl:T.string(),adbUrl:T.string(),token:T.string(),apkDownloadUrl:T.string().optional(),region:T.string().optional()}),l$=T.object({channel:T.string(),tag:T.string(),md5:T.string()}),Kg=T.object({id:T.string(),uploadUrl:T.string().optional(),downloadUrl:T.string(),md5:T.string().optional()}),Yg=T.object({assets:T.array(T.object({channel:T.string(),tag:T.string(),md5:T.string(),createdAt:T.number().describe("Unix timestamp in milliseconds")}))});import{z as Y}from"zod";var u$=Y.object({localTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()}).or(Y.object({cloudTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()})),Xg=(n=>(n.QUARANTINE="QUARANTINE",n.UNQUARANTINE="UNQUARANTINE",n))(Xg||{});var gd=Y.object({name:Y.string(),description:Y.string().nullish(),effect:Y.nativeEnum(Xg),labels:Y.array(Y.string()),githubRepository:Y.string().nullish(),gitlabProjectPath:Y.string().nullish(),gitBranchName:Y.string().nullish()}),JC=Y.object({type:Y.literal("LAST_N_RUNS"),lastN:Y.number().min(1).max(10)}),QC=Y.object({type:Y.literal("LAST_N_HOURS"),lastN:Y.number().min(1).max(24)}),ZC=Y.object({type:Y.literal("LAST_N_DAYS"),lastN:Y.number().min(1).max(7)}),hd=Y.discriminatedUnion("type",[JC,QC,ZC]),ev=Y.object({flakeRateThreshold:Y.number().min(1).max(100),evaluationWindow:hd}),tv=gd.extend({type:Y.literal("FLAKE_RATE"),config:ev}),nv=Y.object({passRateThreshold:Y.number().min(1).max(100),evaluationWindow:hd}),rv=gd.extend({type:Y.literal("PASS_RATE"),config:nv}),ov=Y.object({failureCountThreshold:Y.number().min(0),evaluationWindow:hd}),av=gd.extend({type:Y.literal("FAILURE_COUNT"),config:ov}),m$=Y.discriminatedUnion("type",[tv,rv,av]);import{z as ot}from"zod";var h$=ot.object({repositoriesIndexed:ot.boolean(),indexingInProgress:ot.boolean(),indexesOutdated:ot.boolean()}),Jg=(i=>(i.Queued="queued",i.InProgress="in_progress",i.Completed="completed",i.Waiting="waiting",i.Requested="requested",i.Pending="pending",i))(Jg||{}),Qg=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(Qg||{}),f$=ot.object({name:ot.string(),status:ot.nativeEnum(Jg),conclusion:ot.nativeEnum(Qg).nullable()}),Xa=ot.object({sha:ot.string(),message:ot.string(),author:ot.object({name:ot.string().optional(),email:ot.string().optional(),date:ot.coerce.date().optional()}),committer:ot.object({name:ot.string().optional(),email:ot.string().optional(),date:ot.coerce.date().optional()})});import{z as Fe}from"zod";var Zg=Fe.object({orgId:Fe.string(),cacheKeys:Fe.string().array()}),b$=Fe.object({keyParams:Zg,clientMetadata:Fe.string(),lockAcquisitionTimeoutMs:Fe.number().optional()}),eh=Fe.object({acquired:Fe.boolean(),acquiredByMetadata:Fe.string(),keyPrefix:Fe.string()}),T$=Fe.object({keyPrefix:Fe.string(),result:Fe.string(),ttlMs:Fe.number()}),w$=Fe.union([Fe.object({keyPrefix:Fe.string()}),Zg]),iv=Fe.object({remainingTtlMs:Fe.number(),value:Fe.string().nullish()}),E$=Fe.object({results:Fe.record(Fe.string(),iv),activeLocks:Fe.string().array()}),th=0,nh=5*60*1e3;var A$=90*24*60*60*1e3,x$=7*24*60*60*1e3;import{z as rh}from"zod";var M$=rh.object({quarantineNotifications:rh.string().nullish()});import{z as ut}from"zod";var sv=ut.object({version:ut.string(),json:ut.record(ut.unknown()),hash:ut.string()}),oh=ut.record(ut.unknown()),k$=ut.object({newSvgs:ut.array(sv),metadata:oh.optional()}),lv=ut.object({version:ut.string(),json:ut.record(ut.unknown()).nullish(),hash:ut.string(),description:ut.string().nullish(),metadata:oh.nullish()}),ah=ut.record(ut.string().describe("icon hash"),lv);import{z as ze}from"zod";var fd=ze.object({assertion:ze.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),cv=ze.object({instruction:ze.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:fd.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),ih=cv.extend({subSteps:ze.lazy(()=>ih.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),sh=ze.object({name:ze.string().describe("Short name describing the test plan"),description:ze.string().nullish().transform(t=>t??void 0).describe("Longer form description of the high level goal of the test plan")}),lh=sh.extend({id:ze.string(),createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string(),createdBy:ze.string(),test:ze.object({id:ze.string(),name:ze.string()}).nullish().transform(t=>t??void 0)}),U$=lh.extend({testGenRuns:ze.tuple([]).or(ze.tuple([ze.object({id:ze.string(),startedAt:ze.coerce.date(),status:ze.nativeEnum(ce)})]))}),ch=ze.object({preConditions:fd.array().nullish().transform(t=>t??[]),postConditions:fd.array().nullish().transform(t=>t??[]),steps:ih.array().nullish().transform(t=>t??[])}),B$=lh.extend({plan:ch.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),dv=sh.extend({plan:ch.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),z$=dv.array().nullish().transform(t=>t??[]);import{validator as uv}from"@exodus/schemasafe";function dh(t){let e;try{e=JSON.parse(t)}catch(n){return`The schema is not valid JSON. ${n}`}try{uv(e)}catch(n){return`The schema is not a valid JSON schema. ${n}`}}var uh=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,n])=>e.trim()&&n.trim())))};import{z as rj}from"zod";var As=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};import{z as K}from"zod";var mv=K.object({step:We,status:K.nativeEnum(we),startedAt:K.coerce.date(),finishedAt:K.coerce.date().optional(),healMetadata:K.object({healType:K.nativeEnum(Na).or(K.literal("AI")),healedAt:K.coerce.date()}).optional(),beforeSnapshotId:K.string().uuid().optional(),afterSnapshotId:K.string().uuid().optional(),message:K.string().optional()}),wj=mv.extend({finishedAt:K.coerce.date().optional().transform(t=>t??new Date)}),mh="1.0.0",Sd=Fg.extend({id:K.string().uuid().optional(),startedAt:K.coerce.date(),runAttemptSchemaVersion:K.string().optional(),schemaVersion:K.string().optional().default("1.0.19"),results:K.record(K.string(),K.unknown()).array().optional(),beforeResults:K.record(K.string(),K.unknown()).array().optional(),afterResults:K.record(K.string(),K.unknown()).array().optional()}),ph=Sd.extend({finishedAt:K.coerce.date().optional().transform(t=>t??new Date)}),Ej=Sd.merge(_a),Rj=ph.merge(_a),gh=K.object({results:K.array(ms),beforeResults:K.array(ms).optional(),afterResults:K.array(ms).optional()}),Cj=Sd.merge(gh),vj=ph.merge(gh),pv=Dg.merge(kg).extend({executionType:K.nativeEnum(ko).optional().default("WEB"),testId:K.string().uuid(),testDescription:K.string().optional(),runGroupId:K.string().uuid(),status:K.nativeEnum(ce),startedAt:K.coerce.date(),attempts:K.number(),failureRecoveryDetails:K.record(K.unknown()).optional()}),Aj=pv.extend({finishedAt:K.coerce.date().optional().transform(t=>t??new Date)}),gv=Og.merge(Ng).extend({id:K.string().uuid().optional(),startedAt:K.coerce.date(),cliVersion:K.string(),labels:K.string().array().optional().default([])}),Ja=gv.extend({updatedAt:K.coerce.date().optional().transform(t=>t??new Date),finishedAt:K.coerce.date().optional().transform(t=>t??new Date)});function hh(t){try{return hv(t)&&fv(t).isDirectory()}catch(e){return S.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as Iv,input as Pv}from"@inquirer/prompts";import{existsSync as Mv,mkdirSync as Lv,statSync as Ov}from"fs";import{dirname as Nv}from"path";import An,{supportsColor as Av}from"chalk";import{Console as fh}from"console";import{format as Qa}from"util";var yd=class extends Error{constructor(e,n,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,n),Error.stackTraceLimit=o}},xs=class t extends fh{_buffer=[];_groupDepth=0;Console=fh;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,n,r,o=2){let a=new yd(void 0,t.write).stack;if(!a)return e;let i=a.split(`
12
12
  `).slice(o).filter(Boolean).join(`
13
- `);return e.push({message:r,origin:i,type:n}),e}_log(e,n){t.write(this._buffer,e," ".repeat(this._groupDepth)+n,3)}debug(e,...n){this._log("debug",Ja(e,...n))}error(e,...n){this._log("error",Ja(e,...n))}info(e,...n){this._log("info",Ja(e,...n))}log(e,...n){this._log("log",Ja(e,...n))}warn(e,...n){this._log("warn",Ja(e,...n))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function yh(t){let e=globalThis.console,n=new xs;globalThis.console=n;try{t()}finally{let o=n.getBuffer()?.map(a=>a.message).join(`
13
+ `);return e.push({message:r,origin:i,type:n}),e}_log(e,n){t.write(this._buffer,e," ".repeat(this._groupDepth)+n,3)}debug(e,...n){this._log("debug",Qa(e,...n))}error(e,...n){this._log("error",Qa(e,...n))}info(e,...n){this._log("info",Qa(e,...n))}log(e,...n){this._log("log",Qa(e,...n))}warn(e,...n){this._log("warn",Qa(e,...n))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Sh(t){let e=globalThis.console,n=new xs;globalThis.console=n;try{t()}finally{let o=n.getBuffer()?.map(a=>a.message).join(`
14
14
  `);process.stderr.write(`${o}
15
- `),globalThis.console=e}}var Ke=" ".repeat(6);function bh(t,e="",n=!1){let r=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(r-e.length,20),a=t.split(`
16
- `),i=[];for(let s of a)if(n){let l=s;for(;l.length>o;){let d=l.slice(0,o+1).lastIndexOf(" "),u=d>-1?d:o;i.push(e+l.slice(0,u)),l=l.slice(u).trimStart()}i.push(e+l)}else{let l=s.split(" "),c="";for(let d of l){if(!c.length){c=d;continue}let u=`${c} ${d}`;u.length<=o?c=u:(i.push(e+c),c=d)}i.push(e+c)}return i.join(`
17
- `)}import hv from"os";import Th,{multistream as fv}from"pino";import Sv from"pino-pretty";import yv from"pino-std-serializers";var Qa=new Map,bv=!0,wh="Log throttle exceeded",Tv=100,wv=5e3,wd=class t{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:n,disableConsoleLogs:r,flushIntervalMs:o,maxBatchSize:a}){this.hostname=n??hv.hostname(),this.disableConsoleLogs=r,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=a??10;let i={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=bv?Th(i):Th(i,fv([{stream:Sv({colorize:!0})}]))}getLevel(){return Rs[this.minLevelValue]}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let n=await fetch(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Va(e)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch(n){this.consoleLogger.warn({err:n},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===wh)return!0;let n=Date.now();return n-this.lastWindowStart>wv&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,wh),this.droppedLogsInWindow=!1,this.lastWindowStart=n),this.logsInCurrentWindow<Tv?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,n,r,...o){try{this.logHelper(e,n,r,...o)}catch(a){this.consoleLogger.warn(`Failed to log to Signoz: ${a}`)}}logHelper(e,n,r,...o){if(qa[e]<this.minLevelValue||!this.shouldAllowLog(r))return;typeof n=="string"&&!r&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=yv.err(n.err));let a={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...o.length>0?{args:o}:{}},i={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](a,r,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:i,attributes:{},body:bg({message:r||"",...a})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let n=this.bindingAttributes.app;this.bindingAttributes.app=e,Qa.set("app",this),Qa.delete(n)}debug(e,n,...r){this.log("debug",e,n,...r)}info(e,n,...r){this.log("info",e,n,...r)}warn(e,n,...r){this.log("warn",e,n,...r)}error(e,n,...r){this.log("error",e,n,...r)}bindings(){return this.bindingAttributes}addBinding(e,n){this.bindingAttributes[e]=n}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=Rs[e]):(this.minLevelValue=qa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Is=({app:t,hostname:e,disableConsoleLogs:n})=>(Qa.has(t)||Qa.set(t,new wd({bindings:{app:t},hostname:e,disableConsoleLogs:n})),Qa.get(t));import{hostname as Ev}from"os";var X=Is({app:"cli",hostname:Ev(),disableConsoleLogs:!0}).child({cliVersion:"2.16.0"});var Cv=5;async function Ms({getResults:t,checkDone:e,name:n,timeoutMs:r=18e5}){let o=Date.now(),a=0;for(;Date.now()-o<r;){let i;a>Cv&&(S.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{i=await t(),a=0}catch(c){a++,X.warn({err:c},"Failed to fetch run status, retrying..."),S.warn({err:c},"Failed to fetch run status, retrying..."),await new Promise(d=>setTimeout(d,1500*a));continue}if(e(i))return i;let l=Math.max(1e4,Math.floor(r/100));await new Promise(c=>setTimeout(c,l))}S.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(r/1e3)}s).`),process.exit(1)}function Vo({results:t,startTime:e,entity:n,getDisplayLine:r,onFailed:o}){let a=t.filter(d=>d.status==="PASSED"&&d.quarantined),i=t.filter(d=>d.status==="PASSED"&&!d.quarantined),s=t.filter(d=>d.status==="FAILED"&&d.quarantined),l=t.filter(d=>d.status==="FAILED"&&!d.quarantined),c=t.filter(d=>d.status==="CANCELLED");return yh(()=>{if(l.forEach(d=>{S.log(""),o(d)}),l.length){S.log("");let d=l.length===1?"":"s";S.error(`${l.length} ${n}${d} failed:`),l.forEach(u=>{S.dimmed(r(u))})}if(c.length){S.log("");let d=c.length===1?"":"s";S.warn(`${c.length} ${n}${d} cancelled:`),c.forEach(u=>{S.dimmed(r(u))})}if(i.length){S.log("");let d=i.length===1?"":"s";S.success(`${i.length} ${n}${d} passed:`),i.forEach(u=>{S.dimmed(r(u))})}if(s.length){S.log("");let d=s.length===1?"":"s";S.warn(`${s.length} quarantined ${n}${d} failed:`),s.forEach(u=>{S.dimmed(r(u))})}if(a.length){S.log("");let d=a.length===1?"":"s";S.warn(`${a.length} quarantined ${n}${d} passed:`),a.forEach(u=>{S.dimmed(r(u))})}S.log(""),S.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:a.length,passed:i.length,quarantinedFailed:s.length,failed:l.length,cancelled:c.length}}var Ls=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let n=Ki[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||No[t.failureReason],o=t.failureDetails.classification?.rootCause;if(S.error(e),o){S.log(`${Ke}- Error type: ${An.dim(n)}`);let a="- Root cause analysis:",i=bh(`${a} ${o}`,`${Ke} `,!1),s=i.indexOf(":");S.log(`${Ke}${a} ${An.dim(i.slice(s+1))}`)}else S.log(`${Ke}Reason: ${An.red(n)}`),S.log(`${Ke}Description: ${An.red(r)}`)},Za=({status:t,testLogRef:e,getRunningTestsCount:n,getTotalTestsCount:r,additionalText:o})=>{t=t.toUpperCase();let a=t,i;t.includes("FAIL")?(a=An.bgRed.white("FAIL"),i=3):t.includes("PASS")?(a=An.bgGreen.white("PASS"),i=3):t.includes("START")?(a=An.bgBlue.white("START"),i=2):t.includes("CANCEL")?(a=An.bgRgb(191,68,11).white("CANCEL"),i=1):t.includes("RETRY")?(a=An.bgRgb(191,68,11).white("RETRY"),i=2):t.includes("RUN")||t.includes("PROG")?(a=An.bgMagenta.white("RUNNING"),i=0):(S.warn(`Unknown status tried to be logged in run test locally: ${t}`),i=0),Rv||(a=`${a}`),S.log(`${a}${" ".repeat(i)} ${e} ${o?`${o} `:""}(${n()}/${r()})`)};var Lv=!1,Rh=(()=>{try{return Pv("/.dockerenv"),!0}catch{return!1}})();async function bt(t,e){return Ea||Lv||Rh?!0:(S.flush(),X.flush(),await new Promise(r=>setTimeout(r,500)),await vv({message:t}))}async function Ed(t){let e=Mv(t);return fh(e)?xv(t)?bt(`File '${Eh(t)}' already exists. Overwrite existing content?`,!0):!0:await bt(`Directory '${Eh(e)}' doesn't exist. Create it now?`,!0)?(Iv(e,{recursive:!0}),!0):!1}function Eh(t){return t.replace(/(\s+)/g,"\\$1")}async function Ch(t,e){return Ea||Rh?e:(await Av({message:t,default:e})).trim()||e}import Ov from"fs";import{tmpdir as Nv}from"os";import kv from"path";import{registry as ei}from"playwright-core/lib/server";import vh from"proper-lockfile";var Ah=kv.join(Nv(),"momenticBrowserInstallation");var Rd=["chrome","chromium","chrome-for-testing"],_v={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},xh={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function Ih(t){let e=xh[_v[t]??""]??"",n=ei.findExecutable(e);return!n||n.installType==="none"?!1:Cd(n)}function Cd(t){let e=t.executablePath();return Ov.existsSync(e)}function Dv(t,e){let n=xh[t];if(!n)throw new Error(`Requested install of unknown browser type ${t}`);let r=ei.findExecutable(n);if(!r||r.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&&Cd(r)))return r}async function Fv({browser:t,force:e}){let n=Dv(t,e);if(!n){S.info(`Browser '${t}' is already installed, skipping...`);return}S.info(`Installing browser '${t}'...`);try{await ei.installDeps([n],!1),await ei.install([n],!1)}catch(r){if(r.message.includes("Lock file is already being held")){S.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ei.findExecutable(t),a=5*60*1e3,i=Date.now();for(;Date.now()-i<a&&!Cd(o);)S.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw r}}async function Ph({rawBrowsers:t,force:e=!1,all:n=!1}){let r=n?Rd:Array.from(new Set(t));try{await vh.lock(Ah,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(a){S.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${a}. Continuing without installation...`);return}let o;try{for(let a of r)try{await Fv({browser:a,force:e})}catch(i){o=i,S.error(`Failed to install the ${a} browser: ${i}`)}}finally{await vh.unlock(Ah,{realpath:!1})}if(o)throw o}import{randomUUID as nN}from"crypto";import jb from"body-parser";import VL from"cors";import qL from"dedent";import{Router as AA}from"express";import It from"fs";import{globSync as xA}from"glob";import lt from"path";import Ud from"fs";import{z as Ad}from"zod";var z="v1",ti="2.16.0";var pr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Mh=t=>{let e=t.reason===void 0?new DOMException("This operation was aborted.","AbortError"):t.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function H(t,e){let{milliseconds:n,fallback:r,message:o,customTimers:a={setTimeout,clearTimeout}}=e,i,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);return new Promise((l,c)=>{if(e.signal){let{signal:u}=e;if(u.aborted)return c(Mh(u));s=()=>c(Mh(u)),u.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(u){c(u)}else{typeof t.cancel=="function"&&Promise.resolve().then(()=>t.cancel()).catch(()=>{});let u=o instanceof Error?o:new pr(o??`Promise timed out after ${n}ms`);c(u)}};i=a.setTimeout(d,n),Promise.resolve(t).then(u=>l(u)).catch(u=>c(u))}).finally(()=>{a.clearTimeout(i),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var Os=class{limit;windowMs;userActions;constructor(e,n){this.limit=e,this.windowMs=n,this.userActions=new Map}_cleanup(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;if(this.userActions.has(o)){let i=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];i.length>0?this.userActions.set(o,i):this.userActions.delete(o)}}increment(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;this._cleanup(n,e),this.userActions.has(o)||this.userActions.set(o,[]);let a=this.userActions.get(o);return a.length>=this.limit?!0:(a.push(r),!1)}};var Uv=9e4,Bv=3,zv=1500,Hv=15e3,cn=class extends Error{status;rawError;constructor(e,n,r,o={}){super(r,o),this.status=e,this.rawError=n}};async function $v(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var vd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ti&&(e[Rg]=ti),e}async sendRequest(e,n){let{retries:r=Bv,requestTimeoutMs:o=Uv,initialRetryDelayMs:a=zv,maxRetryDelayMs:i=Hv}=n,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:n.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,n,o)}catch(u){if(c=u,u instanceof cn&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError"&&(c=new pr),s===0)throw c;let m=l-s,p=Math.min(a*Math.pow(2,m-1),i);await new Promise(g=>setTimeout(g,p))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,n,r){let o={path:e,baseUrl:this.baseUrl,method:n.method},a=new AbortController,i=setTimeout(()=>a.abort(),r),s=()=>a.abort();n.signal&&n.signal.addEventListener("abort",s);let l={...this.getHeaders(),...n.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:l,signal:a.signal});if(!c.ok){let u=await $v(c);throw new cn(c.status,u,`Request to ${n.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&&n.logResponse===!0&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(i),n.signal&&n.signal.removeEventListener("abort",s)}}},xt=class extends vd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Je=class extends xt{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${z}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return zg.parse(e)}async bulkGetRunStatus(e){let n=await this.sendRequest(`/${z}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Dg.parse(n)}async getTestYAMLExport(e){let n=await this.sendRequest(`/${z}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Pg.parse(n)}async updateStepCaches(e,n){await this.sendRequest(`/${z}/cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,n){let r=await this.sendRequest(`/${z}/cache`,{method:"POST",body:e,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Lg.parse(r)}async updateMobileStepCaches(e,n){await this.sendRequest(`/${z}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,n){let r=await this.sendRequest(`/${z}/mobile-cache`,{method:"POST",body:e,extraHeaders:n,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Og.parse(r)}async queueTests(e){let n=await this.sendRequest(`/${z}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ig.parse(n)}async uploadScreenshot(e){let n=await this.sendRequest(`/${z}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Bg.parse(n)}async getAllEnvironments(){let e=await this.sendRequest(`/${z}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Hg.parse(e)}async acquireCacheLock(e,n){let r=await this.sendRequest(`/${z}/result-cache/lock`,{method:"POST",body:e,signal:n,retries:3,requestTimeoutMs:3e4});return th.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${z}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${z}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(e){let n=await this.sendRequest(`/${z}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $g.parse(n)}async bulkGetRunGroupStatus(e){let n={runGroupIds:e},r=await this.sendRequest(`/${z}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return ip.array().parse(r)}async uploadProposedSteps(e,n){try{await this.sendRequest(`/${z}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){n.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,n){try{await this.sendRequest(`/${z}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let n=await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return jg.parse(n)}async patchTestFragment(e,n){await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,n){let r=await this.sendRequest(`/${z}/results/tests/${e}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Gg.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${z}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Wg.parse(e)}async startProcessingResultsUpload(e,n){let r=await this.sendRequest(`/${z}/results/uploads/${e}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Vg.parse(r)}async fetchIconKnowledgeBase(e){try{let n=await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ih.parse(n)}catch(n){return e.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,n){try{await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(r){n.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,n,r,o){let a=new URLSearchParams;a.set("base",r),a.set("head",o);let i=await this.sendRequest(`/${z}/git/github/${e}/${n}/merge-base-commit?${a.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ya.parse(i)}async getCommitFromGithub(e,n,r){let o=await this.sendRequest(`/${z}/git/github/${e}/${n}/commits/${r}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ya.parse(o)}async getMergeBaseCommitFromGitlab(e,n,r){let o=new URLSearchParams;o.set("base",n),o.set("head",r);let a=await this.sendRequest(`/${z}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ya.parse(a)}async getCommitFromGitlab(e,n){let r=await this.sendRequest(`/${z}/git/gitlab/${e}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ya.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${z}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ad.record(Ad.string(),Ad.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${z}/quarantine`,{method:"GET"});return qg.parse(e)}async quarantineTest(e,n,r){await this.sendRequest(`/${z}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,n,r){await this.sendRequest(`/${z}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let n=await this.sendRequest(`/${z}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Kg.parse(n)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${z}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:n,md5:r}){let o={channel:e,tag:n,md5:r},a=await this.sendRequest(`/${z}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Yg.parse(a)}async deleteAndroidEmulator(e){await this.sendRequest(`/${z}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${z}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Xg.parse(e)}async deleteAndroidAsset(e,n){await this.sendRequest(`/${z}/limbar/assets/${e}/${n}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function xd(t){let e=process.versions.node,n=parseInt(e.split(".")[0]);(isNaN(n)||n<18)&&(S.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),S.debug(`Identified node version ${e}`);let r=await t.client.getAuthInfo();return S.debug("Got auth info from API"),r}import{randomUUID as Lh}from"crypto";var Ns=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,n,r){try{return await this.apiClient.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:r?.eventId??Lh(),properties:Yc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,n,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??Lh(),properties:Yc({creditsUsed:r,usedBy:n},o)}])}catch(a){e.error({err:a},"Failed to report credits used")}}};var qo=class{constructor(e,n){this.client=e;this.orgId=n}async acquireCacheLock(e,n){return this.client.acquireCacheLock(e,n)}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,n){return this.client.saveNewIcons(e,n)}};import{Faker as jv,en as Gv}from"@faker-js/faker";var Ko="v1",gr=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 jv({locale:Gv}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let n=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ko}/tools/ai/generate`,{method:"POST",body:n}).catch(r=>{throw r instanceof cn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ko}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ko}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof cn?new Error(n.rawError):n})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/fetchAll`,{method:"POST",body:e}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}};import{z as Wv}from"zod";var Yo=class extends xt{agentConfig;constructor(e,n){super(n),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,n){let r={...e,loggerTags:n.loggerTags},o=await this.sendRequest(`/${z}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:n.abortSignal});return mp.parse(o)}async rankChunksWithRag(e,n){let r=await this.sendRequest(`/${z}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ti,...e},signal:n.abortSignal});return up.parse(r)}async getScreenshotFromS3(e){let n=await this.sendRequest(`/${z}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return Wv.string().parse(n)}async getElementLocation(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${z}/web-agent/locate-element`,{method:"POST",body:r,signal:n.abortSignal});return Ag.parse(o)}async getAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${z}/web-agent/assertion`,{method:"POST",body:r,signal:n.abortSignal});return gd.parse(o)}async getLintStepResult(e,n){let r={...e,disableCache:!!n.disableCache,loggerTags:n.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/step`,{method:"POST",body:r,signal:n.abortSignal});return vg.parse(o)}async getVisualAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${z}/web-agent/visual-assertion`,{method:"POST",body:r,signal:n.abortSignal});return gd.parse(o)}async getAiActionCommand(e,n){let r=await this.sendRequest(`/${z}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Cg.parse(r)}async getMultiturnAiActionCommand(e,n){return await this.sendRequest(`/${z}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(e,n){let r=await this.sendRequest(`/${z}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Lc.parse(r)}async getReverseMappedDescription(e,n){let r=await this.sendRequest(`/${z}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return xg.parse(r)}async getTextExtraction(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${z}/web-agent/text-extraction`,{method:"POST",body:r,signal:n.abortSignal});return Pc.parse(o)}async getTestResultClassification(e,n){let r=await this.sendRequest(`/${z}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return kc.parse(r)}async getExtractedKeywords(e,n){let r=await this.sendRequest(`/${z}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:n.disableCache,context:e},signal:n.abortSignal});return wp.parse(r)}async getAutohealingProposal(e,n){let r=await this.sendRequest(`/${z}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return Hm.parse(r)}async getFailureRecoveryProposal(e,n){let r=await this.sendRequest(`/${z}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return jm.parse(r)}async getFailureRecoveryPlan(e,n){let r=await this.sendRequest(`/${z}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return $m.parse(r)}async getIframeRegex(e,n){let r=await this.sendRequest(`/${z}/web-agent/iframe-regex`,{method:"POST",body:e,signal:n.abortSignal});return Tm.parse(r)}};var Xo=class extends xt{generator;constructor(e,n){super(e),this.generator=n}async runTemplateMatching(e,n={}){let r=await this.sendRequest(`/${z}/web-agent/template-matching`,{method:"POST",body:e,signal:n?.signal});return wm.parse(r)}async constructIframeRegex(e,n={}){return this.generator.getIframeRegex(e,{abortSignal:n.signal})}};function Oh(t,e,n){return fetch(t,{method:"PUT",body:n,headers:{"Content-Type":e}})}var ks=class{constructor(e){this.client=e}async uploadResultsArchive(e,n){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),a=await Oh(r,"application/zip",n);if(!a.ok)throw new Error(`Failed to upload test results: ${await a.text()}`);let{runGroupId:i}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return i}};import{diff as Dh}from"deep-object-diff";function ni(t){let e={parentChain:[]};return _s(t,e),e}function _s(t,e){let{onPresetAction:n,onSimpleStepContainer:r,onConditional:o,earlyStop:a}=t;for(let i of t.steps)switch(i.type){case"PRESET_ACTION":if(n(i,e)&&a)return!0;break;case"CONDITIONAL":if(o?.(i,e)&&a)return!0;e.parentChain.push(i);for(let l of i.blocks)if(n(l.assertion,e)&&a||_s({...t,steps:l.steps},e)&&a)return!0;if(_s({...t,steps:i.elseSteps??[]},e)&&a)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(r?.(i,e)&&a)return!0;if(i.steps){if(e.parentChain.push(i),_s({...t,steps:i.steps},e)&&a)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(i,e)&&a)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(i)}}function Nh(t,e,n,r){let o=Array.from(e),a=Array.from(r);for(let s=0;s<o.length;s++){if(o[s]!==a[s])return!1;a.shift()}return!!Vv([t],n,a).result}function Vv(t,e,n=[]){let r,o=[],a=(i,s)=>{let l=JSON.stringify(s.parentChain.map(d=>d.id)),c=n.length===0?!0:JSON.stringify(n)===l;return i.id===e&&c?(r=i,o=s.parentChain,!0):!1};return ni({steps:t,earlyStop:!0,onPresetAction:a,onConditional:a,onSimpleStepContainer:a}),{result:r,parentChain:o}}function kh(t,e){e(t);for(let n in t){let r=t[n];r&&(Array.isArray(r)?Fs(r,e):typeof r=="object"&&kh(r,e))}}function Fs(t,e){for(let n of t)n&&(Array.isArray(n)?Fs(n,e):typeof n=="object"&&kh(n,e))}function Id(t,e){if(t.length>e.length)return Id(e,t);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Ds(t){for(let e of t.results)switch(e.type){case"PRESET_ACTION":t.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":t.onSimpleStepContainer?.(e),Ds({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),Ds({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}import{cloneDeep as _h}from"lodash-es";import{v4 as Pd}from"uuid";async function He(t){let e=new Map,n=new Set,r=_h(t.stepLists.steps),o=await Jr({...t,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n}),a={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let i of["beforeSteps","afterSteps"]){let s=_h(t.stepLists[i]);if(!s)continue;let l=await Jr({...t,steps:s,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n});a.cachesToSave.push(...l.cachesToSave),a.moduleUpdates.push(...l.moduleUpdates),a.stepsToSave[i]=l.stepsToSave}return a}async function Jr({steps:t,...e}){let{seenModules:n,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:a,moduleIdReplacements:i,shouldCreateNewModuleId:s,createNewCacheIds:l}=e,c={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let d of t)switch(delete d.index,delete d.aiSuggested,d.id=l?Pd():d.id,d.type){case"PRESET_ACTION":{let m=d.command;m.id=l?Pd():m.id,"cache"in m&&m.cache&&(r&&(c.cachesToSave=c.cachesToSave.concat(Md({id:m.id,orgId:r.orgId,testId:r.testId,value:Bn.parse(m),moduleIdParents:o,moduleStepParents:a}))),delete m.cache),m.thoughts&&delete m.thoughts,c.stepsToSave.push({...d,command:m});break}case"RESOLVED_MODULE":{let m=l?Pd():d.id,p=d.moduleId;i.has(p)?p=i.get(p):s!==void 0&&(p=await s(d),i.set(d.moduleId,p));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await Jr({...e,steps:d.steps,cacheCreationParams:r?{...r}:void 0,createNewCacheIds:!1,moduleStepParents:[...a,m],moduleIdParents:[...o,p],skipCacheIntermediateEntries:l});c.moduleUpdates=c.moduleUpdates.concat(f),c.cachesToSave=c.cachesToSave.concat(g),n.has(p)||(n.add(p),c.moduleUpdates.push({...Ot.parse(d),steps:Me.array().parse(h),moduleId:p}));let y=sn.parse({...d,type:"MODULE",moduleId:p,inputs:d.inputs,id:m,skipped:d.skipped,cacheConfig:d.cacheConfig,envKey:d.envKey});c.stepsToSave.push(y);break}case"AI_ACTION":{if(!d.steps){c.stepsToSave.push(d);break}let{stepsToSave:m,cachesToSave:p}=await Jr({...e,steps:d.steps});try{d.steps=Ht.array().parse(m)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}c.stepsToSave.push(d),c.cachesToSave=c.cachesToSave.concat(p);break}case"AI_ACTION_DYNAMIC":{c.stepsToSave.push(d);break}case"CONDITIONAL":{let m=[];for(let g of d.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:y}=await Jr({...e,steps:g.steps});m.push({...g,steps:h}),c.cachesToSave=c.cachesToSave.concat(f),c.moduleUpdates=c.moduleUpdates.concat(y)}let p={...d,elseSteps:void 0,blocks:m};if(d.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await Jr({...e,steps:d.elseSteps});p.elseSteps=g,c.cachesToSave=c.cachesToSave.concat(h),c.moduleUpdates=c.moduleUpdates.concat(f)}c.stepsToSave.push(p);break}case"SECTION":{let{stepsToSave:m,cachesToSave:p,moduleUpdates:g}=await Jr({...e,steps:d.steps}),h={...d,steps:m};c.moduleUpdates=c.moduleUpdates.concat(g),c.stepsToSave.push(h),c.cachesToSave=c.cachesToSave.concat(p);break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return c}function Jo({steps:t,topLevel:e=!0,...n}){let{stepCacheEntries:r,logger:o,keyPrefix:a}=n,i=[],s=[],l=[],c=0,d=(m,p)=>{try{let g=Bn.parse(p.value);if(g.type!==m.type){o.warn({parsedCacheEntry:g,command:m},"Not using step cache due to type mismatch"),s.push(p.key);return}m.cache=g.cache,i.push(p.key),l.push(p.uniqueKey)}catch(g){s.push(p.key),o.error({err:g,cacheEntry:p},"Not using step cache due to parsing error")}},u=(m,p)=>{let g=Kv(m.id,p),h=g.find(f=>!!r[f]);if(h)d(m,r[h]);else{if(m.type==="AI_ASSERTION")return;s.push(g[0])}};for(let m of t)switch(m.type){case"RESOLVED_MODULE":{c+=m.steps.length;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.steps,keyPrefix:a?`${a}:${m.id}`:m.id,topLevel:!1});i.push(...p),s.push(...g),l.push(...h);break}case"SECTION":case"AI_ACTION":{if(c+=m.steps?.length??0,!m.steps?.length)break;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.steps,topLevel:!1});i.push(...p),s.push(...g),l.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!$i.includes(m.command.type)||(m.command.type==="TYPE"||m.command.type==="MOUSE_DRAG"||m.command.type==="VISUAL_DIFF"||m.command.type==="SCROLL_DOWN"||m.command.type==="SCROLL_UP"||m.command.type==="SCROLL_LEFT"||m.command.type==="SCROLL_RIGHT")&&!m.command.target||"cache"in m.command&&m.command.cache)continue;c++,u(m.command,a);break}case"CONDITIONAL":{for(let p of m.blocks){c++,u(p.assertion.command,a),c+=p.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=Jo({...n,steps:p.steps,topLevel:!1});i.push(...g),s.push(...h),l.push(...f)}if(m.elseSteps){c+=m.elseSteps.length;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.elseSteps,topLevel:!1});i.push(...p),s.push(...g),l.push(...h)}break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(m)}return e&&c&&s.length>0&&o.warn({totalSteps:c,cacheKeysMissed:s,cacheKeysHit:i,uniqueKeysHit:l,cacheEntries:r.length},"Step cache did not fully resolve"),{cacheKeysHit:i,cacheKeysMissed:s,uniqueKeysHit:l}}function Fh(t,e){return e?`${e}:${t}`:t}function Kv(t,e){let n=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let a=[...r.slice(o),t];n.push(a.join(":"))}return n.reverse(),n}function Md(t){let{moduleStepParents:e=[],moduleIdParents:n=[]}=t;if(e.length!==n.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
18
- ${JSON.stringify(n)}`);let r=[];return r.push({key:Fh(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId}),r}function Uh(t){let e=new Set;return Fs(t,n=>{if("type"in n&&n.type==="RESOLVED_MODULE"&&"moduleId"in n){let r=n.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function Us({cmd:t,newTarget:e,key:n,logger:r}){t.type==="DRAG"?n!=="fromTarget"&&n!=="toTarget"?r.error({cmd:t,newTarget:e,key:n},"Attempted to apply invalid cache to DRAG command"):t.cache={...t.cache,[n]:e}:n==="target"&&Om(t)?t.cache={...t.cache,target:e}:r.error({cmd:t,newTarget:e,key:n},"Invalid target cache application")}function Bs(t,e){t.cache={...t.cache,memory:{type:"GCS_TRACES",traces:e}}}async function zs({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:a}){let i=Dh(o,a);if(Object.keys(i).length!==0){t.debug({changes:i},"Updating steps caches post-run success");try{let{cachesToSave:s}=await He({stepLists:a,cacheCreationParams:{testId:r,orgId:n}});await e.saveStepCacheEntries({logger:t,testId:r,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Hs({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:a}){let i=Dh(o,a);if(Object.keys(i).length===0)return;t.debug({changes:i},"Updating memory post-run failure");let s={};for(let d of["steps","beforeSteps","afterSteps"]){let u=o[d];if(!u||!u.length)continue;let m=Yv({steps:u});for(let[p,g]of Object.entries(m))s[p]=g}let{cachesToSave:l}=await He({stepLists:a,cacheCreationParams:{testId:r,orgId:n}}),c=Xv({newEntries:l,originalCachesMap:s,logger:t});if(c.length){t.debug({prunedCaches:c},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,testId:r,entries:l})}catch(d){t.error({err:d},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}function Yv({steps:t}){let e={};return ni({steps:t,onPresetAction:(n,r)=>{let o=n.command;if(!("cache"in o)||!o.cache)return;let a=r.parentChain.filter(l=>l.type==="RESOLVED_MODULE").map(l=>l.id).join(":"),i=Fh(n.id,a),s=Bn.parse(o);e[i]=s},onSimpleStepContainer:(n,r)=>{},onConditional:(n,r)=>{}}),e}function Xv({newEntries:t,originalCachesMap:e,logger:n}){let r=[];for(let o of t){let a=e[o.key];if(!a||!a.cache||o.value.type!==a.type)continue;let i=o.value.cache;if(o.value={...a},!i){r.push(o);continue}if("memory"in i&&i.memory)n.debug({cacheKey:o.key,newCacheMemory:i.memory,originalCache:a},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:i.memory};else if("target"in i&&i.target.memory){let s=zt.parse(o.value.cache);if(!s)continue;n.debug({cacheKey:o.key,newCacheMemory:i.target.memory,originalCache:a},"Overwriting target cache memory"),s.target.memory=i.target.memory,o.value.cache=s}else if("fromTarget"in i||"toTarget"in i){let s=Sc.optional().parse(o.value.cache);if(!s)continue;s.fromTarget&&i.fromTarget&&(s.fromTarget.memory=i.fromTarget.memory),s.toTarget&&i.toTarget&&(s.toTarget.memory=i.toTarget.memory),n.debug({cacheKey:o.key,fromTargetMemory:i.fromTarget?.memory,toTargetMemory:i.toTarget?.memory,originalCache:a},"Overwriting drag cache memory"),o.value.cache=s}r.push(o)}return r}function $e(t,e,n=!1){return t.length<e?t:t.slice(0,e-3)+(n?"...TRUNCATED...":"[...]")}var tn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},nn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Ld={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Od={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function Jv(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?nn[t.operation]:tn[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let n=t.negated?nn[t.operation]:tn[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${n}`:`attribute '${t.attr}' ${n} '${t.value}'`}case"ELEMENT_NAME":{let n=t.negated?nn[t.operation]:tn[t.operation];return t.operation==="EXISTS"?`tag name ${n}`:`tag name ${n} '${t.value}'`}case"ELEMENT_STYLE":{let n=t.negated?nn[t.operation]:tn[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${n}`:`style property '${t.property}' ${n} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?Od[t.condition]:Ld[t.condition];default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var U2={CONTENT:"The page"};function Qv(t){switch(t.type){case"VALUE":return`the option with value ${t.value}`;case"LABEL":return`the option with label ${t.label}`;case"INDEX":return`the option at index ${t.index}`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function js(t){switch(t.type){case"SUBSTRING":return`match substring '${t.url}'`;case"REGEX":return`match regex '${t.regex}'`;case"GLOB":return`match glob '${t.glob}'`;case"DOMAIN":return`match domain '${t.domain}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function $s(t){let e="";return t.method&&(e=` with method ${t.method}`),`${js(t.urlMatcher)}${e}`}function Zv(t){switch(t.type){case"CONTENT":return`${t.negated?nn.CONTAINS:tn.CONTAINS} '${t.value}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function jn(t,e=!0){switch(t.type){case"SUCCESS":return t.condition?.assertion?`Check success condition: ${t.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${t.goal}`;case"NAVIGATE":return`Go to URL: ${e?$e(t.url,30):t.url}`;case"DIALOG":return`Automatically ${t.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"WAIT":return`Wait for ${t.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(t.target?.type==="coordinates")return`Click at coordinates: ${ht(t.target)}`;let r="";return t.target?.elementDescriptor.length?r=` on element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` on element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Click${r}`}case"FOCUS":return`Focus ${ht(t.target)}`;case"BLUR":return`Focus ${ht(t.target)}`;case"DRAG":return`Drag ${ht(t.fromTarget)} onto ${ht(t.toTarget)}`;case"MOUSE_DRAG":return t.target?.type==="description"&&t.target.elementDescriptor?`Click and drag ${ht(t.target)} by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`:`Click and drag mouse by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`;case"TYPE":{let r="";return t.target?.type==="coordinates"?r=` in element at coordinates: ${ht(t.target)}`:t.target?.elementDescriptor.length?r=` in element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` in element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Type '${t.value}'${r||""}`}case"HOVER":{let r="";return t.target.type==="coordinates"?r=` over coordinates: ${ht(t.target)}`:t.target.elementDescriptor.length>0?r=` over element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` over element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Hover${r}`}case"PRESS":return`Press ${t.value}`;case"KEY_DOWN":return`Hold down ${t.value} on the keyboard`;case"KEY_UP":return`Release ${t.value} on the keyboard`;case"SELECT_OPTION":{let r="",o=Qv(t.choice);return t.target.type==="coordinates"?r=` from element at coordinates: ${ht(t.target)}`:t.target.elementDescriptor.length>0?r=` from: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` from: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${r}`}case"TAB":switch(t.action.type){case"SUBSTRING":return`Switch to tab with substring: ${t.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${t.action.pattern}`;case"INDEX":return`Switch to tab at index: ${t.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${t.url}`;case"REQUEST":return`Send ${t.method} request to ${t.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${t.url}`;case"COOKIE":return`Set cookie: ${t.value}`;case"LOCAL_STORAGE":return`Set local storage: ${t.key}: ${t.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?$e(t.code,30):t.code}`;case"AI_ASSERTION":return`Assertion: '${t.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${t.target?`for element: ${ht(t.target)}`:"for entire page"}`;case"FILE_UPLOAD":return t.fileSource.type==="URL"?`Upload file: ${t.fileSource.url}`:`Upload file: ${t.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${ht(t.target)} ${Jv(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${Zv(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${js(t.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return t.requestMatcher?`Register a listener for network requests that ${$s(t.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return t.key?`Wait for the listener ${t.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return t.requestMatcher?`Start recording requests that match ${$s(t.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return t.key?`Get the requests that were recorded for ${t.key}`:"Get the requests that were recorded";case"SET_HEADER":return t.name?t.requestMatcher?`Set a ${t.name} header for requests that match ${$s(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${$s(t.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return t.key?`Remove the mock with key ${t.key}`:"Remove all route mocks";case"OFFLINE_MODE":return t.enable?"Enable offline mode":"Disable offline mode";default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Bh(t){let e=[];for(let n of t){n.sort((i,s)=>i.timestamp-s.timestamp);let r=[],o,a=1;for(let i of n)o&&o.text===i.text&&o.type===i.type&&JSON.stringify(o.args??null)===JSON.stringify(i.args??null)?a++:(o&&(a>1?o.args&&o.args.length?o.args.push(`(repeated ${a} times)`):o.text+=` (repeated ${a} times)`:r.push(o)),o=i,a=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as $2}from"lodash-es";import{v4 as K2}from"uuid";import{cloneDeep as eA}from"lodash-es";import Wh from"truncate-json";import{cloneDeep as Q2,unset as Z2}from"lodash-es";function hr(t){switch(t.type){case"AI_ACTION":return`AI action: ${$e(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${$e(t.text,100)}`;case"PRESET_ACTION":return jn(t.command);case"MODULE":return`Module: ${t.id}`;case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${t.description?`with goal: ${$e(t.description,100)}`:""}`;default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}function Qr(t,e){return t.split(`
15
+ `),globalThis.console=e}}var Ye=" ".repeat(6);function yh(t,e="",n=!1){let r=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(r-e.length,20),a=t.split(`
16
+ `),i=[];for(let s of a)if(n){let c=s;for(;c.length>o;){let d=c.slice(0,o+1).lastIndexOf(" "),u=d>-1?d:o;i.push(e+c.slice(0,u)),c=c.slice(u).trimStart()}i.push(e+c)}else{let c=s.split(" "),l="";for(let d of c){if(!l.length){l=d;continue}let u=`${l} ${d}`;u.length<=o?l=u:(i.push(e+l),l=d)}i.push(e+l)}return i.join(`
17
+ `)}import yv from"os";import bh,{multistream as bv}from"pino";import Tv from"pino-pretty";import wv from"pino-std-serializers";var Za=new Map,Ev=!0,Th="Log throttle exceeded",Rv=100,Cv=5e3,bd=class t{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:n,disableConsoleLogs:r,flushIntervalMs:o,maxBatchSize:a}){this.hostname=n??yv.hostname(),this.disableConsoleLogs=r,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=a??10;let i={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=Ev?bh(i):bh(i,bv([{stream:Tv({colorize:!0})}]))}getLevel(){return Rs[this.minLevelValue]}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let n=await fetch(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:qa(e)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch(n){this.consoleLogger.warn({err:n},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===Th)return!0;let n=Date.now();return n-this.lastWindowStart>Cv&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,Th),this.droppedLogsInWindow=!1,this.lastWindowStart=n),this.logsInCurrentWindow<Rv?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,n,r,...o){try{this.logHelper(e,n,r,...o)}catch(a){this.consoleLogger.warn(`Failed to log to Signoz: ${a}`)}}logHelper(e,n,r,...o){if(Ka[e]<this.minLevelValue||!this.shouldAllowLog(r))return;typeof n=="string"&&!r&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=wv.err(n.err));let a={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...o.length>0?{args:o}:{}},i={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](a,r,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:i,attributes:{},body:yg({message:r||"",...a})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let n=this.bindingAttributes.app;this.bindingAttributes.app=e,Za.set("app",this),Za.delete(n)}debug(e,n,...r){this.log("debug",e,n,...r)}info(e,n,...r){this.log("info",e,n,...r)}warn(e,n,...r){this.log("warn",e,n,...r)}error(e,n,...r){this.log("error",e,n,...r)}bindings(){return this.bindingAttributes}addBinding(e,n){this.bindingAttributes[e]=n}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=Rs[e]):(this.minLevelValue=Ka[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Is=({app:t,hostname:e,disableConsoleLogs:n})=>(Za.has(t)||Za.set(t,new bd({bindings:{app:t},hostname:e,disableConsoleLogs:n})),Za.get(t));import{hostname as vv}from"os";var X=Is({app:"cli",hostname:vv(),disableConsoleLogs:!0}).child({cliVersion:"2.17.0"});var xv=5;async function Ms({getResults:t,checkDone:e,name:n,timeoutMs:r=18e5}){let o=Date.now(),a=0;for(;Date.now()-o<r;){let i;a>xv&&(S.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{i=await t(),a=0}catch(l){a++,X.warn({err:l},"Failed to fetch run status, retrying..."),S.warn({err:l},"Failed to fetch run status, retrying..."),await new Promise(d=>setTimeout(d,1500*a));continue}if(e(i))return i;let c=Math.max(1e4,Math.floor(r/100));await new Promise(l=>setTimeout(l,c))}S.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(r/1e3)}s).`),process.exit(1)}function Vo({results:t,startTime:e,entity:n,getDisplayLine:r,onFailed:o}){let a=t.filter(d=>d.status==="PASSED"&&d.quarantined),i=t.filter(d=>d.status==="PASSED"&&!d.quarantined),s=t.filter(d=>d.status==="FAILED"&&d.quarantined),c=t.filter(d=>d.status==="FAILED"&&!d.quarantined),l=t.filter(d=>d.status==="CANCELLED");return Sh(()=>{if(c.forEach(d=>{S.log(""),o(d)}),c.length){S.log("");let d=c.length===1?"":"s";S.error(`${c.length} ${n}${d} failed:`),c.forEach(u=>{S.dimmed(r(u))})}if(l.length){S.log("");let d=l.length===1?"":"s";S.warn(`${l.length} ${n}${d} cancelled:`),l.forEach(u=>{S.dimmed(r(u))})}if(i.length){S.log("");let d=i.length===1?"":"s";S.success(`${i.length} ${n}${d} passed:`),i.forEach(u=>{S.dimmed(r(u))})}if(s.length){S.log("");let d=s.length===1?"":"s";S.warn(`${s.length} quarantined ${n}${d} failed:`),s.forEach(u=>{S.dimmed(r(u))})}if(a.length){S.log("");let d=a.length===1?"":"s";S.warn(`${a.length} quarantined ${n}${d} passed:`),a.forEach(u=>{S.dimmed(r(u))})}S.log(""),S.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:a.length,passed:i.length,quarantinedFailed:s.length,failed:c.length,cancelled:l.length}}var Ls=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let n=Ki[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||No[t.failureReason],o=t.failureDetails.classification?.rootCause;if(S.error(e),o){S.log(`${Ye}- Error type: ${An.dim(n)}`);let a="- Root cause analysis:",i=yh(`${a} ${o}`,`${Ye} `,!1),s=i.indexOf(":");S.log(`${Ye}${a} ${An.dim(i.slice(s+1))}`)}else S.log(`${Ye}Reason: ${An.red(n)}`),S.log(`${Ye}Description: ${An.red(r)}`)},ei=({status:t,testLogRef:e,getRunningTestsCount:n,getTotalTestsCount:r,additionalText:o})=>{t=t.toUpperCase();let a=t,i;t.includes("FAIL")?(a=An.bgRed.white("FAIL"),i=3):t.includes("PASS")?(a=An.bgGreen.white("PASS"),i=3):t.includes("START")?(a=An.bgBlue.white("START"),i=2):t.includes("CANCEL")?(a=An.bgRgb(191,68,11).white("CANCEL"),i=1):t.includes("RETRY")?(a=An.bgRgb(191,68,11).white("RETRY"),i=2):t.includes("RUN")||t.includes("PROG")?(a=An.bgMagenta.white("RUNNING"),i=0):(S.warn(`Unknown status tried to be logged in run test locally: ${t}`),i=0),Av||(a=`${a}`),S.log(`${a}${" ".repeat(i)} ${e} ${o?`${o} `:""}(${n()}/${r()})`)};var kv=!1,Eh=(()=>{try{return Ov("/.dockerenv"),!0}catch{return!1}})();async function Tt(t,e){return Ea||kv||Eh?!0:(S.flush(),X.flush(),await new Promise(r=>setTimeout(r,500)),await Iv({message:t}))}async function Td(t){let e=Nv(t);return hh(e)?Mv(t)?Tt(`File '${wh(t)}' already exists. Overwrite existing content?`,!0):!0:await Tt(`Directory '${wh(e)}' doesn't exist. Create it now?`,!0)?(Lv(e,{recursive:!0}),!0):!1}function wh(t){return t.replace(/(\s+)/g,"\\$1")}async function Rh(t,e){return Ea||Eh?e:(await Pv({message:t,default:e})).trim()||e}import _v from"fs";import{tmpdir as Dv}from"os";import Fv from"path";import{registry as ti}from"playwright-core/lib/server";import Ch from"proper-lockfile";var vh=Fv.join(Dv(),"momenticBrowserInstallation");var wd=["chrome","chromium","chrome-for-testing"],Uv={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Ah={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function xh(t){let e=Ah[Uv[t]??""]??"",n=ti.findExecutable(e);return!n||n.installType==="none"?!1:Ed(n)}function Ed(t){let e=t.executablePath();return _v.existsSync(e)}function Bv(t,e){let n=Ah[t];if(!n)throw new Error(`Requested install of unknown browser type ${t}`);let r=ti.findExecutable(n);if(!r||r.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&&Ed(r)))return r}async function zv({browser:t,force:e}){let n=Bv(t,e);if(!n){S.info(`Browser '${t}' is already installed, skipping...`);return}S.info(`Installing browser '${t}'...`);try{await ti.installDeps([n],!1),await ti.install([n],!1)}catch(r){if(r.message.includes("Lock file is already being held")){S.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ti.findExecutable(t),a=5*60*1e3,i=Date.now();for(;Date.now()-i<a&&!Ed(o);)S.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw r}}async function Ih({rawBrowsers:t,force:e=!1,all:n=!1}){let r=n?wd:Array.from(new Set(t));try{await Ch.lock(vh,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(a){S.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${a}. Continuing without installation...`);return}let o;try{for(let a of r)try{await zv({browser:a,force:e})}catch(i){o=i,S.error(`Failed to install the ${a} browser: ${i}`)}}finally{await Ch.unlock(vh,{realpath:!1})}if(o)throw o}import{randomUUID as lN}from"crypto";import qb from"body-parser";import QL from"cors";import ZL from"dedent";import{Router as PA}from"express";import It from"fs";import{globSync as MA}from"glob";import ct from"path";import Dd from"fs";import{z as Cd}from"zod";var H="v1",ni="2.17.0";var mr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ph=t=>{let e=t.reason===void 0?new DOMException("This operation was aborted.","AbortError"):t.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function j(t,e){let{milliseconds:n,fallback:r,message:o,customTimers:a={setTimeout,clearTimeout}}=e,i,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);return new Promise((c,l)=>{if(e.signal){let{signal:u}=e;if(u.aborted)return l(Ph(u));s=()=>l(Ph(u)),u.addEventListener("abort",s)}let d=()=>{if(r)try{c(r())}catch(u){l(u)}else{typeof t.cancel=="function"&&Promise.resolve().then(()=>t.cancel()).catch(()=>{});let u=o instanceof Error?o:new mr(o??`Promise timed out after ${n}ms`);l(u)}};i=a.setTimeout(d,n),Promise.resolve(t).then(u=>c(u)).catch(u=>l(u))}).finally(()=>{a.clearTimeout(i),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var Os=class{limit;windowMs;userActions;constructor(e,n){this.limit=e,this.windowMs=n,this.userActions=new Map}_cleanup(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;if(this.userActions.has(o)){let i=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];i.length>0?this.userActions.set(o,i):this.userActions.delete(o)}}increment(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;this._cleanup(n,e),this.userActions.has(o)||this.userActions.set(o,[]);let a=this.userActions.get(o);return a.length>=this.limit?!0:(a.push(r),!1)}};var Hv=9e4,$v=3,jv=1500,Gv=15e3,un=class extends Error{status;rawError;constructor(e,n,r,o={}){super(r,o),this.status=e,this.rawError=n}};async function Wv(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Rd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ni&&(e[Eg]=ni),e}async sendRequest(e,n){let{retries:r=$v,requestTimeoutMs:o=Hv,initialRetryDelayMs:a=jv,maxRetryDelayMs:i=Gv}=n,s=r,c=r,l,d={path:e,baseUrl:this.baseUrl,method:n.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,n,o)}catch(u){if(l=u,u instanceof un&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError"&&(l=new mr),s===0)throw l;let m=c-s,p=Math.min(a*Math.pow(2,m-1),i);await new Promise(g=>setTimeout(g,p))}throw this.logger.warn({...d,err:l},"Got fatal error response from Momentic server"),l}async sendSingleRequestHelper(e,n,r){let o={path:e,baseUrl:this.baseUrl,method:n.method},a=new AbortController,i=setTimeout(()=>a.abort(),r),s=()=>a.abort();n.signal&&n.signal.addEventListener("abort",s);let c={...this.getHeaders(),...n.extraHeaders};try{let l=await fetch(`${this.baseUrl}${e}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:c,signal:a.signal});if(!l.ok){let u=await Wv(l);throw new un(l.status,u,`Request to ${n.method} ${e} failed with status ${l.status}: ${u}`)}let d;if(l.status===204)d={};else{let u=await l.text();try{d=JSON.parse(u)}catch{d=u}}return this.logger&&n.logResponse===!0&&d&&this.logger.debug({result:d,status:l.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(i),n.signal&&n.signal.removeEventListener("abort",s)}}},xt=class extends Rd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Ze=class extends xt{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",retries:10,requestTimeoutMs:5e3});return Bg.parse(e)}async bulkGetRunStatus(e){let n=await this.sendRequest(`/${H}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return _g.parse(n)}async getTestYAMLExport(e){let n=await this.sendRequest(`/${H}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Ig.parse(n)}async updateStepCaches(e,n){await this.sendRequest(`/${H}/cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,n){let r=await this.sendRequest(`/${H}/cache`,{method:"POST",body:e,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Mg.parse(r)}async updateMobileStepCaches(e,n){await this.sendRequest(`/${H}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,n){let r=await this.sendRequest(`/${H}/mobile-cache`,{method:"POST",body:e,extraHeaders:n,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Lg.parse(r)}async queueTests(e){let n=await this.sendRequest(`/${H}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return xg.parse(n)}async uploadScreenshot(e){let n=await this.sendRequest(`/${H}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Ug.parse(n)}async getAllEnvironments(){let e=await this.sendRequest(`/${H}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return zg.parse(e)}async acquireCacheLock(e,n){let r=await this.sendRequest(`/${H}/result-cache/lock`,{method:"POST",body:e,signal:n,retries:3,requestTimeoutMs:3e4});return eh.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(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(e){let n=await this.sendRequest(`/${H}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Hg.parse(n)}async bulkGetRunGroupStatus(e){let n={runGroupIds:e},r=await this.sendRequest(`/${H}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return ap.array().parse(r)}async uploadProposedSteps(e,n){try{await this.sendRequest(`/${H}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){n.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,n){try{await this.sendRequest(`/${H}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let n=await this.sendRequest(`/${H}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return $g.parse(n)}async patchTestFragment(e,n){await this.sendRequest(`/${H}/test-fragments/${e}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,n){let r=await this.sendRequest(`/${H}/results/tests/${e}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return jg.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${H}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Gg.parse(e)}async startProcessingResultsUpload(e,n){let r=await this.sendRequest(`/${H}/results/uploads/${e}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Wg.parse(r)}async fetchIconKnowledgeBase(e){try{let n=await this.sendRequest(`/${H}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ah.parse(n)}catch(n){return e.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,n){try{await this.sendRequest(`/${H}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(r){n.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,n,r,o){let a=new URLSearchParams;a.set("base",r),a.set("head",o);let i=await this.sendRequest(`/${H}/git/github/${e}/${n}/merge-base-commit?${a.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Xa.parse(i)}async getCommitFromGithub(e,n,r){let o=await this.sendRequest(`/${H}/git/github/${e}/${n}/commits/${r}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Xa.parse(o)}async getMergeBaseCommitFromGitlab(e,n,r){let o=new URLSearchParams;o.set("base",n),o.set("head",r);let a=await this.sendRequest(`/${H}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Xa.parse(a)}async getCommitFromGitlab(e,n){let r=await this.sendRequest(`/${H}/git/gitlab/${e}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Xa.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${H}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Cd.record(Cd.string(),Cd.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${H}/quarantine`,{method:"GET"});return Vg.parse(e)}async quarantineTest(e,n,r){await this.sendRequest(`/${H}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,n,r){await this.sendRequest(`/${H}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let n=await this.sendRequest(`/${H}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return qg.parse(n)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${H}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:n,md5:r}){let o={channel:e,tag:n,md5:r},a=await this.sendRequest(`/${H}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Kg.parse(a)}async deleteAndroidEmulator(e){await this.sendRequest(`/${H}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${H}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Yg.parse(e)}async deleteAndroidAsset(e,n){await this.sendRequest(`/${H}/limbar/assets/${e}/${n}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function vd(t){let e=process.versions.node,n=parseInt(e.split(".")[0]);(isNaN(n)||n<18)&&(S.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),S.debug(`Identified node version ${e}`);let r=await t.client.getAuthInfo();return S.debug("Got auth info from API"),r}import{randomUUID as Mh}from"crypto";var Ns=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,n,r){try{return await this.apiClient.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:r?.eventId??Mh(),properties:Vc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,n,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??Mh(),properties:Vc({creditsUsed:r,usedBy:n},o)}])}catch(a){e.error({err:a},"Failed to report credits used")}}};var qo=class{constructor(e,n){this.client=e;this.orgId=n}async acquireCacheLock(e,n){return this.client.acquireCacheLock(e,n)}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,n){return this.client.saveNewIcons(e,n)}};import{Faker as Vv,en as qv}from"@faker-js/faker";var Ko="v1",pr=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 Vv({locale:qv}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let n=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ko}/tools/ai/generate`,{method:"POST",body:n}).catch(r=>{throw r instanceof un?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ko}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof un?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ko}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof un?new Error(n.rawError):n})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof un?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/fetchAll`,{method:"POST",body:e}).catch(n=>{throw n instanceof un?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof un?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}};import{z as Kv}from"zod";var Yo=class extends xt{agentConfig;constructor(e,n){super(n),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,n){let r={...e,loggerTags:n.loggerTags},o=await this.sendRequest(`/${H}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:n.abortSignal});return up.parse(o)}async rankChunksWithRag(e,n){let r=await this.sendRequest(`/${H}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ni,...e},signal:n.abortSignal});return dp.parse(r)}async getScreenshotFromS3(e){let n=await this.sendRequest(`/${H}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return Kv.string().parse(n)}async getElementLocation(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${H}/web-agent/locate-element`,{method:"POST",body:r,signal:n.abortSignal});return vg.parse(o)}async getAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${H}/web-agent/assertion`,{method:"POST",body:r,signal:n.abortSignal});return md.parse(o)}async getLintStepResult(e,n){let r={...e,disableCache:!!n.disableCache,loggerTags:n.loggerTags},o=await this.sendRequest(`/${H}/web-agent/lint/step`,{method:"POST",body:r,signal:n.abortSignal});return Cg.parse(o)}async getVisualAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${H}/web-agent/visual-assertion`,{method:"POST",body:r,signal:n.abortSignal});return md.parse(o)}async getAiActionCommand(e,n){let r=await this.sendRequest(`/${H}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Rg.parse(r)}async getMultiturnAiActionCommand(e,n){return await this.sendRequest(`/${H}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(e,n){let r=await this.sendRequest(`/${H}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Ic.parse(r)}async getReverseMappedDescription(e,n){let r=await this.sendRequest(`/${H}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Ag.parse(r)}async getTextExtraction(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${H}/web-agent/text-extraction`,{method:"POST",body:r,signal:n.abortSignal});return Ac.parse(o)}async getTestResultClassification(e,n){let r=await this.sendRequest(`/${H}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return Lc.parse(r)}async getExtractedKeywords(e,n){let r=await this.sendRequest(`/${H}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:n.disableCache,context:e},signal:n.abortSignal});return Tp.parse(r)}async getAutohealingProposal(e,n){let r=await this.sendRequest(`/${H}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return zm.parse(r)}async getFailureRecoveryProposal(e,n){let r=await this.sendRequest(`/${H}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return $m.parse(r)}async getFailureRecoveryPlan(e,n){let r=await this.sendRequest(`/${H}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return Hm.parse(r)}async getIframeRegex(e,n){let r=await this.sendRequest(`/${H}/web-agent/iframe-regex`,{method:"POST",body:e,signal:n.abortSignal});return bm.parse(r)}};var Xo=class extends xt{generator;constructor(e,n){super(e),this.generator=n}async runTemplateMatching(e,n={}){let r=await this.sendRequest(`/${H}/web-agent/template-matching`,{method:"POST",body:e,signal:n?.signal});return Tm.parse(r)}async constructIframeRegex(e,n={}){return this.generator.getIframeRegex(e,{abortSignal:n.signal})}};function Lh(t,e,n){return fetch(t,{method:"PUT",body:n,headers:{"Content-Type":e}})}var ks=class{constructor(e){this.client=e}async uploadResultsArchive(e,n){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),a=await Lh(r,"application/zip",n);if(!a.ok)throw new Error(`Failed to upload test results: ${await a.text()}`);let{runGroupId:i}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return i}};import{diff as _h}from"deep-object-diff";function ri(t){let e={parentChain:[]};return _s(t,e),e}function _s(t,e){let{onPresetAction:n,onSimpleStepContainer:r,onConditional:o,earlyStop:a}=t;for(let i of t.steps)switch(i.type){case"PRESET_ACTION":if(n(i,e)&&a)return!0;break;case"CONDITIONAL":if(o?.(i,e)&&a)return!0;e.parentChain.push(i);for(let c of i.blocks)if(n(c.assertion,e)&&a||_s({...t,steps:c.steps},e)&&a)return!0;if(_s({...t,steps:i.elseSteps??[]},e)&&a)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(r?.(i,e)&&a)return!0;if(i.steps){if(e.parentChain.push(i),_s({...t,steps:i.steps},e)&&a)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(i,e)&&a)return!0;break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(i)}}function Oh(t,e,n,r){let o=Array.from(e),a=Array.from(r);for(let s=0;s<o.length;s++){if(o[s]!==a[s])return!1;a.shift()}return!!Yv([t],n,a).result}function Yv(t,e,n=[]){let r,o=[],a=(i,s)=>{let c=JSON.stringify(s.parentChain.map(d=>d.id)),l=n.length===0?!0:JSON.stringify(n)===c;return i.id===e&&l?(r=i,o=s.parentChain,!0):!1};return ri({steps:t,earlyStop:!0,onPresetAction:a,onConditional:a,onSimpleStepContainer:a}),{result:r,parentChain:o}}function Nh(t,e){e(t);for(let n in t){let r=t[n];r&&(Array.isArray(r)?Fs(r,e):typeof r=="object"&&Nh(r,e))}}function Fs(t,e){for(let n of t)n&&(Array.isArray(n)?Fs(n,e):typeof n=="object"&&Nh(n,e))}function Ad(t,e){if(t.length>e.length)return Ad(e,t);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Ds(t){for(let e of t.results)switch(e.type){case"PRESET_ACTION":t.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":t.onSimpleStepContainer?.(e),Ds({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),Ds({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}import{cloneDeep as kh}from"lodash-es";import{v4 as xd}from"uuid";async function He(t){let e=new Map,n=new Set,r=kh(t.stepLists.steps),o=await Jr({...t,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n}),a={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let i of["beforeSteps","afterSteps"]){let s=kh(t.stepLists[i]);if(!s)continue;let c=await Jr({...t,steps:s,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n});a.cachesToSave.push(...c.cachesToSave),a.moduleUpdates.push(...c.moduleUpdates),a.stepsToSave[i]=c.stepsToSave}return a}async function Jr({steps:t,...e}){let{seenModules:n,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:a,moduleIdReplacements:i,shouldCreateNewModuleId:s,createNewCacheIds:c}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let d of t)switch(delete d.index,delete d.aiSuggested,d.id=c?xd():d.id,d.type){case"PRESET_ACTION":{let m=d.command;m.id=c?xd():m.id,"cache"in m&&m.cache&&(r&&(l.cachesToSave=l.cachesToSave.concat(Id({id:m.id,orgId:r.orgId,testId:r.testId,value:Un.parse(m),moduleIdParents:o,moduleStepParents:a}))),delete m.cache),m.thoughts&&delete m.thoughts,l.stepsToSave.push({...d,command:m});break}case"RESOLVED_MODULE":{let m=c?xd():d.id,p=d.moduleId;i.has(p)?p=i.get(p):s!==void 0&&(p=await s(d),i.set(d.moduleId,p));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await Jr({...e,steps:d.steps,cacheCreationParams:r?{...r}:void 0,createNewCacheIds:!1,moduleStepParents:[...a,m],moduleIdParents:[...o,p],skipCacheIntermediateEntries:c});l.moduleUpdates=l.moduleUpdates.concat(f),l.cachesToSave=l.cachesToSave.concat(g),n.has(p)||(n.add(p),l.moduleUpdates.push({...Ot.parse(d),steps:Ie.array().parse(h),moduleId:p}));let b=cn.parse({...d,type:"MODULE",moduleId:p,inputs:d.inputs,id:m,skipped:d.skipped,cacheConfig:d.cacheConfig,envKey:d.envKey});l.stepsToSave.push(b);break}case"AI_ACTION":{if(!d.steps){l.stepsToSave.push(d);break}let{stepsToSave:m,cachesToSave:p}=await Jr({...e,steps:d.steps});try{d.steps=Ht.array().parse(m)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}l.stepsToSave.push(d),l.cachesToSave=l.cachesToSave.concat(p);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(d);break}case"CONDITIONAL":{let m=[];for(let g of d.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:b}=await Jr({...e,steps:g.steps});m.push({...g,steps:h}),l.cachesToSave=l.cachesToSave.concat(f),l.moduleUpdates=l.moduleUpdates.concat(b)}let p={...d,elseSteps:void 0,blocks:m};if(d.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await Jr({...e,steps:d.elseSteps});p.elseSteps=g,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(f)}l.stepsToSave.push(p);break}case"SECTION":{let{stepsToSave:m,cachesToSave:p,moduleUpdates:g}=await Jr({...e,steps:d.steps}),h={...d,steps:m};l.moduleUpdates=l.moduleUpdates.concat(g),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(p);break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return l}function Jo({steps:t,topLevel:e=!0,...n}){let{stepCacheEntries:r,logger:o,keyPrefix:a}=n,i=[],s=[],c=[],l=0,d=(m,p)=>{try{let g=Un.parse(p.value);if(g.type!==m.type){o.warn({parsedCacheEntry:g,command:m},"Not using step cache due to type mismatch"),s.push(p.key);return}m.cache=g.cache,i.push(p.key),c.push(p.uniqueKey)}catch(g){s.push(p.key),o.error({err:g,cacheEntry:p},"Not using step cache due to parsing error")}},u=(m,p)=>{let g=Jv(m.id,p),h=g.find(f=>!!r[f]);if(h)d(m,r[h]);else{if(m.type==="AI_ASSERTION")return;s.push(g[0])}};for(let m of t)switch(m.type){case"RESOLVED_MODULE":{l+=m.steps.length;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.steps,keyPrefix:a?`${a}:${m.id}`:m.id,topLevel:!1});i.push(...p),s.push(...g),c.push(...h);break}case"SECTION":case"AI_ACTION":{if(l+=m.steps?.length??0,!m.steps?.length)break;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.steps,topLevel:!1});i.push(...p),s.push(...g),c.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!$i.includes(m.command.type)||(m.command.type==="TYPE"||m.command.type==="MOUSE_DRAG"||m.command.type==="VISUAL_DIFF"||m.command.type==="SCROLL_DOWN"||m.command.type==="SCROLL_UP"||m.command.type==="SCROLL_LEFT"||m.command.type==="SCROLL_RIGHT")&&!m.command.target||"cache"in m.command&&m.command.cache)continue;l++,u(m.command,a);break}case"CONDITIONAL":{for(let p of m.blocks){l++,u(p.assertion.command,a),l+=p.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=Jo({...n,steps:p.steps,topLevel:!1});i.push(...g),s.push(...h),c.push(...f)}if(m.elseSteps){l+=m.elseSteps.length;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.elseSteps,topLevel:!1});i.push(...p),s.push(...g),c.push(...h)}break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(m)}return e&&l&&s.length>0&&o.warn({totalSteps:l,cacheKeysMissed:s,cacheKeysHit:i,uniqueKeysHit:c,cacheEntries:r.length},"Step cache did not fully resolve"),{cacheKeysHit:i,cacheKeysMissed:s,uniqueKeysHit:c}}function Dh(t,e){return e?`${e}:${t}`:t}function Jv(t,e){let n=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let a=[...r.slice(o),t];n.push(a.join(":"))}return n.reverse(),n}function Id(t){let{moduleStepParents:e=[],moduleIdParents:n=[]}=t;if(e.length!==n.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
18
+ ${JSON.stringify(n)}`);let r=[];return r.push({key:Dh(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId}),r}function Fh(t){let e=new Set;return Fs(t,n=>{if("type"in n&&n.type==="RESOLVED_MODULE"&&"moduleId"in n){let r=n.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function Us({cmd:t,newTarget:e,key:n,logger:r}){t.type==="DRAG"?n!=="fromTarget"&&n!=="toTarget"?r.error({cmd:t,newTarget:e,key:n},"Attempted to apply invalid cache to DRAG command"):t.cache={...t.cache,[n]:e}:n==="target"&&Lm(t)?t.cache={...t.cache,target:e}:r.error({cmd:t,newTarget:e,key:n},"Invalid target cache application")}function Bs(t,e){t.cache={...t.cache,memory:{type:"GCS_TRACES",traces:e}}}async function zs({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:a}){let i=_h(o,a);if(Object.keys(i).length!==0){t.debug("Updating step caches post-success");try{let{cachesToSave:s}=await He({stepLists:a,cacheCreationParams:{testId:r,orgId:n}});await e.saveStepCacheEntries({logger:t,testId:r,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Hs({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:a}){let i=_h(o,a);if(Object.keys(i).length===0)return;t.debug({changes:i},"Updating memory post-run failure");let s={};for(let d of["steps","beforeSteps","afterSteps"]){let u=o[d];if(!u||!u.length)continue;let m=Qv({steps:u});for(let[p,g]of Object.entries(m))s[p]=g}let{cachesToSave:c}=await He({stepLists:a,cacheCreationParams:{testId:r,orgId:n}}),l=Zv({newEntries:c,originalCachesMap:s,logger:t});if(l.length){t.debug({prunedCaches:l},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,testId:r,entries:c})}catch(d){t.error({err:d},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}function Qv({steps:t}){let e={};return ri({steps:t,onPresetAction:(n,r)=>{let o=n.command;if(!("cache"in o)||!o.cache)return;let a=r.parentChain.filter(c=>c.type==="RESOLVED_MODULE").map(c=>c.id).join(":"),i=Dh(n.id,a),s=Un.parse(o);e[i]=s},onSimpleStepContainer:(n,r)=>{},onConditional:(n,r)=>{}}),e}function Zv({newEntries:t,originalCachesMap:e,logger:n}){let r=[];for(let o of t){let a=e[o.key];if(!a||!a.cache||o.value.type!==a.type)continue;let i=o.value.cache;if(o.value={...a},!i){r.push(o);continue}if("memory"in i&&i.memory)n.debug({cacheKey:o.key,newCacheMemory:i.memory,originalCache:a},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:i.memory};else if("target"in i&&i.target.memory){let s=zt.parse(o.value.cache);if(!s)continue;n.debug({cacheKey:o.key,newCacheMemory:i.target.memory,originalCache:a},"Overwriting target cache memory"),s.target.memory=i.target.memory,o.value.cache=s}else if("fromTarget"in i||"toTarget"in i){let s=gc.optional().parse(o.value.cache);if(!s)continue;s.fromTarget&&i.fromTarget&&(s.fromTarget.memory=i.fromTarget.memory),s.toTarget&&i.toTarget&&(s.toTarget.memory=i.toTarget.memory),n.debug({cacheKey:o.key,fromTargetMemory:i.fromTarget?.memory,toTargetMemory:i.toTarget?.memory,originalCache:a},"Overwriting drag cache memory"),o.value.cache=s}r.push(o)}return r}function $e(t,e,n=!1){return t.length<e?t:t.slice(0,e-3)+(n?"...TRUNCATED...":"[...]")}var nn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},rn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Pd={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Md={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function eA(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?rn[t.operation]:nn[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let n=t.negated?rn[t.operation]:nn[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${n}`:`attribute '${t.attr}' ${n} '${t.value}'`}case"ELEMENT_NAME":{let n=t.negated?rn[t.operation]:nn[t.operation];return t.operation==="EXISTS"?`tag name ${n}`:`tag name ${n} '${t.value}'`}case"ELEMENT_STYLE":{let n=t.negated?rn[t.operation]:nn[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${n}`:`style property '${t.property}' ${n} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?Md[t.condition]:Pd[t.condition];default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var V2={CONTENT:"The page"};function tA(t){switch(t.type){case"VALUE":return`the option with value ${t.value}`;case"LABEL":return`the option with label ${t.label}`;case"INDEX":return`the option at index ${t.index}`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function js(t){switch(t.type){case"SUBSTRING":return`match substring '${t.url}'`;case"REGEX":return`match regex '${t.regex}'`;case"GLOB":return`match glob '${t.glob}'`;case"DOMAIN":return`match domain '${t.domain}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function $s(t){let e="";return t.method&&(e=` with method ${t.method}`),`${js(t.urlMatcher)}${e}`}function nA(t){switch(t.type){case"CONTENT":return`${t.negated?rn.CONTAINS:nn.CONTAINS} '${t.value}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function $n(t,e=!0){switch(t.type){case"SUCCESS":return t.condition?.assertion?`Check success condition: ${t.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${t.goal}`;case"NAVIGATE":return`Go to URL: ${e?$e(t.url,30):t.url}`;case"DIALOG":return`Automatically ${t.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ft(t.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ft(t.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ft(t.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ft(t.target)}`:""}`;case"WAIT":return`Wait for ${t.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(t.target?.type==="coordinates")return`Click at coordinates: ${ft(t.target)}`;let r="";return t.target?.elementDescriptor.length?r=` on element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` on element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Click${r}`}case"FOCUS":return`Focus ${ft(t.target)}`;case"BLUR":return`Focus ${ft(t.target)}`;case"DRAG":return`Drag ${ft(t.fromTarget)} onto ${ft(t.toTarget)}`;case"MOUSE_DRAG":return t.target?.type==="description"&&t.target.elementDescriptor?`Click and drag ${ft(t.target)} by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`:`Click and drag mouse by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`;case"TYPE":{let r="";return t.target?.type==="coordinates"?r=` in element at coordinates: ${ft(t.target)}`:t.target?.elementDescriptor.length?r=` in element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` in element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Type '${t.value}'${r||""}`}case"HOVER":{let r="";return t.target.type==="coordinates"?r=` over coordinates: ${ft(t.target)}`:t.target.elementDescriptor.length>0?r=` over element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` over element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Hover${r}`}case"PRESS":return`Press ${t.value}`;case"KEY_DOWN":return`Hold down ${t.value} on the keyboard`;case"KEY_UP":return`Release ${t.value} on the keyboard`;case"SELECT_OPTION":{let r="",o=tA(t.choice);return t.target.type==="coordinates"?r=` from element at coordinates: ${ft(t.target)}`:t.target.elementDescriptor.length>0?r=` from: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` from: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${r}`}case"TAB":switch(t.action.type){case"SUBSTRING":return`Switch to tab with substring: ${t.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${t.action.pattern}`;case"INDEX":return`Switch to tab at index: ${t.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${t.url}`;case"REQUEST":return`Send ${t.method} request to ${t.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${t.url}`;case"COOKIE":return`Set cookie: ${t.value}`;case"LOCAL_STORAGE":return`Set local storage: ${t.key}: ${t.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?$e(t.code,30):t.code}`;case"AI_ASSERTION":return`Assertion: '${t.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${t.target?`for element: ${ft(t.target)}`:"for entire page"}`;case"FILE_UPLOAD":return t.fileSource.type==="URL"?`Upload file: ${t.fileSource.url}`:`Upload file: ${t.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${ft(t.target)} ${eA(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${nA(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${js(t.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return t.requestMatcher?`Register a listener for network requests that ${$s(t.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return t.key?`Wait for the listener ${t.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return t.requestMatcher?`Start recording requests that match ${$s(t.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return t.key?`Get the requests that were recorded for ${t.key}`:"Get the requests that were recorded";case"SET_HEADER":return t.name?t.requestMatcher?`Set a ${t.name} header for requests that match ${$s(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${$s(t.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return t.key?`Remove the mock with key ${t.key}`:"Remove all route mocks";case"OFFLINE_MODE":return t.enable?"Enable offline mode":"Disable offline mode";default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Uh(t){let e=[];for(let n of t){n.sort((i,s)=>i.timestamp-s.timestamp);let r=[],o,a=1;for(let i of n)o&&o.text===i.text&&o.type===i.type&&JSON.stringify(o.args??null)===JSON.stringify(i.args??null)?a++:(o&&(a>1?o.args&&o.args.length?o.args.push(`(repeated ${a} times)`):o.text+=` (repeated ${a} times)`:r.push(o)),o=i,a=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as X2}from"lodash-es";import{v4 as nY}from"uuid";import{cloneDeep as rA}from"lodash-es";import Gh from"truncate-json";import{cloneDeep as iY,unset as sY}from"lodash-es";function gr(t){switch(t.type){case"AI_ACTION":return`AI action: ${$e(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${$e(t.text,100)}`;case"PRESET_ACTION":return $n(t.command);case"MODULE":return`Module: ${t.id}`;case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${t.description?`with goal: ${$e(t.description,100)}`:""}`;default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}function Qr(t,e){return t.split(`
19
19
  `).map(n=>" ".repeat(e)+n).join(`
20
- `)}function Nd(t){switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`AI action: ${t.text}
21
- ${Qr(`Sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return jn(t.command,!1);case"MODULE":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;if("moduleName"in t){let n=t.moduleName;return`Module: ${t.id} ModuleName: ${n}
20
+ `)}function Ld(t){switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`AI action: ${t.text}
21
+ ${Qr(`Sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return $n(t.command,!1);case"MODULE":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;if("moduleName"in t){let n=t.moduleName;return`Module: ${t.id} ModuleName: ${n}
22
22
  ${Qr(`Sub-steps: ${e}`,2)}`}return`Module: ${t.id}
23
- ${Qr(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in t&&t.assertionResult&&(e.push(Qr("Conditional check:",2)),e.push(Qr(Nd(t.assertionResult),2))),"results"in t&&Array.isArray(t.results)){let n=t.results.length,r="assertionResult"in t&&t.assertionResult?"Branch steps":"Else branch steps";e.push(Qr(`${r}: ${n}`,2))}return e.join(`
23
+ ${Qr(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in t&&t.assertionResult&&(e.push(Qr("Conditional check:",2)),e.push(Qr(Ld(t.assertionResult),2))),"results"in t&&Array.isArray(t.results)){let n=t.results.length,r="assertionResult"in t&&t.assertionResult?"Branch steps":"Else branch steps";e.push(Qr(`${r}: ${n}`,2))}return e.join(`
24
24
  `)}case"SECTION":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`Section${t.description?`with goal: ${t.description}`:""}
25
- ${Qr(`Sub-steps: ${e}`,2)}`}default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}var zh=1e3,Hh=3e6,tA="[FAILED]";async function $h(t,e,n){if(n){let r=await e.getScreenshot(t,n);if(r)return`data:image/jpeg;base64,${Buffer.from(r).toString("base64")}`}}function nA(t,e){let n=(()=>{switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":return"AI action";case"PRESET_ACTION":return"Preset action";case"MODULE":return"Module";case"CONDITIONAL":return"Conditional step";case"SECTION":return"Section";default:return(a=>{throw new Error("You missed a case in the switch above")})(t)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${n}
26
- ${o}`:o)(Nd(t))}function Gs(t,e={}){let{index:n,includeDomState:r=!1,header:o}=e,a=nA(t,o),i;t.type==="PRESET_ACTION"&&(i=t.results?.[0]?.elementInteracted);let s=t.message!=="Successfully executed preset action."?t.message:void 0,l=a;t.status==="FAILED"&&(l=`${tA} ${l}`);let c={description:l,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:i,message:s,index:n};if(t.status==="FAILED"&&r)try{let d=sp.array().parse(t.details);for(let u of d)"pageState"in u&&(c.pageState=u.pageState)}catch{}return c}async function Vh(t,e,n,{addIndices:r=!0,includeDomState:o=!1,flatten:a=!0,maxItemsFromEnd:i=15,indexOffset:s=0}){let l,c=[];for(let d=0;d<n.length;d++){let u=n[d],m=r?d+s:void 0;switch(u.type){case"PRESET_ACTION":{c.push(Gs(u,{index:m,includeDomState:o,header:void 0})),u.status==="FAILED"&&(l=m);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(a){c.push(Gs(u,{index:r?m:void 0,includeDomState:o,header:"start"})),s+=1;let{failureIndex:p,results:g}=await Vh(t,e,u.results,{addIndices:r,includeDomState:o,flatten:a,maxItemsFromEnd:i,indexOffset:s+d});if(c.push(...g),p!==void 0){l=p;break}s+=g.length,c.push(Gs(u,{index:r?s+d:void 0,includeDomState:o,header:"end"})),s+=1}else c.push(Gs(u,{index:r?s+d:void 0,includeDomState:o,header:void 0}));break}default:return(g=>{throw new Error("You missed a case in the switch above")})(u)}if(l!==void 0)break}return{results:c,failureIndex:l}}async function Qo(t,e,n,{numStepsWithScreenshots:r=5,addIndices:o=!0,includeBeforeScreenshots:a=!1,includeDomState:i=!1,flatten:s=!0,maxItemsFromEnd:l=20}){let{results:c,failureIndex:d}=await Vh(t,e,n,{addIndices:o,includeDomState:i,flatten:s,maxItemsFromEnd:l,indexOffset:0}),u=[],m=0;if(l!==void 0&&c.length>l&&(m=c.length-l),d!==void 0&&d<c.length-1&&t.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:c.length,lastIndex:c.length-1,isLastIndex:d===c.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let p=m;p<c.length;p++){let g=c[p],h={description:g.description,startedAt:g.startedAt,finishedAt:g.finishedAt,beforeUrl:g.beforeUrl,afterUrl:g.afterUrl,elementInteracted:g.elementInteracted,message:g.message,pageState:g.pageState,index:g.index},f,y;(r===void 0||r>0&&p>=c.length-r)&&(g.afterSnapshot&&(y=await $h(t,e,g.afterSnapshot)),a&&g.beforeSnapshot&&(f=await $h(t,e,g.beforeSnapshot))),h.beforeScreenshot=f,h.afterScreenshot=y,u.push(h)}return{results:u,failureIndex:d!==void 0?d-m:void 0}}function _d({json:t,keysToRedact:e,maxJsonStringSize:n}){try{if(!t)return t;if(typeof t=="string")return $e(t,n??2e4);if(typeof t=="object"){let{jsonString:r}=Wh(JSON.stringify(t,(o,a)=>e?.includes(o)||typeof a=="string"&&a.length>3e4?"REDACTED":a),n??2e4);return JSON.parse(r)}return t}catch{return t}}function kd(t,e){for(let n=0;n<t.length;n++){let r=t[n];try{if(r.data){let{jsonString:o}=Wh(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":jh(r);break;case"CONDITIONAL":r.assertionResult&&jh(r.assertionResult),kd(r.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{kd(r.results,e);break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}}function jh(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Gh(t,e){let n=JSON.stringify(t),r=n.replaceAll("\\u0000","");if(n.length!==r.length){let o=n.indexOf("\\u0000");e.warn({input:n.slice(Math.max(0,o-500),Math.min(n.length,o+500))},"Database content violation: stripped unicode character from input")}return r}function Ws(t,e){let n=eA(t);if(kd(n,e),n.length>zh)return e.error("Database content violation: results too long, truncating before insertion"),n.slice(0,zh);let r=Gh(n,e);if(r.length>Hh)for(e.error({serializedLength:r.length,resultsArrayLength:n.length},"Database content violation: results too large, truncating before insertion");r.length>Hh;)n.pop(),r=Gh(n,e);try{return et.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 bY}from"lodash-es";var rA=/^(?!.*\S+\s+\S+).*$/,oA=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,aA=/style="([^"]*)/g,iA=/data-[\w-]+/g,sA=t=>{switch(t.type){case"AI_ASSERTION":return{type:t.type,assertion:t.assertion};case"DRAG":if(t.fromTarget.type==="description")return{type:t.type,description:t.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(t.target?.type==="description")return{type:t.type,description:t.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function qh(t){let e=sA(t),n=e.type==="AI_ASSERTION"?e.assertion:e.description;return!n||n==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:rA.test(n)&&oA.test(n)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:aA.test(n)?{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"}:iA.test(n)?{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(n)?{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 Kh(t,e){if(!(!t.envs||!t.envs.length)){for(let n of t.envs){let r=n;e in n&&(r[e]&&(n.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}t.envs.some(n=>n.default)||(t.envs[0].default=!0)}}import{cloneDeep as Ef}from"lodash-es";import mA from"diff-lines";import qs,{gte as pA}from"semver";var Yh={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>(t=t.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),t=t.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),t)};var Xh={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let n=e.commands,r=n[n.length-1];return r&&r.type!=="SUCCESS"&&n.push({type:"SUCCESS"}),e})};var lA=["target","fromTarget","toTarget"];function Jh(t){for(let e of lA){if(t[e]===void 0)continue;let n=t[e];n.elementDescriptor!==void 0?n.type="description":t[e]={type:"description",elementDescriptor:""}}}var Qh={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":return Jh(e.command),e;case"AI_ACTION":{let n=e.commands;for(let r of n??[])Jh(r);return e}default:return e}})};import{v4 as cA}from"uuid";var Zh={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=cA()),e;default:return e}})};import{v4 as ef}from"uuid";var tf={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return n.id=n.id??ef(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(n=>({type:"PRESET_ACTION",command:{...n,id:n.id??ef()}})),delete e.commands),e;default:return e}})};var nf={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return typeof n.type!="string"||n.type!=="AI_WAIT"||(n.type="AI_ASSERTION",n.timeout||(n.timeout=10)),e}default:return e}})};import{v4 as dA}from"uuid";var rf={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>("id"in e&&typeof e.id=="string"||(e.id=dA()),e))};import{v4 as of}from"uuid";var af={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let n=e.condition;n.id||(n.id=of())}return e.id=of(),e})};var sf={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};import{v4 as uA}from"uuid";var lf={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=uA()),e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};var cf={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:n.option},e.option=void 0),e})};var df={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return n&&uf(n),e})};function uf(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){uf(t[e]);return}if(typeof t[e]!="string")return;let n=t[e];e==="code"?t[e]=n.replace(/inputs\./g,"env."):n.includes("{{")&&n.includes("}}")&&(t[e]=n.replace(/inputs\./g,"env."))})}var mf={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TAB"||n.url===void 0||(n.action={type:"SUBSTRING",substring:n.url},n.url=void 0),e})};var pf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TYPE"?e:n.pressKeysSequentially===void 0?(n.delay=0,e):(n.pressKeysSequentially&&(n.pressKeysSequentially=void 0,n.delay=50),e)})};var gf={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="WAIT_FOR_URL"||n.url===void 0||(n.matcher={type:"GLOB",glob:n.url},n.url=void 0),e})};var hf={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;if(!n)return e;if(n.type==="SELECT_OPTION"){if(n.option===void 0)return e;n.choice={type:"VALUE",value:n.option},n.option=void 0}else if(n.type==="TAB"){if(n.url===void 0)return e;n.action={type:"SUBSTRING",substring:n.url},n.url=void 0}else if(n.type==="WAIT_FOR_URL"){if(n.url===void 0)return e;n.matcher={type:"GLOB",glob:n.url},n.url=void 0}else n.type==="AI_WAIT"&&(n.type="AI_ASSERTION",n.timeout||(n.timeout=10));return e})};var ff={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="MOCK_ROUTE"&&n.type!=="SET_HEADER"&&n.type!=="RECORD_REQUESTS"&&n.type!=="REGISTER_REQUEST_LISTENER"||(n.type==="REGISTER_REQUEST_LISTENER"||n.type==="RECORD_REQUESTS"?n.requestMatcher={urlMatcher:{type:"REGEX",regex:n.pattern}}:(n.type==="SET_HEADER"||n.type==="MOCK_ROUTE")&&n.urlPattern&&(n.requestMatcher={urlMatcher:{type:"REGEX",regex:n.urlPattern}})),e})};var Sf={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async t=>t.map(e=>{if(e.type!=="AI_ASSERTION")return e;let 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 Vs=new Set(["CLICK","TYPE","SELECT_OPTION"]),yf={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type,o=n?.elementDescriptor;return(o!==void 0||Vs.has(r))&&(n.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i?.elementDescriptor,l=i?.type;(s!==void 0||Vs.has(l))&&(i.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,l=s?.elementDescriptor,c=s?.type;(l!==void 0||Vs.has(c))&&(s.target={elementDescriptor:l??""}),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(u=>{let m=u?.elementDescriptor,p=u?.type;(m!==void 0||Vs.has(p))&&(u.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var bf={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e;return n.status==="FAILURE"&&(n.status="FAILED"),typeof n.commands=="object"&&Array.isArray(n.commands)&&n.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),n}),stopOnFailure:!0};var Tf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type;return r?.startsWith("PRESET_")&&(n.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let i=a.type;i?.startsWith("PRESET_")&&(a.type=i.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let i=a.command,s=i?.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7)),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(c=>{let d=c.type;d?.startsWith("PRESET_")&&(c.type=d.slice(7))})}),e}),stopOnFailure:!0};var Zr=[Sf,bf,Tf,yf,Yh,Xh,Qh,Zh,tf,nf,rf,af,sf,lf,cf,df,mf,pf,gf,hf,ff];if(se!==Zr[Zr.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Zr.forEach((t,e)=>{if(!qs.valid(t.toVersion)||!qs.valid(t.fromVersion))throw new Error(`Migration '${t.name}' has invalid version`);if(!qs.gt(t.toVersion,t.fromVersion))throw new Error(`Migration '${t.name}' has toVersion <= fromVersion`);if(e===0)return;if(Zr[e-1].toVersion!==t.fromVersion)throw new Error(`Migration '${t.name}' at index ${e} is not contiguous with previous migration`)});function gA(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var ri=async({metadata:t,steps:e,logger:n,toVersion:r})=>{let o=e,{schemaVersion:a,id:i}=t,s=Zr.findIndex(d=>qs.gt(d.toVersion,a));if(s===-1)return{steps:o,newVersion:a};let l=a;for(let d=s;d<Zr.length;d++){if(r&&pA(l,r)){n.debug("Stopping migration early because toVersion was reached");break}let u=Zr[d],m={id:i,migration:u.name,toVersion:u.toVersion};try{o=await wf(o,u),l=u.toVersion}catch(p){throw n.error({err:p,...m},"Migration failed"),new Error(`Step migration ${u.name} failed: ${p}`)}}let c=mA(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&n.debug({diffs:c,id:i},"Migration diffs"),{newVersion:l,steps:o}};async function wf(t,e){let n=await e.execute(t);for(let r of n)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let a=r[o];!a||!Array.isArray(a)||gA(a)&&(r[o]=await wf(a,e))}return n}async function Rf({rawSteps:t,metadata:e,logger:n,callbacks:r}){Kh(e,"defaultOnCloud");let o={},{resolvedSteps:a,newSchemaVersion:i}=await Ks({rawSteps:t.steps,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o}),s={...e,steps:a,schemaVersion:i};for(let l of["beforeSteps","afterSteps"]){let c=t[l];if(!c)continue;let{resolvedSteps:d}=await Ks({rawSteps:c,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o});s[l]=d}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function eo(t,e,n){let{newVersion:r,steps:o}=await ri({metadata:t,steps:e,logger:n});try{return{steps:Me.array().parse(o),newVersion:r}}catch(a){throw n.error({type:"zod",err:a,newVersion:r,id:t.id,steps:o},"Failed to parse test steps while migrating test"),new Ss(`Failed to parse test steps while migrating test: ${a}`,t.id,"entity",{cause:a})}}async function Ks({rawSteps:t,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:a,steps:i}=await eo(e,t,n),s=[];for(let l of i)s.push(await oi({step:l,callbacks:r,logger:n,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:a}}async function oi({step:t,callbacks:e,logger:n,resolvedModuleCache:r}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let l=t.moduleId,c=r[l];if(c)return{...Ef(c),...t,type:"RESOLVED_MODULE"};let d=await e.onFetchModule({id:l,logger:n});if(!d)throw new Error(`Could not find module with id ${l}`);let{newVersion:u,steps:m}=await ri({metadata:{id:l,schemaVersion:d.schemaVersion},steps:d.steps,logger:n}),p;try{p=Me.array().parse(m)}catch(f){throw n.error({type:"zod",err:f,steps:m,newVersion:u,id:l},"Module failed to parse"),f}let g;try{g=await Promise.all(p.map(f=>oi({step:f,callbacks:e,logger:n,resolvedModuleCache:r})))}catch(f){throw n.error({err:f,...t},`Failed to recursively resolve module '${d.name}': ${f}`),f}let h={...d,steps:g};return r[l]=Ef(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of t.blocks){let c=[];for(let d of l.steps)c.push(await oi({step:d,callbacks:e,logger:n,resolvedModuleCache:r}));o.push({...l,steps:c})}let a;if(t.elseSteps){a=[];for(let l of t.elseSteps)a.push(await oi({step:l,callbacks:e,logger:n,resolvedModuleCache:r}))}return{...t,blocks:o,elseSteps:a};case"SECTION":let i=[];for(let l of t.steps)i.push(await oi({step:l,callbacks:e,logger:n,resolvedModuleCache:r}));return{...t,steps:i};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function hA(t){return typeof t=="object"&&t!==null}function Gn(t){if(Array.isArray(t))return t.map(Gn);if(hA(t)){let e={};return Object.entries(t).forEach(([n,r])=>{r!==void 0&&(e[n]=Gn(r))}),e}return t}import{cloneDeep as fA}from"lodash-es";import{stringify as Cf}from"yaml";async function vf({test:t,processedModuleNames:e=new Set,createNewCacheIds:n=!1}){let r={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},a=await SA({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:n}),i={fileType:pe.TEST,...r,beforeSteps:a.beforeSteps&&a.beforeSteps.length>0?a.beforeSteps:void 0,steps:a.steps,afterSteps:a.afterSteps&&a.afterSteps.length>0?a.afterSteps:void 0};return{test:Cf(i),modules:o}}async function SA({originalStepLists:t,modules:e,processedModuleNames:n,createNewCacheIds:r}){let o=fA(t);Object.values(o).forEach(s=>{yA(s??[])});let{stepsToSave:a,moduleUpdates:i}=await He({stepLists:o,createNewCacheIds:r});for(let s of i)n.has(s.name)||(e[s.name]=bA(s),n.add(s.name));return a}function yA(t){ni({steps:t,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function bA(t){let e=Ot.parse(t),n={fileType:pe.MODULE,...e,schemaVersion:se,steps:t.steps};return Cf(n)}async function J(t,e){if(!(t<=0))return new Promise((n,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",a);let o=setTimeout(()=>{e?.removeEventListener("abort",a),n()},t);function a(){clearTimeout(o),e?.removeEventListener("abort",a),r(e?.reason)}})}async function ai({promiseGenerator:t,signal:e,codePath:n,logger:r}){let a=Date.now(),i=setInterval(()=>{if(e?.aborted){clearInterval(i);return}r?.warn({codePath:n,startTime:a,elapsedMilliseconds:Date.now()-a},`Asynchronous operation is taking a long time (${n})`)},5e3);return new Promise((s,l)=>{function c(){clearInterval(i),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(i);return}e?.addEventListener("abort",c),(async()=>{try{s(await t())}catch(d){l(d)}finally{clearInterval(i),e?.removeEventListener("abort",c)}})()})}async function to({promiseGenerator:t,timeoutMs:e,codePath:n,logger:r,signal:o}){let a=!1,i=new AbortController,s=()=>{i.abort()},l=setTimeout(()=>{a||i.abort()},e);o?.addEventListener("abort",s);try{return await ai({promiseGenerator:t,signal:i.signal,codePath:n,logger:r})}finally{a=!0,o?.removeEventListener("abort",s),clearTimeout(l)}}function Af(t){let e;return t>10*60*1e3?e=2*60*1e3:t>60*1e3?e=20*1e3:t>10*1e3?e=2*1e3:e=1e3,e}function Ys(t){let e=[];for(let n of t)switch(n.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(n);break;case"RESOLVED_MODULE":{let r={...n,type:"MODULE"};e.push(sn.parse(r));break}case"SECTION":{let r={...n,steps:Ys(n.steps)};e.push(Me.parse(r));break}case"CONDITIONAL":{let r={...n,blocks:n.blocks.map(o=>({assertion:o.assertion,steps:Ys(o.steps)})),elseSteps:n.elseSteps?Ys(n.elseSteps):void 0};e.push(Br.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}function Xs(t){return Ys([t])[0]}import TA from"picomatch";var Js=(t,e,n)=>{n?.caseInsensitive&&(t=t.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=n?.caseInsensitive?e.url.toLowerCase():e.url;r=t.includes(o);break}case"GLOB":{let o=n?.caseInsensitive?e.glob.toLowerCase():e.glob;r=t===e.glob||TA(o)(t);break}case"REGEX":{r=new RegExp(e.regex).test(t);break}case"DOMAIN":{let o=n?.caseInsensitive?e.domain.toLowerCase():e.domain;r=new URL(t).hostname===o;break}}return n?.negated?!r:r},Qs=(t,e)=>{try{let{hostname:n,pathname:r}=new URL(t),{hostname:o,pathname:a}=new URL(e);return n!==o||r!==a}catch{return!1}},Zo=t=>{try{return new URL(t),!0}catch{return!1}},xf=t=>!t.toLowerCase().startsWith("http"),ea=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function no(t,e){try{return!!new URL(t).origin.trim()}catch(n){return e?.error({url:t,err:n},"Invalid URL in check"),!1}}async function wA(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:l}=t,c=[];if(o.length>0){let{results:u}=await Qo(e,n,o,{numStepsWithScreenshots:s,maxItemsFromEnd:i,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});c=u}return await r.getTestResultClassification({results:c,errorMessage:a.message,errorStack:a.stack},{disableCache:l??!1})}async function If(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:l}=t;if(!n||!o||o.length===0)return{};try{let c=await wA({logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:l});return{classification:c,aiFailureReason:c.reason}}catch(c){return e.error({err:c},"Failed to classify test result"),{}}}function ta({orgId:t,client:e,gitMetadata:n,alwaysSaveCache:r,noCache:o}){return o?new As:new Dd(t,e,n,r)}var Dd=class{constructor(e,n,r,o){this.orgId=e;this.client=n;let{gitBranchName:a,gitProtectedBranches:i}=r;this.cacheHeaders=hd(r),o?this.writeCaches=!0:a?this.writeCaches=!i.includes(a):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:n,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:n},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:n,beforeSteps:r,afterSteps:o}=e.stepLists,a=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[n,r,o])s&&Jo({steps:s,stepCacheEntries:a,logger:e.logger});let{cachesToSave:i}=await He({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:i,testId:e.testId},this.cacheHeaders)}};import RA from"path";var CA=new Os(30,60*1e3),zd="https://api.momentic.ai",Pf,Mf=t=>{zd=t},ii=()=>zd;var na,Bd,Zs,Lf=async t=>{if(Pf&&na&&Zs)return na;let e=new Je({baseUrl:zd,apiKey:t,logger:S});Pf=e;try{let n=await e.getAuthInfo();return na=n.orgId,Bd=n.userId,Zs=t,na}catch(n){throw new Error(`Error checking API key against server: ${n}`)}},rn=()=>{if(!na)throw new Error("Your organization ID is invalid.");return na},el=()=>{if(!Bd)throw new Error("Your user ID is invalid.");return Bd},Hd=()=>{if(!Zs)throw new Error("Your API key is invalid.");return Zs},$d,Fd,tl=(t,e)=>{$d=t,Fd?.abort(),Fd=new AbortController;let n=Fd.signal,r=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let a=RA.resolve(t.rootDir,o.envFile);try{if(Ud.lstatSync(a).isSymbolicLink())return;Ud.existsSync(a)&&r.push(a)}catch(i){S.warn({err:i},`Failed to check if env file ${a} exists`)}});try{vA({filesToWatch:r,revalidator:e,signal:n,project:t})}catch(o){S.error({err:o},"Failed to start config file watchers")}},ae=()=>$d;function vA({filesToWatch:t,revalidator:e,signal:n,project:r}){t.forEach(o=>{Ud.watch(o,{signal:n,persistent:!1,recursive:!1},(a,i)=>{i&&(CA.increment("setLocalProject")&&S.warn(`A file change under the ${r.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),$d=e(r.configFilePath))})})}function ce(t){return function(...e){let n=e[e.length-1],r=t(...e);Promise.resolve(r).catch(n)}}var li=AA();function si(t){let e=ae(),n=lt.dirname(e.configFilePath);return lt.join(n,...t)}function IA(t){let e=ae(),n=lt.dirname(e.configFilePath),r=lt.relative(n,t);return r?r.split(lt.sep):[]}function PA(t,e){let n=It.statSync(t),r=IA(t);return sd.parse({name:e,absolutePath:t,relativePath:r.join(lt.sep),pathSegments:r,isDirectory:n.isDirectory(),size:n.size,createdAt:n.birthtime,modifiedAt:n.mtime,accessedAt:n.atime})}li.post("/",ce(async(t,e,n)=>{let r;try{r=hg.parse(t.body).pathSegments}catch(u){e.status(400).json({error:`Failed to parse folder read body: ${u}`});return}let o=si(r);if(!It.existsSync(o)){e.status(404).json({error:`Path not found: ${r.join(lt.sep)}`});return}if(!It.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(lt.sep)}`});return}let i=ae(),s=Array.from(i.config.exclude??[]).concat(ws),c=xA("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(u=>{let m=lt.join(o,u);return PA(m,u)}),d={absolutePath:o,pathSegments:r,contents:c};e.status(200).json(d)}));li.put("/",ce(async(t,e,n)=>{let r;try{r=fg.parse(t.body).pathSegments}catch(i){e.status(400).json({error:`Failed to parse folder create body: ${i}`});return}let o=si(r);if(It.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${r.join(lt.sep)}`,pathSegments:r});return}It.mkdirSync(o,{recursive:!0});let a={success:!0,message:`Folder created: ${r.join(lt.sep)}`,pathSegments:r};e.status(201).json(a)}));li.patch("/",ce(async(t,e,n)=>{let r,o;try{let c=Sg.parse(t.body);r=c.pathSegments,o=c.newPathSegments}catch(c){e.status(400).json({error:`Failed to parse folder update body: ${c}`});return}let a=si(r),i=si(o);if(!It.existsSync(a)){e.status(400).json({error:`Folder not found: ${r.join(lt.sep)}`});return}if(It.existsSync(i)){e.status(400).json({error:`Destination already exists: ${o.join(lt.sep)}`});return}let s=lt.dirname(i);It.existsSync(s)||It.mkdirSync(s,{recursive:!0}),It.renameSync(a,i);let l={success:!0,message:`Folder moved from ${r.join(lt.sep)} to ${o.join(lt.sep)}`,pathSegments:o};e.status(200).json(l)}));li.delete("/",ce(async(t,e,n)=>{let r,o=!0;try{let l=yg.parse(t.body);r=l.pathSegments,o=l.recursive??!0}catch(l){e.status(400).json({error:`Failed to parse folder delete body: ${l}`});return}let a=si(r);if(!It.existsSync(a)){e.status(200).json({success:!0,message:`Folder not found: ${r.join(lt.sep)}`,pathSegments:r});return}if(!It.statSync(a).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(lt.sep)}`});return}if(o)It.rmSync(a,{recursive:!0,force:!0});else{if(It.readdirSync(a).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${r.join("/")}`});return}It.rmdirSync(a)}let s={success:!0,message:`Folder deleted: ${r.join("/")}`,pathSegments:r};e.status(200).json(s)}));var jd=li;import KL from"events";import Gb,{Router as YL}from"express";import{diff as NA}from"deep-object-diff";import dn from"fs";import oo from"path";import ra from"yaml";import{z as _f}from"zod";import{execSync as MA}from"child_process";function ro(t,e){let n=e.hooks?.postSave;if(!n)return;let r;n.includes("$1")?r=n.replaceAll("$1",t):r=`${n} ${t}`,S.debug({postSaveCommand:r},"Executing post-save hook command");try{MA(r,{encoding:"utf-8"})}catch(o){S.warn({err:o,postSaveCommand:r},"Failed to execute post-save hook command, continuing...")}}import{diff as Of}from"deep-object-diff";import xn from"fs";import{cloneDeep as LA}from"lodash-es";import ci from"path";import{v4 as OA}from"uuid";import di from"yaml";function $t({content:t,schemaVersion:e,momenticFiles:n,project:r,forceSaveOnNoDiffs:o}){let a=n.modules[t.moduleId]?.fullFilePath;if(!a||!xn.existsSync(a))throw new Error(`Tried to update module ${t.moduleId} that could not be found on disk`);let i=xn.readFileSync(a,"utf-8"),s=di.parse(i),l;if(t.name&&t.name!==s.name){let p=`${ve(t.name)}.${st.MODULE}`;if(l=ci.join(ci.dirname(a),p),xn.existsSync(l))throw new Error(`Module with name '${t.name}' already exists at path '${l}'`)}let c={...t,schemaVersion:e},d=Gn({fileType:pe.MODULE,...dd.parse(c),steps:Me.array().parse(t.steps)}),u=Of(d,s);if(u&&Object.keys(u).length===0&&!o){S.debug(`Skipping save for module ${t.moduleId} since there are no changes`);return}let m=di.stringify(d);xn.writeFileSync(a,m,"utf-8"),l&&xn.renameSync(a,l),ro(l||a,r.config)}function Nf({moduleId:t,content:e,momenticFiles:n,project:r,logger:o}){let a=n.modules[t]?.fullFilePath;if(!a)throw new Error(`Tried to update module ${t} that could not be found on disk`);let i=Wn(a,o),s={...i,...e},l=Gn({fileType:pe.MODULE,...dd.parse(s),steps:i.steps}),c=Of(l,i);if(c&&Object.keys(c).length===0){S.debug(`Skipping save for module ${t} since there are no changes`);return}let d=di.stringify(l);xn.writeFileSync(a,d,"utf-8");let u;if(e.name){let m=`${ve(e.name)}.${st.MODULE}`;if(u=ci.join(ci.dirname(a),m),xn.existsSync(u))throw new Error(`Module with name '${e.name}' already exists at path '${u}'`);xn.renameSync(a,u)}ro(u||a,r.config)}async function kf({name:t,description:e,enabled:n,steps:r,folder:o,project:a}){let i=ve(t),s=ci.join(o,`${i}.module.yaml`),l=OA(),{stepsToSave:c}=await He({stepLists:{steps:r}}),d={fileType:pe.MODULE,schemaVersion:se,moduleId:l,name:t,description:e,enabled:n,steps:c.steps},u=di.stringify(d);return xn.writeFileSync(s,u,"utf-8"),ro(s,a.config),{moduleId:l,name:t,description:e,enabled:n,steps:r}}function Wn(t,e){let n=xn.readFileSync(t,"utf-8"),r=di.parse(n);try{return ed.parse(r)}catch(o){throw e.error({err:o,moduleFilePath:t,moduleContents:n},`${t} does not parse as a valid Momentic module`),o}}async function nl(t,e,n,r){let o=Wn(t.fullFilePath,n),{resolvedSteps:a}=await Ks({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:r,logger:n,callbacks:{onFetchModule:async({id:s})=>{let l=e.modules[s]?.fullFilePath;if(l)return Wn(l,n)}}}),i={...o,steps:a};return r&&(r[t.id]=LA(i)),i}async function rl(t,e){let n={};return await Promise.all(Object.values(t.modules).map(async r=>{await nl(r,t,e,n)})),Array.from(Object.values(n))}async function Df({test:t,name:e,folder:n}){let r=await vf({test:t});if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let a=`${ve(e)}.${st.TEST}`,i=oo.join(n,a);return dn.writeFileSync(i,r.test,"utf-8"),i}function Gd(t,e,n){let r=oo.join(n.rootDir,t);if(!dn.existsSync(r))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let o=dn.readFileSync(r,"utf-8"),a=ra.parse(o),i,s;if(e.name&&e.name!==a.name){let m=`${ve(e.name)}.${st.TEST}`;if(i=oo.join(oo.dirname(t),m),s=oo.join(n.rootDir,i),dn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let l={...a,...e},c=en.parse(l),d={fileType:pe.TEST,...en.parse(c),beforeSteps:a.beforeSteps??void 0,steps:a.steps,afterSteps:a.afterSteps??void 0},u=ra.stringify(d);return dn.writeFileSync(r,u,"utf-8"),s&&dn.renameSync(r,s),ro(r,n.config),{newRelativeTestPath:i}}function Pt({relativeTestPath:t,steps:e,schemaVersion:n,project:r,forceSaveOnNoDiffs:o}){let a=oo.join(r.rootDir,t);if(!dn.existsSync(a))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let i=dn.readFileSync(a,"utf-8"),s=ra.parse(i),l=en.parse({...s,schemaVersion:n}),c=Me.array().or(_f.undefined()).parse(e.beforeSteps),d=Me.array().parse(e.steps),u=Me.array().or(_f.undefined()).parse(e.afterSteps),m=Gn({fileType:pe.TEST,...l,beforeSteps:c&&c.length>0?c:void 0,steps:d,afterSteps:u&&u.length>0?u:void 0}),p=NA(m,s);if(p&&Object.keys(p).length===0&&!o){S.debug(`Skipping save for test ${l.name} since there are no changes`);return}let g=ra.stringify(m);dn.writeFileSync(a,g,"utf-8"),S.debug(`Saving test ${l.name} to ${a}`),ro(a,r.config)}function ol(t,e){let n=oo.join(e.rootDir,t);if(!n)throw new Error(`Could not find test with path ${t} in Momentic project (${e.rootDir})`);let r;try{r=dn.readFileSync(n,"utf8"),r=r.replace(/\r\n|\r/g,`
27
- `)}catch(a){throw new Error(`Could not read test file ${n}: ${a}`)}let o;try{o=ra.parse(r)}catch(a){throw new Error(`Could not parse test file ${n} as YAML: ${a}`)}return St.parse(o)}function ao(t,e,n){let r=n.project.rootDir,o;try{o=dn.readFileSync(t,"utf-8")}catch(i){throw e.error({err:i,projectRoot:r},i.message),new Error(i.message)}let a=ra.parse(o);if(!a.steps||!Array.isArray(a.steps))throw new Error(`Test ${t} is missing steps`);return a}async function Mt(t,e,n){let r=ao(t,e,n),o;try{o=en.parse(r)}catch(i){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${i}`)}let{resolvedTest:a}=await Rf({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:i,logger:s})=>{let l=n.modules[i]?.fullFilePath;if(l)return Wn(l,s)}}});return a}import kA from"@dotenvx/dotenvx";import _A from"fs";import Ff from"path";function Uf(t,e){return(t.config.environments??[]).map(n=>ui(n.name,t,e))}function Bf(t){return t.includes("${")?t.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,o]=n.split(/:-|-/,2),a=process.env[r];return n.includes(":-")?a&&a!==""?a:o||"":n.includes("-")?a!==void 0?a:o||"":a||""}):t}function DA(t){let{envVariables:e,project:n}=t;if(!e)return{};let r={};for(let[o,a]of Object.entries(e)){if(typeof a=="string"){let s=Bf(a);s&&(r[o]=s);continue}let i;try{i=_A.readFileSync(Ff.resolve(n.rootDir,a.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${a.fromFile}': ${s}`)}if(a.json)try{r[o]=JSON.parse(i)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${a.fromFile}' as JSON: ${s}`)}else r[o]=i}return Object.keys(r).length>0&&S.debug(r,"Set environment variables with interpolation from project configuration"),r}function FA(t){let{project:e,envFile:n,logger:r}=t,o={};if(!n)return o;let a=kA.config({path:Ff.resolve(e.rootDir,n),processEnv:o,logLevel:"error",quiet:!0});if(a.error)throw new Error(`Failed to load .env file: ${a.error.message}`);return r.debug(o,"Set environment variables from .env file"),o}function ui(t,e,n){let r=(e.config.environments??[]).find(l=>l.name===t);if(!r)throw new Error(`Environment ${t} not found in local project configuration file`);if(!r.baseUrl)throw new Error(`Browser environment ${t} does not have a baseUrl configured`);let o={[at]:Bf(r.baseUrl)},a=DA({envVariables:r.envVariables,project:e});Object.assign(o,a);let i=FA({project:e,envFile:r.envFile,logger:n});return Object.assign(o,i),r.inheritFromShell&&(n.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:t,variables:o,browser:r.browser}}import{existsSync as YA,readFileSync as XA,readdirSync as JA,writeFileSync as QA}from"fs";import{globSync as ZA}from"glob";import io,{dirname as jf}from"path";import{cwd as Yd}from"process";import Gf from"yaml";import{z as ke}from"zod";import zf from"fs";import{globSync as UA}from"glob";import mi from"path";import BA from"yaml";import{z as Wd}from"zod";var Hf=!1,Vd=[`**/*.${st.TEST}`,`**/*.${st.MODULE}`],qd=Wd.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),Kd=50,zA=Wd.object({fileType:Wd.nativeEnum(pe)});function te(t,e){let n={project:t,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},r=t.config.include??Vd,o=Array.from(t.config.exclude??[]).concat(ws),a=UA(r,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:Kd,nodir:!0});for(let i of a){let s=HA(t.rootDir,i,n,e);s&&(n.duplicateEntities[s.id]=s.paths)}return Hf=!0,n}function HA(t,e,n,r){let o=mi.join(t,e),a=$A(o,r);if(!a)return;let i=jA(a,o,r);if(!i)return;let s=zA.safeParse(i);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=GA(o,r);if(!c)return;let d=WA(e,o,c);switch(l){case pe.TEST:try{return VA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${u}`);return}case pe.MODULE:try{return qA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${u}`);return}case pe.MOBILE_TEST:try{return KA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${u}`);return}default:{let u=l;return}}}function $A(t,e){try{return zf.readFileSync(t,"utf-8")}catch(n){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${n}`);return}}function jA(t,e,n){try{let r=BA.parse(t);if(typeof r!="object"||r===null)throw new Error("The YAML document should parse as a map with key-value pairs");return r}catch(r){n.warn(`Could not parse possible Momentic file at ${e}, skipping: ${r}`);return}}function GA(t,e){try{return zf.statSync(t)}catch(n){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${n}`);return}}function WA(t,e,n){return{relativePath:t,fullFilePath:e,platformSep:mi.sep,fullPathSegments:e.split(mi.sep),relativePathSegments:t.split(mi.sep),fileName:mi.basename(e),lastModified:n.mtime,createdAt:n.birthtime}}function VA(t,e,n,r,o){let a=en.parse(t),i;if(e.tests[a.id]){let s=e.tests[a.id].fullFilePath;i={id:a.id,paths:[s,r]}}return e.tests[a.id]={type:pe.TEST,name:a.name,id:a.id,description:a.description??void 0,labels:a.labels,...n},i}function qA(t,e,n,r,o){let a=Ot.parse(t),i;if(e.modules[a.moduleId]){let l=e.modules[a.moduleId].fullFilePath;i={id:a.moduleId,paths:[l,r]}}e.modules[a.moduleId]={type:pe.MODULE,name:a.name,id:a.moduleId,description:a.description??void 0,...n};let s=n.fileName.replace(`.${st.MODULE}`,"");return!Hf&&ve(a.name)!==s&&o.warn(`The module with ID ${a.moduleId} has a name (${a.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),i}function KA(t,e,n,r,o){let a=td.parse(t),i;if(e.mobileTests[a.id]){let l=e.mobileTests[a.id].fullFilePath;i={id:a.id,paths:[l,r]}}let s=n.fileName.replace(`.${st.TEST}`,"");return e.mobileTests[a.id]={type:pe.MOBILE_TEST,name:s,id:a.id,description:a.description??void 0,...n},i}var oa="momentic.config.yaml",$f="momentic.workspace.yaml",ex=ke.object({projects:ke.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),tx=ke.union([ke.string(),ke.object({fromFile:ke.string(),json:ke.boolean().optional()})]),nx=ke.object({name:qd,baseUrl:ke.string().optional().describe("Optional for mobile tests"),envFile:ke.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:ke.record(ke.string(),tx).optional(),inheritFromShell:ke.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:$r.optional().describe("deprecated: use project-level configuration only")}),rx=ke.object({postSave:ke.string().optional()}),ox=ke.object({name:qd,include:ke.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:ke.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:ke.string().optional(),reporterDir:ke.string().optional(),outputDir:ke.string().optional(),retries:ke.number().optional().describe("number of retries per test"),parallel:ke.number().optional().describe("degree of parallelism"),environments:ke.array(nx).optional(),gitMainBranch:ke.string().optional(),gitProtectedBranches:ke.string().array().optional(),ai:ud.optional(),browser:$r.optional(),advanced:md.optional(),hooks:rx.optional()});function Wf(t,e){let n;try{n=XA(t,"utf-8")}catch(o){S.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let r;try{if(r=Gf.parse(n),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){S.warn(`Possible Momentic ${e} file at ${t} does not parse as valid YAML: ${o}`);return}return r}function Xd(t){let e=Wf(t,"project configuration");if(e!==void 0)try{return ox.parse(e)}catch(n){S.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function ax(t){let e=Wf(t,"workspace configuration");if(e!==void 0)try{return ex.parse(e)}catch(n){S.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function ix(){let t=[],e=Yd(),n=io.parse(e).root,r=15,o=0;for(;o<r;){o++;let a=io.basename(e);if(Ts.includes(a))return S.warn(`Stopping search for Momentic projects since the current directory name (${a}) is likely a system artifact folder.`),t;for(let i of JA(e))if(i.endsWith(oa)){let s=io.join(e,i),l=Xd(s);l&&t.push({configFilePath:s,config:l,rootDir:jf(s)})}if(t.length)return t;if(e=io.dirname(e),e===n)break}return t}function ct(t={}){let{configFilePath:e,nameFilter:n}=t,r=Jd(e);if(n&&(r=r.filter(o=>o.config.name===n)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
28
- ${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return S.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function sx(t){let e=ax(t);if(!e||!e.projects||!e.projects.length)return;let n=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${oa}`)),r=ZA(n,{absolute:!1,cwd:Yd(),dotRelative:!1,maxDepth:Kd,nodir:!0}),o=[];for(let a of r){let i=io.join(Yd(),a),s=Xd(i);s&&o.push({configFilePath:i,config:s,rootDir:jf(i)})}return o}function Jd(t){if(t){t=io.resolve(t);let n=Xd(t);return n||(console.error(`No valid Momentic project file found at ${t}.`),process.exit(1)),[{config:n,configFilePath:t,rootDir:io.dirname(t)}]}if(YA($f)){let n=sx($f);if(n)return n}return ix()}function aa(t,e){let n=Gf.stringify(t);QA(e,n)}import ia from"fs";import Qd from"path";import{z as Zd}from"zod";var Vf="golden/visual-diff",qf="reports",Kf="test-results";var lx=Zd.object({width:Zd.number(),height:Zd.number()}),sa=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,n){let r=Qd.join(e.rootDir,e.config.goldenFileDir??Vf);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=n}async prepareGoldenScreenshotForComparison(e,n,r){if(n.screenshot?.data?.startsWith("https://")){let i=await fetch(n.screenshot.data);return{buffer:Buffer.from(await i.arrayBuffer()),width:n.screenshot.width,height:n.screenshot.height}}let o=n.screenshot?.data;o||(o=Qd.join(this.defaultGoldenScreenshotDir,`${n.id}.jpg`));let a=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ia.mkdirSync(Qd.dirname(o),{recursive:!0}),ia.writeFileSync(o,r.buffer),ia.writeFileSync(a,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(ia.existsSync(o)){let i=ia.readFileSync(o),s=lx.parse(JSON.parse(ia.readFileSync(a,"utf-8")));return{buffer:i,width:s.width,height:s.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var fr=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 cx}from"node:child_process";import{promisify as dx}from"node:util";import ux from"simple-git";var Ae=ux(),Yf=dx(cx);async function mx(t){let e=await xe(t,Ae.raw(["config","--list"])),n={};if(!e)return n;for(let r of e.split(`
29
- `)){let o=r.indexOf("=");if(o===-1)continue;let a=r.slice(0,o),i=r.slice(o+1).trim();n[a]=i}return n}async function px(t,e,n){try{let o=n["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("@"),a=e.indexOf(":",o+1);o!==-1&&a!==-1&&(r=e.slice(o+1,a))}}catch{}if(r=r?.toLowerCase(),!!r){try{if(e?.startsWith("git@")&&r?.includes("github")){let{stdout:o,stderr:a}=await Yf("ssh",["-T","-o","BatchMode=yes",`git@${r}`],{timeout:5e3}),s=`${o??""}${a??""}`.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:a}=await Yf("gh",o,{timeout:5e3}),i=a?.toString().trim();if(i)return i}catch{}}}async function gx(t,e,n){let r=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(r)return px(t,e,n);if(o)return}catch{}}function al(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let n=e[1].replace(".git","").split("/");if(n.length===2){let r=n[0],o=n[1];return`${r}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let n=new URL(t).pathname.split("/").filter(Boolean);if(n.length>=2){let r=n[0],o=n[1].replace(".git","");return`${r}/${o}`}}}async function xe(t,e){try{return(await e).trim()}catch(n){t.error({err:n},"Failed to run git command");return}}function hx(){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 fx(t){let[e,n,r,o]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.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:n,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function Sx(t){let[e,n,r]=await Promise.all([xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.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:n,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function yx(t){let[e,n,r,o]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),a=n?.includes("github.com"),i=n?.includes("gitlab.com"),s=n?al(n):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:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function bx(t){let[e,n,r]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,a=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?al(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:n,gitCommitAuthorName:r,githubRepository:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function Tx(t){let[e,n,r]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],a=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?al(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:n,gitCommitAuthorName:r,githubRepository:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function wx(t,e){let[n,r,o,a,i,s,l,c,d]=await Promise.all([xe(t,Ae.revparse(["HEAD"])),xe(t,Ae.revparse(["--short","HEAD"])),xe(t,Ae.revparse(["--abbrev-ref","HEAD"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"])),e?xe(t,Ae.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),mx(t)]),u=c?await xe(t,Ae.show(["--no-patch","--format=%ci",c])):void 0,m=a?.includes("github.com"),p=a?.includes("gitlab.com"),g=a?al(a):void 0,h=d["user.email"]||void 0,f=d["user.name"]||void 0,y=d["user.username"]||void 0,b=await gx(t,a,d)??y??void 0;return t.debug({userUsername:b,gitLocalUserLogin:y,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:n,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:a,gitCommitTimestamp:i?new Date(i):void 0,gitCommitMessage:s,gitCommitAuthorName:l,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:u?new Date(u):void 0,githubRepository:m?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function Ex(){let t=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:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function Rx(t){let e=t.config.gitProtectedBranches??[];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function eu(t,e){let n=hx();if(!n)return wx(t,e);switch(n){case"GithubActions":return fx(t);case"GitlabCI":return Sx(t);case"CircleCI":return yx(t);case"Buildkite":return bx(t);case"AzureDevOps":return Tx(t);case"GCPCloudBuild":return Ex()}}async function Cx(t,e,n,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGitlab(n,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let a=await e.getCommitFromGitlab(n,r.gitCommitSha);a&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??a.author.name,gitCommitMessage:o.gitCommitMessage??a.message})}return o}async function vx(t,e,n,r,o){let a=o;if(!o.gitCommitSha)return a;if(o.gitMainBranch&&(!a.lastCommitOnMainSha||!a.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGithub(n,r,o.gitMainBranch,o.gitCommitSha);a={...a,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!a.gitCommitTimestamp||!a.gitCommitAuthorName||!a.gitCommitMessage||!a.gitCommitAuthorName){let i=await e.getCommitFromGithub(n,r,o.gitCommitSha);i&&(a={...a,gitCommitTimestamp:a.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:a.gitCommitAuthorName??i.author.name,gitCommitMessage:a.gitCommitMessage??i.message})}return a}async function Ax(t,e,n){try{if(n.githubRepository){let[r,o]=n.githubRepository.split("/");return await vx(t,e,r,o,n)}else if(n.gitlabProjectPath)return await Cx(t,e,n.gitlabProjectPath,n)}catch(r){t.warn({err:r},"Failed to get remote git metadata")}return n}async function Sr(t,e,n){let r=await Rx(n),o=await eu(t,r.gitMainBranch),a={...r,...o};(!a.lastCommitOnMainSha||!a.lastCommitOnMainTimestamp)&&a.gitBranchName===r.gitMainBranch&&(a.lastCommitOnMainSha=a.gitCommitSha,a.lastCommitOnMainTimestamp=a.gitCommitTimestamp);let i=await Ax(t,e,a);return{...r,...o,...i}}import UJ from"yaml";import{randomUUID as xx}from"crypto";import Vn from"fs";import so from"path";var Xf={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let n=new Set([...t.labels??[],...e.labels??[]]);return Array.from(n)}};function Ix(t,e,n){if(Xf[n]){let a=Xf[n];return a(t,e)}let r=t[n],o=e[n];if(r!==o)throw new Error(`Metadata values for key "${n}" do not match: "${r}" vs "${o}"`);return r}var Jf=new Set([".DS_Store","__MACOSX"]);function Qf(t,e,n){let r=xx(),o=t.child({runGroupId:r});Vn.rmSync(e,{recursive:!0,force:!0});let a=Vn.readdirSync(n).filter(c=>!Jf.has(c)).map(c=>so.join(n,c));if(a.length===0)throw new Error(`No run groups found in results path: ${n}`);Vn.mkdirSync(e,{recursive:!0});let i=so.join(a[0],"metadata.json"),s={...Xa.parse(JSON.parse(Vn.readFileSync(i,"utf-8"))),id:r};for(let c of a){let d=so.join(c,"runs");if(!Vn.existsSync(d))continue;let u=Vn.readdirSync(d);for(let g of u){if(Jf.has(g))continue;let h=so.join(d,g),f=so.join(e,"runs",g);Vn.cpSync(h,f,{recursive:!0})}let m=so.join(c,"metadata.json"),p=Xa.parse(JSON.parse(Vn.readFileSync(m,"utf-8")));o.info({oldRunGroupId:p.id},"Merging metadata from run groups");for(let g in p){if(g==="id")continue;let h=g;s[h]=Ix(s,p,h)}}let l=so.join(e,"metadata.json");Vn.writeFileSync(l,JSON.stringify(s,null,2))}import Zf from"adm-zip";import tu from"fs";import il from"path";function Px(t){let e=new Zf,n=il.join(t,"metadata.json"),r=Xa.parse(JSON.parse(tu.readFileSync(n,"utf-8")));e.addLocalFile(n);for(let o of tu.readdirSync(il.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let a=o.replace(/\.zip$/,""),i=new Zf(il.join(t,"runs",o));for(let s of i.getEntries())s.isDirectory||e.addFile(il.join("runs",a,s.entryName),s.getData())}return{runGroupId:r.id,buffer:e.toBuffer()}}async function sl(t){let{client:e,consoleLogger:n,resultsPath:r}=t;if(!tu.existsSync(r)){n.warn("Results path does not exist, skipping upload.");return}let o=new ks(e);try{let{runGroupId:a,buffer:i}=Px(r),s=await o.uploadResultsArchive(a,i),l=`${e.getAppUrl()}/run-groups/${s}`;n.success(`Successfully uploaded test results. Once processed, your results can be found at ${l}`);return}catch(a){let i;a instanceof Error?i=a.message:typeof a=="string"?i=a:i="Unknown error",n.error(`Failed to upload test results: ${i}.`);return}}import Mx from"adm-zip";import Lt from"fs";import un from"path";var pi=class t{constructor(e){this.filePath=e;Lt.rmSync(this.filePath,{recursive:!0,force:!0}),Lt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new t(un.join(this.filePath,e))}mkdir(e){Lt.mkdirSync(un.join(this.filePath,e),{recursive:!0})}readFile(e){let n=un.join(this.filePath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}storeFile(e){let{name:n,contents:r}=e,o=un.join(this.filePath,n);try{Lt.writeFileSync(o,r)}catch{}}createRunArchive(e){return new nu(un.join(this.filePath,"runs"),e)}},nu=class{constructor(e,n){this.filePath=e;this.tempPath=un.join(e,`.${n}`),this.finalPath=un.join(e,`${n}.zip`),Lt.rmSync(this.tempPath,{recursive:!0,force:!0}),Lt.rmSync(this.finalPath,{recursive:!0,force:!0}),Lt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let n=un.join(this.tempPath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}mkdir(e){Lt.mkdirSync(un.join(this.tempPath,e),{recursive:!0})}cd(e){return new pi(un.join(this.tempPath,e))}storeFile(e){let{name:n,contents:r}=e,o=un.join(this.tempPath,n);Lt.writeFileSync(o,r)}close(){let e=new Mx;e.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store");let n=e.toBuffer();Lt.writeFileSync(this.finalPath,n),Lt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import XL from"http";import JL from"path";import{Server as aL}from"socket.io";var Lx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{e.info({sessionId:r},"Cancel event received");let o=n.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},eS={event:"cancel",createHandler:Lx};var Ox=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,a)=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),a({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),a({err:l.message})}}},tS={event:"fetchA11yTree",createHandler:Ox};var Nx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,a)=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let l=await s.html();a({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?a({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):a({err:l.message})}}},nS={event:"fetchDom",createHandler:Nx};var kx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),n.removeSession(r,e)}},rS={event:"disconnect",createHandler:kx};function In(t){let{result:e,nestedResults:n}=t;if(!t.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=_x(n);Dx(e,r,o);let a=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await Fx(a,e,r,o)}catch(i){t.logger.error({result:t.result,err:i},"Error hoisting scalar result metadata")}})())}function _x(t){let e=t[0],n;for(;;){switch(e.type){case"PRESET_ACTION":{n=e;break}case"CONDITIONAL":if(e.assertionResult){n=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){n=e;break}e=e.results[e.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(n)break}let r=t[t.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(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:n,lastMetadata:o}}function Dx(t,e,n){e&&(t.beforeUrl=e.beforeUrl),n&&(t.afterUrl=n.afterUrl,t.data=n.data,n.status!=="SUCCESS"&&(t.message=n.message))}async function Fx(t,e,n,r){await Promise.allSettled(t),n&&(e.beforeSnapshot=n.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import gi from"os";import Ux from"v8";var oS,Pn,Bx=gi.platform(),zx=gi.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{});function aS(t){let e=()=>{try{let n=!1,r=Hx(),o=$x();r.freeMemory<1e6&&(n=!0);let a=Ux.getHeapStatistics(),i=a.used_heap_size,s=a.heap_size_limit;i/s>.9&&(n=!0),n?t.warn({memory:r,cpu:o,heapStats:a},"Critical resource usage metrics detected"):t.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:zx,platform:Bx}}function Hx(){let t=gi.totalmem(),e=gi.freemem(),n=t-e;return{totalMemory:t,freeMemory:e,usedMemory:n}}function $x(){let t=gi.cpus(),e=Date.now(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;if(n.total=n.user+n.nice+n.sys+n.idle+n.irq,!Pn)return Pn=n,null;let r={user:n.user-Pn.user,nice:n.nice-Pn.nice,sys:n.sys-Pn.sys,idle:n.idle-Pn.idle,irq:n.irq-Pn.irq,total:n.total-Pn.total};return oS={measurementTime:e,intervalMs:e-Pn.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},Pn=n,oS}import{randomUUID as Zx}from"crypto";import{faker as jx}from"@faker-js/faker";import Gx from"assert";import Wx from"axios";import*as Vx from"child_process";import qx from"moment";import*as Kx from"otpauth";import Yx from"pg";async function iS(t){let e;try{e=new URL(t.url).hostname}catch{}let n=[];return t.headers.getSetCookie()?.forEach(r=>{let o=ds(r,e);n.push(...o)}),n}function Xx(t,e){if(!t&&!e)return;let n;if(t){let{url:o,options:a}=t;n=new Request(o,a)}let r;if(e){let{body:o,options:a}=e;r=new Response(o??null,a)}return{request:n,response:r}}async function Jx(t,e){switch(t){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let n=[];return e.headers.forEach((o,a)=>{n.push([a,o])}),{status:e.status,headers:n,body:await e.text()}}else throw new Error("Result is not a Response object")}}var Qx=Object.getPrototypeOf(async function(){}).constructor;async function sS(t,e,n){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o,additionalBindings:a,request:i,response:s}=e.bindings,l=e.tools,c={},d=(w,C)=>{o[w]=C,c[w]=C},u={},m=(w,C)=>{o[w]=C,u[w]=C},p;r.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let g;r.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new Qx("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(a??{}),r)(Wx,qx,l.fakerInstance??jx,Gx,Yx,p,g,Kx,Vx,iS,o,e.options.disallowVariableUpdates?void 0:d,e.options.disallowVariableUpdates?void 0:m,C=>l.sms.send(C),C=>l.sms.fetchLatest(C),l.email,l.sms,l.ai,Xx(i,s),...Object.values(a??{}))),f=!0,y,b;try{let w=await H(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});y=await Jx(e.options.responseSerialization??"RAW",w)}catch(w){n.error({err:w,env:o,evalCode:r},`[${t}] Error executing code: ${w}`),f=!1,w instanceof pr?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=w instanceof Error?w.message:`${w}`}return{result:y,variableUpdates:c,persistentVariableUpdates:u,success:f,error:b}}async function lS({code:t,fragment:e,context:n,localTools:r,logger:o,signal:a,timeoutMs:i=cr,disallowVariableUpdates:s,additionalBindings:l,responseSerialization:c,mock:d}){let u=Zx(),m=await sS(u,{code:t,options:{fragment:e,timeoutMs:i,disallowVariableUpdates:s,responseSerialization:c},bindings:{...n.toObjectCopy(),...d,additionalBindings:l},tools:r,signal:a},o);return S.debug(`[${u}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as eI,randomUUID as tI}from"crypto";import nI from"fetch-retry";var rI=nI(global.fetch,{retries:3,retryOn:function(t,e,n){return!!(e!==null||n&&n.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),cS=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,dS=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function uS({orgId:t,code:e,fragment:n,context:r,timeoutMs:o=cr,retries:a=2,signal:i,logger:s,additionalBindings:l,disallowVariableUpdates:c,responseSerialization:d,mock:u}){if(!cS)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,p,g=0;if(!dS)throw new Error("Missing lambda auth secret.");let h=eI("sha256",dS).update(t).digest("hex");for(;g<=a;){g++,i?.throwIfAborted();let y={id:tI(),orgId:t,momenticLambdaAuthHash:h,code:e,fragment:n,state:{...r.toObjectCopy(),...u,additionalBindings:l},timeoutMs:o,disallowVariableUpdates:c,responseSerialization:d};try{if(m=await H(rI(cS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:i}),!m)throw new Error("Got empty response from code evaluation server");if(!m.ok)throw new Error(`Code evaluation server returned error code ${m.status}`);p=void 0;break}catch(b){p=b}}if(p)throw s.error({err:p},"Failed to evaluate code remotely"),p;if(!m)throw new Error(`An unexpected code evaluation error occurred${p?`: ${p}`:""}`);let f;try{f=Wp.parse(await m.json())}catch(y){throw new Error(`Code evaluation server returned invalid response: ${y}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function yr(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await uS(t);else if(t.localTools)e=await lS({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let n=`Failed to evaluate code:
25
+ ${Qr(`Sub-steps: ${e}`,2)}`}default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}var Bh=1e3,zh=3e6,oA="[FAILED]";async function Hh(t,e,n){if(n){let r=await e.getScreenshot(t,n);if(r)return`data:image/jpeg;base64,${Buffer.from(r).toString("base64")}`}}function aA(t,e){let n=(()=>{switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":return"AI action";case"PRESET_ACTION":return"Preset action";case"MODULE":return"Module";case"CONDITIONAL":return"Conditional step";case"SECTION":return"Section";default:return(a=>{throw new Error("You missed a case in the switch above")})(t)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${n}
26
+ ${o}`:o)(Ld(t))}function Gs(t,e={}){let{index:n,includeDomState:r=!1,header:o}=e,a=aA(t,o),i;t.type==="PRESET_ACTION"&&(i=t.results?.[0]?.elementInteracted);let s=t.message!=="Successfully executed preset action."?t.message:void 0,c=a;t.status==="FAILED"&&(c=`${oA} ${c}`);let l={description:c,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:i,message:s,index:n};if(t.status==="FAILED"&&r)try{let d=ip.array().parse(t.details);for(let u of d)"pageState"in u&&(l.pageState=u.pageState)}catch{}return l}async function Wh(t,e,n,{addIndices:r=!0,includeDomState:o=!1,flatten:a=!0,maxItemsFromEnd:i=15,indexOffset:s=0}){let c,l=[];for(let d=0;d<n.length;d++){let u=n[d],m=r?d+s:void 0;switch(u.type){case"PRESET_ACTION":{l.push(Gs(u,{index:m,includeDomState:o,header:void 0})),u.status==="FAILED"&&(c=m);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(a){l.push(Gs(u,{index:r?m:void 0,includeDomState:o,header:"start"})),s+=1;let{failureIndex:p,results:g}=await Wh(t,e,u.results,{addIndices:r,includeDomState:o,flatten:a,maxItemsFromEnd:i,indexOffset:s+d});if(l.push(...g),p!==void 0){c=p;break}s+=g.length,l.push(Gs(u,{index:r?s+d:void 0,includeDomState:o,header:"end"})),s+=1}else l.push(Gs(u,{index:r?s+d:void 0,includeDomState:o,header:void 0}));break}default:return(g=>{throw new Error("You missed a case in the switch above")})(u)}if(c!==void 0)break}return{results:l,failureIndex:c}}async function Qo(t,e,n,{numStepsWithScreenshots:r=5,addIndices:o=!0,includeBeforeScreenshots:a=!1,includeDomState:i=!1,flatten:s=!0,maxItemsFromEnd:c=20}){let{results:l,failureIndex:d}=await Wh(t,e,n,{addIndices:o,includeDomState:i,flatten:s,maxItemsFromEnd:c,indexOffset:0}),u=[],m=0;if(c!==void 0&&l.length>c&&(m=l.length-c),d!==void 0&&d<l.length-1&&t.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:l.length,lastIndex:l.length-1,isLastIndex:d===l.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let p=m;p<l.length;p++){let g=l[p],h={description:g.description,startedAt:g.startedAt,finishedAt:g.finishedAt,beforeUrl:g.beforeUrl,afterUrl:g.afterUrl,elementInteracted:g.elementInteracted,message:g.message,pageState:g.pageState,index:g.index},f,b;(r===void 0||r>0&&p>=l.length-r)&&(g.afterSnapshot&&(b=await Hh(t,e,g.afterSnapshot)),a&&g.beforeSnapshot&&(f=await Hh(t,e,g.beforeSnapshot))),h.beforeScreenshot=f,h.afterScreenshot=b,u.push(h)}return{results:u,failureIndex:d!==void 0?d-m:void 0}}function Nd({json:t,keysToRedact:e,maxJsonStringSize:n}){try{if(!t)return t;if(typeof t=="string")return $e(t,n??2e4);if(typeof t=="object"){let{jsonString:r}=Gh(JSON.stringify(t,(o,a)=>e?.includes(o)||typeof a=="string"&&a.length>3e4?"REDACTED":a),n??2e4);return JSON.parse(r)}return t}catch{return t}}function Od(t,e){for(let n=0;n<t.length;n++){let r=t[n];try{if(r.data){let{jsonString:o}=Gh(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":$h(r);break;case"CONDITIONAL":r.assertionResult&&$h(r.assertionResult),Od(r.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{Od(r.results,e);break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}}function $h(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function jh(t,e){let n=JSON.stringify(t),r=n.replaceAll("\\u0000","");if(n.length!==r.length){let o=n.indexOf("\\u0000");e.warn({input:n.slice(Math.max(0,o-500),Math.min(n.length,o+500))},"Database content violation: stripped unicode character from input")}return r}function Ws(t,e){let n=rA(t);if(Od(n,e),n.length>Bh)return e.error("Database content violation: results too long, truncating before insertion"),n.slice(0,Bh);let r=jh(n,e);if(r.length>zh)for(e.error({serializedLength:r.length,resultsArrayLength:n.length},"Database content violation: results too large, truncating before insertion");r.length>zh;)n.pop(),r=jh(n,e);try{return rt.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 xY}from"lodash-es";var iA=/^(?!.*\S+\s+\S+).*$/,sA=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,lA=/style="([^"]*)/g,cA=/data-[\w-]+/g,dA=t=>{switch(t.type){case"AI_ASSERTION":return{type:t.type,assertion:t.assertion};case"DRAG":if(t.fromTarget.type==="description")return{type:t.type,description:t.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(t.target?.type==="description")return{type:t.type,description:t.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function Vh(t){let e=dA(t),n=e.type==="AI_ASSERTION"?e.assertion:e.description;return!n||n==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:iA.test(n)&&sA.test(n)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:lA.test(n)?{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"}:cA.test(n)?{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(n)?{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 qh(t,e){if(!(!t.envs||!t.envs.length)){for(let n of t.envs){let r=n;e in n&&(r[e]&&(n.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}t.envs.some(n=>n.default)||(t.envs[0].default=!0)}}import{cloneDeep as wf}from"lodash-es";import hA from"diff-lines";import qs,{gte as fA}from"semver";var Kh={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>(t=t.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),t=t.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),t)};var Yh={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let n=e.commands,r=n[n.length-1];return r&&r.type!=="SUCCESS"&&n.push({type:"SUCCESS"}),e})};var uA=["target","fromTarget","toTarget"];function Xh(t){for(let e of uA){if(t[e]===void 0)continue;let n=t[e];n.elementDescriptor!==void 0?n.type="description":t[e]={type:"description",elementDescriptor:""}}}var Jh={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":return Xh(e.command),e;case"AI_ACTION":{let n=e.commands;for(let r of n??[])Xh(r);return e}default:return e}})};import{v4 as mA}from"uuid";var Qh={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=mA()),e;default:return e}})};import{v4 as Zh}from"uuid";var ef={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return n.id=n.id??Zh(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(n=>({type:"PRESET_ACTION",command:{...n,id:n.id??Zh()}})),delete e.commands),e;default:return e}})};var tf={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return typeof n.type!="string"||n.type!=="AI_WAIT"||(n.type="AI_ASSERTION",n.timeout||(n.timeout=10)),e}default:return e}})};import{v4 as pA}from"uuid";var nf={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>("id"in e&&typeof e.id=="string"||(e.id=pA()),e))};import{v4 as rf}from"uuid";var of={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let n=e.condition;n.id||(n.id=rf())}return e.id=rf(),e})};var af={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};import{v4 as gA}from"uuid";var sf={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=gA()),e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};var lf={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:n.option},e.option=void 0),e})};var cf={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return n&&df(n),e})};function df(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){df(t[e]);return}if(typeof t[e]!="string")return;let n=t[e];e==="code"?t[e]=n.replace(/inputs\./g,"env."):n.includes("{{")&&n.includes("}}")&&(t[e]=n.replace(/inputs\./g,"env."))})}var uf={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TAB"||n.url===void 0||(n.action={type:"SUBSTRING",substring:n.url},n.url=void 0),e})};var mf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TYPE"?e:n.pressKeysSequentially===void 0?(n.delay=0,e):(n.pressKeysSequentially&&(n.pressKeysSequentially=void 0,n.delay=50),e)})};var pf={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="WAIT_FOR_URL"||n.url===void 0||(n.matcher={type:"GLOB",glob:n.url},n.url=void 0),e})};var gf={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;if(!n)return e;if(n.type==="SELECT_OPTION"){if(n.option===void 0)return e;n.choice={type:"VALUE",value:n.option},n.option=void 0}else if(n.type==="TAB"){if(n.url===void 0)return e;n.action={type:"SUBSTRING",substring:n.url},n.url=void 0}else if(n.type==="WAIT_FOR_URL"){if(n.url===void 0)return e;n.matcher={type:"GLOB",glob:n.url},n.url=void 0}else n.type==="AI_WAIT"&&(n.type="AI_ASSERTION",n.timeout||(n.timeout=10));return e})};var hf={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="MOCK_ROUTE"&&n.type!=="SET_HEADER"&&n.type!=="RECORD_REQUESTS"&&n.type!=="REGISTER_REQUEST_LISTENER"||(n.type==="REGISTER_REQUEST_LISTENER"||n.type==="RECORD_REQUESTS"?n.requestMatcher={urlMatcher:{type:"REGEX",regex:n.pattern}}:(n.type==="SET_HEADER"||n.type==="MOCK_ROUTE")&&n.urlPattern&&(n.requestMatcher={urlMatcher:{type:"REGEX",regex:n.urlPattern}})),e})};var ff={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async t=>t.map(e=>{if(e.type!=="AI_ASSERTION")return e;let 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 Vs=new Set(["CLICK","TYPE","SELECT_OPTION"]),Sf={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type,o=n?.elementDescriptor;return(o!==void 0||Vs.has(r))&&(n.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i?.elementDescriptor,c=i?.type;(s!==void 0||Vs.has(c))&&(i.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,c=s?.elementDescriptor,l=s?.type;(c!==void 0||Vs.has(l))&&(s.target={elementDescriptor:c??""}),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(u=>{let m=u?.elementDescriptor,p=u?.type;(m!==void 0||Vs.has(p))&&(u.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var yf={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e;return n.status==="FAILURE"&&(n.status="FAILED"),typeof n.commands=="object"&&Array.isArray(n.commands)&&n.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),n}),stopOnFailure:!0};var bf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type;return r?.startsWith("PRESET_")&&(n.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let i=a.type;i?.startsWith("PRESET_")&&(a.type=i.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let i=a.command,s=i?.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7)),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(l=>{let d=l.type;d?.startsWith("PRESET_")&&(l.type=d.slice(7))})}),e}),stopOnFailure:!0};var Zr=[ff,yf,bf,Sf,Kh,Yh,Jh,Qh,ef,tf,nf,of,af,sf,lf,cf,uf,mf,pf,gf,hf];if(le!==Zr[Zr.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Zr.forEach((t,e)=>{if(!qs.valid(t.toVersion)||!qs.valid(t.fromVersion))throw new Error(`Migration '${t.name}' has invalid version`);if(!qs.gt(t.toVersion,t.fromVersion))throw new Error(`Migration '${t.name}' has toVersion <= fromVersion`);if(e===0)return;if(Zr[e-1].toVersion!==t.fromVersion)throw new Error(`Migration '${t.name}' at index ${e} is not contiguous with previous migration`)});function SA(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var oi=async({metadata:t,steps:e,logger:n,toVersion:r})=>{let o=e,{schemaVersion:a,id:i}=t,s=Zr.findIndex(d=>qs.gt(d.toVersion,a));if(s===-1)return{steps:o,newVersion:a};let c=a;for(let d=s;d<Zr.length;d++){if(r&&fA(c,r)){n.debug("Stopping migration early because toVersion was reached");break}let u=Zr[d],m={id:i,migration:u.name,toVersion:u.toVersion};try{o=await Tf(o,u),c=u.toVersion}catch(p){throw n.error({err:p,...m},"Migration failed"),new Error(`Step migration ${u.name} failed: ${p}`)}}let l=hA(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return l.trim()&&n.debug({diffs:l,id:i},"Migration diffs"),{newVersion:c,steps:o}};async function Tf(t,e){let n=await e.execute(t);for(let r of n)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let a=r[o];!a||!Array.isArray(a)||SA(a)&&(r[o]=await Tf(a,e))}return n}async function Ef({rawSteps:t,metadata:e,logger:n,callbacks:r}){qh(e,"defaultOnCloud");let o={},{resolvedSteps:a,newSchemaVersion:i}=await Ks({rawSteps:t.steps,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o}),s={...e,steps:a,schemaVersion:i};for(let c of["beforeSteps","afterSteps"]){let l=t[c];if(!l)continue;let{resolvedSteps:d}=await Ks({rawSteps:l,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o});s[c]=d}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function eo(t,e,n){let{newVersion:r,steps:o}=await oi({metadata:t,steps:e,logger:n});try{return{steps:Ie.array().parse(o),newVersion:r}}catch(a){throw n.error({type:"zod",err:a,newVersion:r,id:t.id,steps:o},"Failed to parse test steps while migrating test"),new Ss(`Failed to parse test steps while migrating test: ${a}`,t.id,"entity",{cause:a})}}async function Ks({rawSteps:t,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:a,steps:i}=await eo(e,t,n),s=[];for(let c of i)s.push(await ai({step:c,callbacks:r,logger:n,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:a}}async function ai({step:t,callbacks:e,logger:n,resolvedModuleCache:r}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let c=t.moduleId,l=r[c];if(l)return{...wf(l),...t,type:"RESOLVED_MODULE"};let d=await e.onFetchModule({id:c,logger:n});if(!d)throw new Error(`Could not find module with id ${c}`);let{newVersion:u,steps:m}=await oi({metadata:{id:c,schemaVersion:d.schemaVersion},steps:d.steps,logger:n}),p;try{p=Ie.array().parse(m)}catch(f){throw n.error({type:"zod",err:f,steps:m,newVersion:u,id:c},"Module failed to parse"),f}let g;try{g=await Promise.all(p.map(f=>ai({step:f,callbacks:e,logger:n,resolvedModuleCache:r})))}catch(f){throw n.error({err:f,...t},`Failed to recursively resolve module '${d.name}': ${f}`),f}let h={...d,steps:g};return r[c]=wf(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let c of t.blocks){let l=[];for(let d of c.steps)l.push(await ai({step:d,callbacks:e,logger:n,resolvedModuleCache:r}));o.push({...c,steps:l})}let a;if(t.elseSteps){a=[];for(let c of t.elseSteps)a.push(await ai({step:c,callbacks:e,logger:n,resolvedModuleCache:r}))}return{...t,blocks:o,elseSteps:a};case"SECTION":let i=[];for(let c of t.steps)i.push(await ai({step:c,callbacks:e,logger:n,resolvedModuleCache:r}));return{...t,steps:i};default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function yA(t){return typeof t=="object"&&t!==null}function jn(t){if(Array.isArray(t))return t.map(jn);if(yA(t)){let e={};return Object.entries(t).forEach(([n,r])=>{r!==void 0&&(e[n]=jn(r))}),e}return t}import{cloneDeep as bA}from"lodash-es";import{stringify as Rf}from"yaml";async function Cf({test:t,processedModuleNames:e=new Set,createNewCacheIds:n=!1}){let r={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},a=await TA({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:n}),i={fileType:ge.TEST,...r,beforeSteps:a.beforeSteps&&a.beforeSteps.length>0?a.beforeSteps:void 0,steps:a.steps,afterSteps:a.afterSteps&&a.afterSteps.length>0?a.afterSteps:void 0};return{test:Rf(i),modules:o}}async function TA({originalStepLists:t,modules:e,processedModuleNames:n,createNewCacheIds:r}){let o=bA(t);Object.values(o).forEach(s=>{wA(s??[])});let{stepsToSave:a,moduleUpdates:i}=await He({stepLists:o,createNewCacheIds:r});for(let s of i)n.has(s.name)||(e[s.name]=EA(s),n.add(s.name));return a}function wA(t){ri({steps:t,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function EA(t){let e=Ot.parse(t),n={fileType:ge.MODULE,...e,schemaVersion:le,steps:t.steps};return Rf(n)}async function J(t,e){if(!(t<=0))return new Promise((n,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",a);let o=setTimeout(()=>{e?.removeEventListener("abort",a),n()},t);function a(){clearTimeout(o),e?.removeEventListener("abort",a),r(e?.reason)}})}async function ii({promiseGenerator:t,signal:e,codePath:n,logger:r}){let a=Date.now(),i=setInterval(()=>{if(e?.aborted){clearInterval(i);return}r?.warn({codePath:n,startTime:a,elapsedMilliseconds:Date.now()-a},`Asynchronous operation is taking a long time (${n})`)},5e3);return new Promise((s,c)=>{function l(){clearInterval(i),e?.removeEventListener("abort",l),c(e?.reason)}if(e?.aborted){c(e?.reason),clearInterval(i);return}e?.addEventListener("abort",l),(async()=>{try{s(await t())}catch(d){c(d)}finally{clearInterval(i),e?.removeEventListener("abort",l)}})()})}async function to({promiseGenerator:t,timeoutMs:e,codePath:n,logger:r,signal:o}){let a=!1,i=new AbortController,s=()=>{i.abort()},c=setTimeout(()=>{a||i.abort()},e);o?.addEventListener("abort",s);try{return await ii({promiseGenerator:t,signal:i.signal,codePath:n,logger:r})}finally{a=!0,o?.removeEventListener("abort",s),clearTimeout(c)}}function vf(t){let e;return t>10*60*1e3?e=2*60*1e3:t>60*1e3?e=20*1e3:t>10*1e3?e=2*1e3:e=1e3,e}function Ys(t){let e=[];for(let n of t)switch(n.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(n);break;case"RESOLVED_MODULE":{let r={...n,type:"MODULE"};e.push(cn.parse(r));break}case"SECTION":{let r={...n,steps:Ys(n.steps)};e.push(Ie.parse(r));break}case"CONDITIONAL":{let r={...n,blocks:n.blocks.map(o=>({assertion:o.assertion,steps:Ys(o.steps)})),elseSteps:n.elseSteps?Ys(n.elseSteps):void 0};e.push(Br.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}function Xs(t){return Ys([t])[0]}import RA from"picomatch";var Js=(t,e,n)=>{n?.caseInsensitive&&(t=t.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=n?.caseInsensitive?e.url.toLowerCase():e.url;r=t.includes(o);break}case"GLOB":{let o=n?.caseInsensitive?e.glob.toLowerCase():e.glob;r=t===e.glob||RA(o)(t);break}case"REGEX":{r=new RegExp(e.regex).test(t);break}case"DOMAIN":{let o=n?.caseInsensitive?e.domain.toLowerCase():e.domain;r=new URL(t).hostname===o;break}}return n?.negated?!r:r},Qs=(t,e)=>{try{let{hostname:n,pathname:r}=new URL(t),{hostname:o,pathname:a}=new URL(e);return n!==o||r!==a}catch{return!1}},Zo=t=>{try{return new URL(t),!0}catch{return!1}},Af=t=>!t.toLowerCase().startsWith("http"),ea=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function no(t,e){try{return!!new URL(t).origin.trim()}catch(n){return e?.error({url:t,err:n},"Invalid URL in check"),!1}}async function CA(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:c}=t,l=[];if(o.length>0){let{results:u}=await Qo(e,n,o,{numStepsWithScreenshots:s,maxItemsFromEnd:i,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});l=u}return await r.getTestResultClassification({results:l,errorMessage:a.message,errorStack:a.stack},{disableCache:c??!1})}async function xf(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:c}=t;if(!n||!o||o.length===0)return{};try{let l=await CA({logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:c});return{classification:l,aiFailureReason:l.reason}}catch(l){return e.error({err:l},"Failed to classify test result"),{}}}function ta({orgId:t,client:e,gitMetadata:n,alwaysSaveCache:r,noCache:o}){return o?new As:new kd(t,e,n,r)}var kd=class{constructor(e,n,r,o){this.orgId=e;this.client=n;let{gitBranchName:a,gitProtectedBranches:i}=r;this.cacheHeaders=pd(r),o?this.writeCaches=!0:a?this.writeCaches=!i.includes(a):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:n,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:n},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:n,beforeSteps:r,afterSteps:o}=e.stepLists,a=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[n,r,o])s&&Jo({steps:s,stepCacheEntries:a,logger:e.logger});let{cachesToSave:i}=await He({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:i,testId:e.testId},this.cacheHeaders)}};import AA from"path";var xA=new Os(30,60*1e3),Ud="https://api.momentic.ai",If,Pf=t=>{Ud=t},si=()=>Ud;var na,Fd,Zs,Mf=async t=>{if(If&&na&&Zs)return na;let e=new Ze({baseUrl:Ud,apiKey:t,logger:S});If=e;try{let n=await e.getAuthInfo();return na=n.orgId,Fd=n.userId,Zs=t,na}catch(n){throw new Error(`Error checking API key against server: ${n}`)}},on=()=>{if(!na)throw new Error("Your organization ID is invalid.");return na},el=()=>{if(!Fd)throw new Error("Your user ID is invalid.");return Fd},Bd=()=>{if(!Zs)throw new Error("Your API key is invalid.");return Zs},zd,_d,tl=(t,e)=>{zd=t,_d?.abort(),_d=new AbortController;let n=_d.signal,r=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let a=AA.resolve(t.rootDir,o.envFile);try{if(Dd.lstatSync(a).isSymbolicLink())return;Dd.existsSync(a)&&r.push(a)}catch(i){S.warn({err:i},`Failed to check if env file ${a} exists`)}});try{IA({filesToWatch:r,revalidator:e,signal:n,project:t})}catch(o){S.error({err:o},"Failed to start config file watchers")}},ie=()=>zd;function IA({filesToWatch:t,revalidator:e,signal:n,project:r}){t.forEach(o=>{Dd.watch(o,{signal:n,persistent:!1,recursive:!1},(a,i)=>{i&&(xA.increment("setLocalProject")&&S.warn(`A file change under the ${r.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),zd=e(r.configFilePath))})})}function de(t){return function(...e){let n=e[e.length-1],r=t(...e);Promise.resolve(r).catch(n)}}var ci=PA();function li(t){let e=ie(),n=ct.dirname(e.configFilePath);return ct.join(n,...t)}function LA(t){let e=ie(),n=ct.dirname(e.configFilePath),r=ct.relative(n,t);return r?r.split(ct.sep):[]}function OA(t,e){let n=It.statSync(t),r=LA(t);return ad.parse({name:e,absolutePath:t,relativePath:r.join(ct.sep),pathSegments:r,isDirectory:n.isDirectory(),size:n.size,createdAt:n.birthtime,modifiedAt:n.mtime,accessedAt:n.atime})}ci.post("/",de(async(t,e,n)=>{let r;try{r=gg.parse(t.body).pathSegments}catch(u){e.status(400).json({error:`Failed to parse folder read body: ${u}`});return}let o=li(r);if(!It.existsSync(o)){e.status(404).json({error:`Path not found: ${r.join(ct.sep)}`});return}if(!It.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(ct.sep)}`});return}let i=ie(),s=Array.from(i.config.exclude??[]).concat(ws),l=MA("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(u=>{let m=ct.join(o,u);return OA(m,u)}),d={absolutePath:o,pathSegments:r,contents:l};e.status(200).json(d)}));ci.put("/",de(async(t,e,n)=>{let r;try{r=hg.parse(t.body).pathSegments}catch(i){e.status(400).json({error:`Failed to parse folder create body: ${i}`});return}let o=li(r);if(It.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${r.join(ct.sep)}`,pathSegments:r});return}It.mkdirSync(o,{recursive:!0});let a={success:!0,message:`Folder created: ${r.join(ct.sep)}`,pathSegments:r};e.status(201).json(a)}));ci.patch("/",de(async(t,e,n)=>{let r,o;try{let l=fg.parse(t.body);r=l.pathSegments,o=l.newPathSegments}catch(l){e.status(400).json({error:`Failed to parse folder update body: ${l}`});return}let a=li(r),i=li(o);if(!It.existsSync(a)){e.status(400).json({error:`Folder not found: ${r.join(ct.sep)}`});return}if(It.existsSync(i)){e.status(400).json({error:`Destination already exists: ${o.join(ct.sep)}`});return}let s=ct.dirname(i);It.existsSync(s)||It.mkdirSync(s,{recursive:!0}),It.renameSync(a,i);let c={success:!0,message:`Folder moved from ${r.join(ct.sep)} to ${o.join(ct.sep)}`,pathSegments:o};e.status(200).json(c)}));ci.delete("/",de(async(t,e,n)=>{let r,o=!0;try{let c=Sg.parse(t.body);r=c.pathSegments,o=c.recursive??!0}catch(c){e.status(400).json({error:`Failed to parse folder delete body: ${c}`});return}let a=li(r);if(!It.existsSync(a)){e.status(200).json({success:!0,message:`Folder not found: ${r.join(ct.sep)}`,pathSegments:r});return}if(!It.statSync(a).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(ct.sep)}`});return}if(o)It.rmSync(a,{recursive:!0,force:!0});else{if(It.readdirSync(a).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${r.join("/")}`});return}It.rmdirSync(a)}let s={success:!0,message:`Folder deleted: ${r.join("/")}`,pathSegments:r};e.status(200).json(s)}));var Hd=ci;import eO from"events";import Kb,{Router as tO}from"express";import{diff as DA}from"deep-object-diff";import mn from"fs";import oo from"path";import ra from"yaml";import{z as kf}from"zod";import{execSync as NA}from"child_process";function ro(t,e){let n=e.hooks?.postSave;if(!n)return;let r;n.includes("$1")?r=n.replaceAll("$1",t):r=`${n} ${t}`,S.debug({postSaveCommand:r},"Executing post-save hook command");try{NA(r,{encoding:"utf-8"})}catch(o){S.warn({err:o,postSaveCommand:r},"Failed to execute post-save hook command, continuing...")}}import{diff as Lf}from"deep-object-diff";import xn from"fs";import{cloneDeep as kA}from"lodash-es";import di from"path";import{v4 as _A}from"uuid";import ui from"yaml";function $t({content:t,schemaVersion:e,momenticFiles:n,project:r,forceSaveOnNoDiffs:o}){let a=n.modules[t.moduleId]?.fullFilePath;if(!a||!xn.existsSync(a))throw new Error(`Tried to update module ${t.moduleId} that could not be found on disk`);let i=xn.readFileSync(a,"utf-8"),s=ui.parse(i),c;if(t.name&&t.name!==s.name){let p=`${Ce(t.name)}.${lt.MODULE}`;if(c=di.join(di.dirname(a),p),xn.existsSync(c))throw new Error(`Module with name '${t.name}' already exists at path '${c}'`)}let l={...t,schemaVersion:e},d=jn({fileType:ge.MODULE,...ld.parse(l),steps:Ie.array().parse(t.steps)}),u=Lf(d,s);if(u&&Object.keys(u).length===0&&!o){S.debug(`Skipping save for module ${t.moduleId} since there are no changes`);return}let m=ui.stringify(d);xn.writeFileSync(a,m,"utf-8"),c&&xn.renameSync(a,c),ro(c||a,r.config)}function Of({moduleId:t,content:e,momenticFiles:n,project:r,logger:o}){let a=n.modules[t]?.fullFilePath;if(!a)throw new Error(`Tried to update module ${t} that could not be found on disk`);let i=Gn(a,o),s={...i,...e},c=jn({fileType:ge.MODULE,...ld.parse(s),steps:i.steps}),l=Lf(c,i);if(l&&Object.keys(l).length===0){S.debug(`Skipping save for module ${t} since there are no changes`);return}let d=ui.stringify(c);xn.writeFileSync(a,d,"utf-8");let u;if(e.name){let m=`${Ce(e.name)}.${lt.MODULE}`;if(u=di.join(di.dirname(a),m),xn.existsSync(u))throw new Error(`Module with name '${e.name}' already exists at path '${u}'`);xn.renameSync(a,u)}ro(u||a,r.config)}async function Nf({name:t,description:e,enabled:n,steps:r,folder:o,project:a}){let i=Ce(t),s=di.join(o,`${i}.module.yaml`),c=_A(),{stepsToSave:l}=await He({stepLists:{steps:r}}),d={fileType:ge.MODULE,schemaVersion:le,moduleId:c,name:t,description:e,enabled:n,steps:l.steps},u=ui.stringify(d);return xn.writeFileSync(s,u,"utf-8"),ro(s,a.config),{moduleId:c,name:t,description:e,enabled:n,steps:r}}function Gn(t,e){let n=xn.readFileSync(t,"utf-8"),r=ui.parse(n);try{return Jc.parse(r)}catch(o){throw e.error({err:o,moduleFilePath:t,moduleContents:n},`${t} does not parse as a valid Momentic module`),o}}async function nl(t,e,n,r){let o=Gn(t.fullFilePath,n),{resolvedSteps:a}=await Ks({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:r,logger:n,callbacks:{onFetchModule:async({id:s})=>{let c=e.modules[s]?.fullFilePath;if(c)return Gn(c,n)}}}),i={...o,steps:a};return r&&(r[t.id]=kA(i)),i}async function rl(t,e){let n={};return await Promise.all(Object.values(t.modules).map(async r=>{await nl(r,t,e,n)})),Array.from(Object.values(n))}async function _f({test:t,name:e,folder:n}){let r=await Cf({test:t});if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let a=`${Ce(e)}.${lt.TEST}`,i=oo.join(n,a);return mn.writeFileSync(i,r.test,"utf-8"),i}function $d(t,e,n){let r=oo.join(n.rootDir,t);if(!mn.existsSync(r))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let o=mn.readFileSync(r,"utf-8"),a=ra.parse(o),i,s;if(e.name&&e.name!==a.name){let m=`${Ce(e.name)}.${lt.TEST}`;if(i=oo.join(oo.dirname(t),m),s=oo.join(n.rootDir,i),mn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let c={...a,...e},l=tn.parse(c),d={fileType:ge.TEST,...tn.parse(l),beforeSteps:a.beforeSteps??void 0,steps:a.steps,afterSteps:a.afterSteps??void 0},u=ra.stringify(d);return mn.writeFileSync(r,u,"utf-8"),s&&mn.renameSync(r,s),ro(r,n.config),{newRelativeTestPath:i}}function Pt({relativeTestPath:t,steps:e,schemaVersion:n,project:r,forceSaveOnNoDiffs:o}){let a=oo.join(r.rootDir,t);if(!mn.existsSync(a))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let i=mn.readFileSync(a,"utf-8"),s=ra.parse(i),c=tn.parse({...s,schemaVersion:n}),l=Ie.array().or(kf.undefined()).parse(e.beforeSteps),d=Ie.array().parse(e.steps),u=Ie.array().or(kf.undefined()).parse(e.afterSteps),m=jn({fileType:ge.TEST,...c,beforeSteps:l&&l.length>0?l:void 0,steps:d,afterSteps:u&&u.length>0?u:void 0}),p=DA(m,s);if(p&&Object.keys(p).length===0&&!o){S.debug(`Skipping save for test ${c.name} since there are no changes`);return}let g=ra.stringify(m);mn.writeFileSync(a,g,"utf-8"),S.debug(`Saving test ${c.name} to ${a}`),ro(a,r.config)}function ol(t,e){let n=oo.join(e.rootDir,t);if(!n)throw new Error(`Could not find test with path ${t} in Momentic project (${e.rootDir})`);let r;try{r=mn.readFileSync(n,"utf8"),r=r.replace(/\r\n|\r/g,`
27
+ `)}catch(a){throw new Error(`Could not read test file ${n}: ${a}`)}let o;try{o=ra.parse(r)}catch(a){throw new Error(`Could not parse test file ${n} as YAML: ${a}`)}return yt.parse(o)}function ao(t,e,n){let r=n.project.rootDir,o;try{o=mn.readFileSync(t,"utf-8")}catch(i){throw e.error({err:i,projectRoot:r},i.message),new Error(i.message)}let a=ra.parse(o);if(!a.steps||!Array.isArray(a.steps))throw new Error(`Test ${t} is missing steps`);return a}async function Mt(t,e,n){let r=ao(t,e,n),o;try{o=tn.parse(r)}catch(i){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${i}`)}let{resolvedTest:a}=await Ef({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:i,logger:s})=>{let c=n.modules[i]?.fullFilePath;if(c)return Gn(c,s)}}});return a}import FA from"@dotenvx/dotenvx";import UA from"fs";import Df from"path";function Ff(t,e){return(t.config.environments??[]).map(n=>mi(n.name,t,e))}function Uf(t){return t.includes("${")?t.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,o]=n.split(/:-|-/,2),a=process.env[r];return n.includes(":-")?a&&a!==""?a:o||"":n.includes("-")?a!==void 0?a:o||"":a||""}):t}function BA(t){let{envVariables:e,project:n}=t;if(!e)return{};let r={};for(let[o,a]of Object.entries(e)){if(typeof a=="string"){let s=Uf(a);s&&(r[o]=s);continue}let i;try{i=UA.readFileSync(Df.resolve(n.rootDir,a.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${a.fromFile}': ${s}`)}if(a.json)try{r[o]=JSON.parse(i)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${a.fromFile}' as JSON: ${s}`)}else r[o]=i}return Object.keys(r).length>0&&S.debug(r,"Set environment variables with interpolation from project configuration"),r}function zA(t){let{project:e,envFile:n,logger:r}=t,o={};if(!n)return o;let a=FA.config({path:Df.resolve(e.rootDir,n),processEnv:o,logLevel:"error",quiet:!0});if(a.error)throw new Error(`Failed to load .env file: ${a.error.message}`);return r.debug(o,"Set environment variables from .env file"),o}function mi(t,e,n){let r=(e.config.environments??[]).find(c=>c.name===t);if(!r)throw new Error(`Environment ${t} not found in local project configuration file`);if(!r.baseUrl)throw new Error(`Browser environment ${t} does not have a baseUrl configured`);let o={[it]:Uf(r.baseUrl)},a=BA({envVariables:r.envVariables,project:e});Object.assign(o,a);let i=zA({project:e,envFile:r.envFile,logger:n});return Object.assign(o,i),r.inheritFromShell&&(n.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:t,variables:o,browser:r.browser}}import{existsSync as QA,readFileSync as ZA,readdirSync as ex,writeFileSync as tx}from"fs";import{globSync as nx}from"glob";import io,{dirname as $f}from"path";import{cwd as qd}from"process";import jf from"yaml";import{z as Ne}from"zod";import Bf from"fs";import{globSync as HA}from"glob";import pi from"path";import $A from"yaml";import{z as jd}from"zod";var zf=!1,Gd=[`**/*.${lt.TEST}`,`**/*.${lt.MODULE}`],Wd=jd.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),Vd=50,jA=jd.object({fileType:jd.nativeEnum(ge)});function ne(t,e){let n={project:t,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},r=t.config.include??Gd,o=Array.from(t.config.exclude??[]).concat(ws),a=HA(r,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:Vd,nodir:!0});for(let i of a){let s=GA(t.rootDir,i,n,e);s&&(n.duplicateEntities[s.id]=s.paths)}return zf=!0,n}function GA(t,e,n,r){let o=pi.join(t,e),a=WA(o,r);if(!a)return;let i=VA(a,o,r);if(!i)return;let s=jA.safeParse(i);if(s.success===!1){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let c=s.data.fileType,l=qA(o,r);if(!l)return;let d=KA(e,o,l);switch(c){case ge.TEST:try{return YA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${u}`);return}case ge.MODULE:try{return XA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${u}`);return}case ge.MOBILE_TEST:try{return JA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${u}`);return}default:{let u=c;return}}}function WA(t,e){try{return Bf.readFileSync(t,"utf-8")}catch(n){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${n}`);return}}function VA(t,e,n){try{let r=$A.parse(t);if(typeof r!="object"||r===null)throw new Error("The YAML document should parse as a map with key-value pairs");return r}catch(r){n.warn(`Could not parse possible Momentic file at ${e}, skipping: ${r}`);return}}function qA(t,e){try{return Bf.statSync(t)}catch(n){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${n}`);return}}function KA(t,e,n){return{relativePath:t,fullFilePath:e,platformSep:pi.sep,fullPathSegments:e.split(pi.sep),relativePathSegments:t.split(pi.sep),fileName:pi.basename(e),lastModified:n.mtime,createdAt:n.birthtime}}function YA(t,e,n,r,o){let a=tn.parse(t),i;if(e.tests[a.id]){let s=e.tests[a.id].fullFilePath;i={id:a.id,paths:[s,r]}}return e.tests[a.id]={type:ge.TEST,name:a.name,id:a.id,description:a.description??void 0,labels:a.labels,...n},i}function XA(t,e,n,r,o){let a=Ot.parse(t),i;if(e.modules[a.moduleId]){let c=e.modules[a.moduleId].fullFilePath;i={id:a.moduleId,paths:[c,r]}}e.modules[a.moduleId]={type:ge.MODULE,name:a.name,id:a.moduleId,description:a.description??void 0,...n};let s=n.fileName.replace(`.${lt.MODULE}`,"");return!zf&&Ce(a.name)!==s&&o.warn(`The module with ID ${a.moduleId} has a name (${a.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),i}function JA(t,e,n,r,o){let a=Zc.parse(t),i;if(e.mobileTests[a.id]){let c=e.mobileTests[a.id].fullFilePath;i={id:a.id,paths:[c,r]}}let s=n.fileName.replace(`.${lt.TEST}`,"");return e.mobileTests[a.id]={type:ge.MOBILE_TEST,name:s,id:a.id,description:a.description??void 0,...n},i}var oa="momentic.config.yaml",Hf="momentic.workspace.yaml",rx=Ne.object({projects:Ne.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),ox=Ne.union([Ne.string(),Ne.object({fromFile:Ne.string(),json:Ne.boolean().optional()})]),ax=Ne.object({name:Wd,baseUrl:Ne.string().optional().describe("Optional for mobile tests"),envFile:Ne.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ne.record(Ne.string(),ox).optional(),inheritFromShell:Ne.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:$r.optional().describe("deprecated: use project-level configuration only")}),ix=Ne.object({postSave:Ne.string().optional()}),sx=Ne.object({name:Wd,include:Ne.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ne.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ne.string().optional(),reporterDir:Ne.string().optional(),outputDir:Ne.string().optional(),retries:Ne.number().optional().describe("number of retries per test"),parallel:Ne.number().optional().describe("degree of parallelism"),environments:Ne.array(ax).optional(),gitMainBranch:Ne.string().optional(),gitProtectedBranches:Ne.string().array().optional(),ai:cd.optional(),browser:$r.optional(),emulator:Qc.optional(),advanced:dd.optional(),hooks:ix.optional()});function Gf(t,e){let n;try{n=ZA(t,"utf-8")}catch(o){S.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let r;try{if(r=jf.parse(n),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){S.warn(`Possible Momentic ${e} file at ${t} does not parse as valid YAML: ${o}`);return}return r}function Kd(t){let e=Gf(t,"project configuration");if(e!==void 0)try{return sx.parse(e)}catch(n){S.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function lx(t){let e=Gf(t,"workspace configuration");if(e!==void 0)try{return rx.parse(e)}catch(n){S.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function cx(){let t=[],e=qd(),n=io.parse(e).root,r=15,o=0;for(;o<r;){o++;let a=io.basename(e);if(Ts.includes(a))return S.warn(`Stopping search for Momentic projects since the current directory name (${a}) is likely a system artifact folder.`),t;for(let i of ex(e))if(i.endsWith(oa)){let s=io.join(e,i),c=Kd(s);c&&t.push({configFilePath:s,config:c,rootDir:$f(s)})}if(t.length)return t;if(e=io.dirname(e),e===n)break}return t}function dt(t={}){let{configFilePath:e,nameFilter:n}=t,r=Yd(e);if(n&&(r=r.filter(o=>o.config.name===n)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
28
+ ${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return S.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function dx(t){let e=lx(t);if(!e||!e.projects||!e.projects.length)return;let n=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${oa}`)),r=nx(n,{absolute:!1,cwd:qd(),dotRelative:!1,maxDepth:Vd,nodir:!0}),o=[];for(let a of r){let i=io.join(qd(),a),s=Kd(i);s&&o.push({configFilePath:i,config:s,rootDir:$f(i)})}return o}function Yd(t){if(t){t=io.resolve(t);let n=Kd(t);return n||(console.error(`No valid Momentic project file found at ${t}.`),process.exit(1)),[{config:n,configFilePath:t,rootDir:io.dirname(t)}]}if(QA(Hf)){let n=dx(Hf);if(n)return n}return cx()}function aa(t,e){let n=jf.stringify(t);tx(e,n)}import ia from"fs";import Xd from"path";import{z as Jd}from"zod";var Wf="golden/visual-diff",Vf="reports",qf="test-results";var ux=Jd.object({width:Jd.number(),height:Jd.number()}),sa=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,n){let r=Xd.join(e.rootDir,e.config.goldenFileDir??Wf);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=n}async prepareGoldenScreenshotForComparison(e,n,r){if(n.screenshot?.data?.startsWith("https://")){let i=await fetch(n.screenshot.data);return{buffer:Buffer.from(await i.arrayBuffer()),width:n.screenshot.width,height:n.screenshot.height}}let o=n.screenshot?.data;o||(o=Xd.join(this.defaultGoldenScreenshotDir,`${n.id}.jpg`));let a=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ia.mkdirSync(Xd.dirname(o),{recursive:!0}),ia.writeFileSync(o,r.buffer),ia.writeFileSync(a,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(ia.existsSync(o)){let i=ia.readFileSync(o),s=ux.parse(JSON.parse(ia.readFileSync(a,"utf-8")));return{buffer:i,width:s.width,height:s.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var hr=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 mx}from"node:child_process";import{promisify as px}from"node:util";import gx from"simple-git";var ve=gx(),Kf=px(mx);async function hx(t){let e=await Ae(t,ve.raw(["config","--list"])),n={};if(!e)return n;for(let r of e.split(`
29
+ `)){let o=r.indexOf("=");if(o===-1)continue;let a=r.slice(0,o),i=r.slice(o+1).trim();n[a]=i}return n}async function fx(t,e,n){try{let o=n["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("@"),a=e.indexOf(":",o+1);o!==-1&&a!==-1&&(r=e.slice(o+1,a))}}catch{}if(r=r?.toLowerCase(),!!r){try{if(e?.startsWith("git@")&&r?.includes("github")){let{stdout:o,stderr:a}=await Kf("ssh",["-T","-o","BatchMode=yes",`git@${r}`],{timeout:5e3}),s=`${o??""}${a??""}`.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:a}=await Kf("gh",o,{timeout:5e3}),i=a?.toString().trim();if(i)return i}catch{}}}async function Sx(t,e,n){let r=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(r)return fx(t,e,n);if(o)return}catch{}}function al(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let n=e[1].replace(".git","").split("/");if(n.length===2){let r=n[0],o=n[1];return`${r}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let n=new URL(t).pathname.split("/").filter(Boolean);if(n.length>=2){let r=n[0],o=n[1].replace(".git","");return`${r}/${o}`}}}async function Ae(t,e){try{return(await e).trim()}catch(n){t.error({err:n},"Failed to run git command");return}}function yx(){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 bx(t){let[e,n,r,o]=await Promise.all([Ae(t,ve.show(["--no-patch","--format=%ci"])),Ae(t,ve.listRemote(["--get-url","origin"])),Ae(t,ve.show(["-s","--pretty=%B"])),Ae(t,ve.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:n,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function Tx(t){let[e,n,r]=await Promise.all([Ae(t,ve.listRemote(["--get-url","origin"])),Ae(t,ve.show(["-s","--pretty=%B"])),Ae(t,ve.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:n,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function wx(t){let[e,n,r,o]=await Promise.all([Ae(t,ve.show(["--no-patch","--format=%ci"])),Ae(t,ve.listRemote(["--get-url","origin"])),Ae(t,ve.show(["-s","--pretty=%B"])),Ae(t,ve.show(["-s","--pretty=%an"]))]),a=n?.includes("github.com"),i=n?.includes("gitlab.com"),s=n?al(n):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:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function Ex(t){let[e,n,r]=await Promise.all([Ae(t,ve.show(["--no-patch","--format=%ci"])),Ae(t,ve.show(["-s","--pretty=%B"])),Ae(t,ve.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,a=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?al(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:n,gitCommitAuthorName:r,githubRepository:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function Rx(t){let[e,n,r]=await Promise.all([Ae(t,ve.show(["--no-patch","--format=%ci"])),Ae(t,ve.show(["-s","--pretty=%B"])),Ae(t,ve.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],a=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?al(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:n,gitCommitAuthorName:r,githubRepository:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function Cx(t,e){let[n,r,o,a,i,s,c,l,d]=await Promise.all([Ae(t,ve.revparse(["HEAD"])),Ae(t,ve.revparse(["--short","HEAD"])),Ae(t,ve.revparse(["--abbrev-ref","HEAD"])),Ae(t,ve.listRemote(["--get-url","origin"])),Ae(t,ve.show(["--no-patch","--format=%ci"])),Ae(t,ve.show(["-s","--pretty=%B"])),Ae(t,ve.show(["-s","--pretty=%an"])),e?Ae(t,ve.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),hx(t)]),u=l?await Ae(t,ve.show(["--no-patch","--format=%ci",l])):void 0,m=a?.includes("github.com"),p=a?.includes("gitlab.com"),g=a?al(a):void 0,h=d["user.email"]||void 0,f=d["user.name"]||void 0,b=d["user.username"]||void 0,y=await Sx(t,a,d)??b??void 0;return t.debug({userUsername:y,gitLocalUserLogin:b,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:n,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:a,gitCommitTimestamp:i?new Date(i):void 0,gitCommitMessage:s,gitCommitAuthorName:c,gitLocalUsername:y,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:l,lastCommitOnMainTimestamp:u?new Date(u):void 0,githubRepository:m?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function vx(){let t=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:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function Ax(t){let e=t.config.gitProtectedBranches??[];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function Qd(t,e){let n=yx();if(!n)return Cx(t,e);switch(n){case"GithubActions":return bx(t);case"GitlabCI":return Tx(t);case"CircleCI":return wx(t);case"Buildkite":return Ex(t);case"AzureDevOps":return Rx(t);case"GCPCloudBuild":return vx()}}async function xx(t,e,n,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGitlab(n,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let a=await e.getCommitFromGitlab(n,r.gitCommitSha);a&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??a.author.name,gitCommitMessage:o.gitCommitMessage??a.message})}return o}async function Ix(t,e,n,r,o){let a=o;if(!o.gitCommitSha)return a;if(o.gitMainBranch&&(!a.lastCommitOnMainSha||!a.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGithub(n,r,o.gitMainBranch,o.gitCommitSha);a={...a,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!a.gitCommitTimestamp||!a.gitCommitAuthorName||!a.gitCommitMessage||!a.gitCommitAuthorName){let i=await e.getCommitFromGithub(n,r,o.gitCommitSha);i&&(a={...a,gitCommitTimestamp:a.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:a.gitCommitAuthorName??i.author.name,gitCommitMessage:a.gitCommitMessage??i.message})}return a}async function Px(t,e,n){try{if(n.githubRepository){let[r,o]=n.githubRepository.split("/");return await Ix(t,e,r,o,n)}else if(n.gitlabProjectPath)return await xx(t,e,n.gitlabProjectPath,n)}catch(r){t.warn({err:r},"Failed to get remote git metadata")}return n}async function fr(t,e,n){let r=await Ax(n),o=await Qd(t,r.gitMainBranch),a={...r,...o};(!a.lastCommitOnMainSha||!a.lastCommitOnMainTimestamp)&&a.gitBranchName===r.gitMainBranch&&(a.lastCommitOnMainSha=a.gitCommitSha,a.lastCommitOnMainTimestamp=a.gitCommitTimestamp);let i=await Px(t,e,a);return{...r,...o,...i}}import VJ from"yaml";import{randomUUID as Mx}from"crypto";import Wn from"fs";import so from"path";var Yf={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let n=new Set([...t.labels??[],...e.labels??[]]);return Array.from(n)}};function Lx(t,e,n){if(Yf[n]){let a=Yf[n];return a(t,e)}let r=t[n],o=e[n];if(r!==o)throw new Error(`Metadata values for key "${n}" do not match: "${r}" vs "${o}"`);return r}var Xf=new Set([".DS_Store","__MACOSX"]);function Jf(t,e,n){let r=Mx(),o=t.child({runGroupId:r});Wn.rmSync(e,{recursive:!0,force:!0});let a=Wn.readdirSync(n).filter(l=>!Xf.has(l)).map(l=>so.join(n,l));if(a.length===0)throw new Error(`No run groups found in results path: ${n}`);Wn.mkdirSync(e,{recursive:!0});let i=so.join(a[0],"metadata.json"),s={...Ja.parse(JSON.parse(Wn.readFileSync(i,"utf-8"))),id:r};for(let l of a){let d=so.join(l,"runs");if(!Wn.existsSync(d))continue;let u=Wn.readdirSync(d);for(let g of u){if(Xf.has(g))continue;let h=so.join(d,g),f=so.join(e,"runs",g);Wn.cpSync(h,f,{recursive:!0})}let m=so.join(l,"metadata.json"),p=Ja.parse(JSON.parse(Wn.readFileSync(m,"utf-8")));o.info({oldRunGroupId:p.id},"Merging metadata from run groups");for(let g in p){if(g==="id")continue;let h=g;s[h]=Lx(s,p,h)}}let c=so.join(e,"metadata.json");Wn.writeFileSync(c,JSON.stringify(s,null,2))}import Qf from"adm-zip";import Zd from"fs";import il from"path";function Ox(t){let e=new Qf,n=il.join(t,"metadata.json"),r=Ja.parse(JSON.parse(Zd.readFileSync(n,"utf-8")));e.addLocalFile(n);for(let o of Zd.readdirSync(il.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let a=o.replace(/\.zip$/,""),i=new Qf(il.join(t,"runs",o));for(let s of i.getEntries())s.isDirectory||e.addFile(il.join("runs",a,s.entryName),s.getData())}return{runGroupId:r.id,buffer:e.toBuffer()}}async function sl(t){let{client:e,consoleLogger:n,resultsPath:r}=t;if(!Zd.existsSync(r)){n.warn("Results path does not exist, skipping upload.");return}let o=new ks(e);try{let{runGroupId:a,buffer:i}=Ox(r),s=await o.uploadResultsArchive(a,i),c=`${e.getAppUrl()}/run-groups/${s}`;n.success(`Successfully uploaded test results. Once processed, your results can be found at ${c}`);return}catch(a){let i;a instanceof Error?i=a.message:typeof a=="string"?i=a:i="Unknown error",n.error(`Failed to upload test results: ${i}.`);return}}import Nx from"adm-zip";import Lt from"fs";import pn from"path";var gi=class t{constructor(e){this.filePath=e;Lt.rmSync(this.filePath,{recursive:!0,force:!0}),Lt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new t(pn.join(this.filePath,e))}mkdir(e){Lt.mkdirSync(pn.join(this.filePath,e),{recursive:!0})}readFile(e){let n=pn.join(this.filePath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}storeFile(e){let{name:n,contents:r}=e,o=pn.join(this.filePath,n);try{Lt.writeFileSync(o,r)}catch{}}createRunArchive(e){return new eu(pn.join(this.filePath,"runs"),e)}},eu=class{constructor(e,n){this.filePath=e;this.tempPath=pn.join(e,`.${n}`),this.finalPath=pn.join(e,`${n}.zip`),Lt.rmSync(this.tempPath,{recursive:!0,force:!0}),Lt.rmSync(this.finalPath,{recursive:!0,force:!0}),Lt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let n=pn.join(this.tempPath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}mkdir(e){Lt.mkdirSync(pn.join(this.tempPath,e),{recursive:!0})}cd(e){return new gi(pn.join(this.tempPath,e))}storeFile(e){let{name:n,contents:r}=e,o=pn.join(this.tempPath,n);Lt.writeFileSync(o,r)}close(){let e=new Nx;e.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store");let n=e.toBuffer();Lt.writeFileSync(this.finalPath,n),Lt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import nO from"http";import rO from"path";import{Server as dL}from"socket.io";var kx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{e.info({sessionId:r},"Cancel event received");let o=n.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},Zf={event:"cancel",createHandler:kx};var _x=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,a)=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let l=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:l},"Fetched a11y tree from the browser"),a({a11yTree:l})}catch(c){e.error({err:c},"Error fetching a11y tree from the browser"),a({err:c.message})}}},eS={event:"fetchA11yTree",createHandler:_x};var Dx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,a)=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let c=await s.html();a({html:c})}catch(c){e.error({err:c},"Error fetching DOM from the browser"),c.name==="TimeoutError"?a({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):a({err:c.message})}}},tS={event:"fetchDom",createHandler:Dx};var Fx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),n.removeSession(r,e)}},nS={event:"disconnect",createHandler:Fx};function In(t){let{result:e,nestedResults:n}=t;if(!t.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=Ux(n);Bx(e,r,o);let a=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await zx(a,e,r,o)}catch(i){t.logger.error({result:t.result,err:i},"Error hoisting scalar result metadata")}})())}function Ux(t){let e=t[0],n;for(;;){switch(e.type){case"PRESET_ACTION":{n=e;break}case"CONDITIONAL":if(e.assertionResult){n=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){n=e;break}e=e.results[e.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(n)break}let r=t[t.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(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:n,lastMetadata:o}}function Bx(t,e,n){e&&(t.beforeUrl=e.beforeUrl),n&&(t.afterUrl=n.afterUrl,t.data=n.data,n.status!=="SUCCESS"&&(t.message=n.message))}async function zx(t,e,n,r){await Promise.allSettled(t),n&&(e.beforeSnapshot=n.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import hi from"os";import Hx from"v8";var rS,Pn,$x=hi.platform(),jx=hi.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{});function oS(t){let e=()=>{try{let n=!1,r=Gx(),o=Wx();r.freeMemory<1e6&&(n=!0);let a=Hx.getHeapStatistics(),i=a.used_heap_size,s=a.heap_size_limit;i/s>.9&&(n=!0),n?t.warn({memory:r,cpu:o,heapStats:a},"Critical resource usage metrics detected"):t.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:jx,platform:$x}}function Gx(){let t=hi.totalmem(),e=hi.freemem(),n=t-e;return{totalMemory:t,freeMemory:e,usedMemory:n}}function Wx(){let t=hi.cpus(),e=Date.now(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;if(n.total=n.user+n.nice+n.sys+n.idle+n.irq,!Pn)return Pn=n,null;let r={user:n.user-Pn.user,nice:n.nice-Pn.nice,sys:n.sys-Pn.sys,idle:n.idle-Pn.idle,irq:n.irq-Pn.irq,total:n.total-Pn.total};return rS={measurementTime:e,intervalMs:e-Pn.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},Pn=n,rS}import{randomUUID as nI}from"crypto";import{faker as Vx}from"@faker-js/faker";import qx from"assert";import Kx from"axios";import*as Yx from"child_process";import Xx from"moment";import*as Jx from"otpauth";import Qx from"pg";async function aS(t){let e;try{e=new URL(t.url).hostname}catch{}let n=[];return t.headers.getSetCookie()?.forEach(r=>{let o=ds(r,e);n.push(...o)}),n}function Zx(t,e){if(!t&&!e)return;let n;if(t){let{url:o,options:a}=t;n=new Request(o,a)}let r;if(e){let{body:o,options:a}=e;r=new Response(o??null,a)}return{request:n,response:r}}async function eI(t,e){switch(t){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let n=[];return e.headers.forEach((o,a)=>{n.push([a,o])}),{status:e.status,headers:n,body:await e.text()}}else throw new Error("Result is not a Response object")}}var tI=Object.getPrototypeOf(async function(){}).constructor;async function iS(t,e,n){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o,additionalBindings:a,request:i,response:s}=e.bindings,c=e.tools,l={},d=(E,v)=>{o[E]=v,l[E]=v},u={},m=(E,v)=>{o[E]=v,u[E]=v},p;r.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let g;r.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new tI("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(a??{}),r)(Kx,Xx,c.fakerInstance??Vx,qx,Qx,p,g,Jx,Yx,aS,o,e.options.disallowVariableUpdates?void 0:d,e.options.disallowVariableUpdates?void 0:m,v=>c.sms.send(v),v=>c.sms.fetchLatest(v),c.email,c.sms,c.ai,Zx(i,s),...Object.values(a??{}))),f=!0,b,y;try{let E=await j(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});b=await eI(e.options.responseSerialization??"RAW",E)}catch(E){n.error({err:E,env:o,evalCode:r},`[${t}] Error executing code: ${E}`),f=!1,E instanceof mr?y=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:y=E instanceof Error?E.message:`${E}`}return{result:b,variableUpdates:l,persistentVariableUpdates:u,success:f,error:y}}async function sS({code:t,fragment:e,context:n,localTools:r,logger:o,signal:a,timeoutMs:i=lr,disallowVariableUpdates:s,additionalBindings:c,responseSerialization:l,mock:d}){let u=nI(),m=await iS(u,{code:t,options:{fragment:e,timeoutMs:i,disallowVariableUpdates:s,responseSerialization:l},bindings:{...n.toObjectCopy(),...d,additionalBindings:c},tools:r,signal:a},o);return S.debug(`[${u}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as rI,randomUUID as oI}from"crypto";import aI from"fetch-retry";var iI=aI(global.fetch,{retries:3,retryOn:function(t,e,n){return!!(e!==null||n&&n.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),lS=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,cS=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function dS({orgId:t,code:e,fragment:n,context:r,timeoutMs:o=lr,retries:a=2,signal:i,logger:s,additionalBindings:c,disallowVariableUpdates:l,responseSerialization:d,mock:u}){if(!lS)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,p,g=0;if(!cS)throw new Error("Missing lambda auth secret.");let h=rI("sha256",cS).update(t).digest("hex");for(;g<=a;){g++,i?.throwIfAborted();let b={id:oI(),orgId:t,momenticLambdaAuthHash:h,code:e,fragment:n,state:{...r.toObjectCopy(),...u,additionalBindings:c},timeoutMs:o,disallowVariableUpdates:l,responseSerialization:d};try{if(m=await j(iI(lS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:i}),!m)throw new Error("Got empty response from code evaluation server");if(!m.ok)throw new Error(`Code evaluation server returned error code ${m.status}`);p=void 0;break}catch(y){p=y}}if(p)throw s.error({err:p},"Failed to evaluate code remotely"),p;if(!m)throw new Error(`An unexpected code evaluation error occurred${p?`: ${p}`:""}`);let f;try{f=Gp.parse(await m.json())}catch(b){throw new Error(`Code evaluation server returned invalid response: ${b}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function Sr(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await dS(t);else if(t.localTools)e=await sS({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let n=`Failed to evaluate code:
30
30
  ${e.error}
31
31
  Code received:
32
- ${t.code}`;throw t.logger.error({err:e.error,code:t.code,env:t.context.toObjectCopy()},n),new Error(n)}if(e.variableUpdates)for(let[n,r]of Object.entries(e.variableUpdates))t.context.setVariable(n,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await t.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[n,r]of Object.entries(e.persistentVariableUpdates))t.context.setVariable(n,r)}return e.result}import{set as oI}from"lodash-es";async function jt(t){let{orgId:e,s:n,context:r,logger:o,signal:a,retries:i=2,timeoutMs:s=cr,allowUndefined:l=!1}=t,c=/{{(.*?)}}/g,d=n.matchAll(c),u=n;for(let m of d){if(m.length<2)continue;let p=m[1].trim(),g;try{g=await yr({orgId:e,code:p,fragment:!0,context:r,timeoutMs:s,logger:o,retries:i,localTools:t.localTools,signal:a})}catch(f){throw o.error({err:f,value:n},"Error evaluating template string"),f}if(g===void 0&&!l)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 h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],h)}return u}async function ll(t){return mS(t)}async function mS({obj:t,bannedKeys:e,allowList:n,context:r,prefixPath:o=[],replacements:a=[],...i}){for(let s in t){if(e.includes(s))continue;let l=!1;if(n)if(n.includes(s))l=!0;else continue;let c=t[s],d=[...o,s];if(typeof c=="string"&&c.includes("{{")){let u=await jt({s:c,context:r,...i});if(c===u)continue;a.push({path:d,original:c}),t[s]=u}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await mS({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:a,allowList:l?void 0:n,...i})}return a}function pS(t,e){for(let{path:n,original:r}of e)oI(t,n,r)}import aI from"fetch-retry";var L6=process.env.MAILINATOR_API_KEY,O6=aI(global.fetch,{retryOn:function(t,e,n){return t>3?!1:!!(e!==null||n&&n.status>=400)},retryDelay:function(t){return 500}});import{hostname as mI}from"os";async function gS(t){let{command:e,tracer:n,timeoutMs:r,targetingWrapper:o,disableCache:a,fixtures:i}=t,{logger:s,abortSignal:l}=i;if(e.target&&!rr(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=sI(e.assertion),d=xm(e.cache)?e.cache:void 0,u=Date.now(),m=0,p,g=500;for(;m<2||Date.now()-u<r;){m++,m>1&&await J(g,l),l?.throwIfAborted();try{let{elementInteractedDisplayString:h,result:f}=await o({ctx:i.ctx,tracer:n,command:e,target:e.target,cache:d?.target,action:async y=>iI(y.locator,t),options:{...e,disableCache:a,disableGlobalLocatorRedirect:!0,source:Hr(e),allowZeroOpacityOverride:!0,targetName:"target"}});if(p={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:h},!f.success){p=f,g=Math.min(g*2,1e4);continue}return p}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(s.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof A)||h.reason!="ActionFailureError")throw h;p={success:!1,err:h}}}if(!p)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return p}async function iI(t,{command:e,fixtures:n}){let r=e.assertion;await n.browser.highlight(t);let o=!0,a,i;switch(r.type){case"ELEMENT_CONTENT":{let l=await t.textContent()??"";if(i={elementTextContent:$e(l,500,!0)},!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,a=new A("AssertionFailureError",`The content ${c} '${r.value}': ${l}`)}break}case"ELEMENT_ATTRIBUTE":{i={elementOuterHtml:$e(await t.evaluate(c=>c.cloneNode(!1).outerHTML),500,!0)};let l;try{l=await t.getAttribute(r.attr,{timeout:3e3})??""}catch(c){a=new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${c}`),o=!1;break}if(!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,r.operation==="EXISTS"?a=new A("AssertionFailureError",`The attribute ${r.attr} ${c}`):a=new A("AssertionFailureError",`The attribute ${r.attr} ${c} '${r.value}': ${l}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await t.evaluate(async(c,d)=>{let u=Date.now();for(;Date.now()-u<d;){await new Promise(p=>setTimeout(p,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},Tn*1e3);break}case"EDITABLE":{o=await t.isEditable({timeout:Tn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await t.isEnabled({timeout:Tn*1e3});break}case"FOCUSED":{o=await t.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?Ld[r.condition]:Od[r.condition];a=new A("AssertionFailureError",`The element ${l}`)}break}case"ELEMENT_NAME":{let l=await t.evaluate(c=>c.tagName);if(!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,a=new A("AssertionFailureError",`The element tag name ${c} '${r.value}': ${l}`)}break}case"ELEMENT_STYLE":{let l=await t.evaluate((c,d)=>window.getComputedStyle(c).getPropertyValue(d),r.property);if(!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,r.operation==="EXISTS"?a=new A("AssertionFailureError",`The style property ${r.property} ${c}`):a=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:i,err:a}}function cl(t,e,n,r){let o;switch(n){case"CONTAINS":{o=t.includes(e);break}case"EQUALS":{o=t.trim()===e.trim();break}case"STARTS_WITH":{o=t.trim().startsWith(e);break}case"EXISTS":{o=t.trim().length>0;break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return r?!o:o}function sI(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function hS(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as lI}from"jimp";async function hi(t,e){let n=await t.screenshot(e),r=await lI.fromBuffer(n);return{buffer:n,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as fS}from"jimp";import ru from"jpeg-js";import cI from"pixelmatch";async function SS({ctx:t,tracer:e,command:n,disableCache:r,browser:o,targetingWrapper:a,logger:i,screenshotStorage:s}){if(n.target&&!rr(n.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:i});let l={clearHighlights:!0,hideCaret:!0},c;n.target?.elementDescriptor?c=(await a({ctx:t,tracer:e,command:n,target:n.target,cache:n.cache?.target,action:async K=>hi(o,{locator:K.locator,...l}),options:{...n,disableCache:r,disableGlobalLocatorRedirect:!0,targetName:"target"}})).result:c=await hi(o,l);let d=await s.prepareGoldenScreenshotForComparison(i,n,c);if((c.height!==d.height||c.width!==d.width)&&i.warn({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 _=`${c.width}x${c.height}`,K=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${_}) 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 fS.fromBuffer(c.buffer),m={width:c.width,height:c.height},p=await fS.fromBuffer(d.buffer),g={width:d.width,height:d.height},h,f=m.width*m.height,y=g.width*g.height,b=Math.abs(m.height-g.height),w=Math.abs(m.width-g.width);if(f>y){let _=u.cover({w:g.width,h:g.height});c.buffer=await _.getBuffer("image/jpeg"),h="current",c.width=g.width,c.height=g.height}else if(y>f){let _=p.cover({w:m.width,h:m.height});d.buffer=await _.getBuffer("image/jpeg"),h="saved"}let C={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},v=n.threshold??.1,x=cI(ru.decode(d.buffer).data,ru.decode(c.buffer).data,C.data,c.width,c.height,{threshold:v,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,M=x>v*100,D=`Visual diff of ${x.toFixed(2)}% detected, which is ${M?"over":"under"} the threshold of ${v*100}%.`;if(h&&(D+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${w} pixels.`),M)throw new A("ActionFailureError",D);return{fail:M,thoughts:D,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:ru.encode(C,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var dI=3e4;async function yS({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??dI/1e3,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([p,g])=>p&&g)),i=new URLSearchParams;Object.entries(t.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{i.append(p,g)});let s=i.toString(),l;if(Zo(t.url)&&(l=t.url),n&&ea(t.url,n)&&(l=new URL(t.url,n).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);e.info({url:l,searchParams:s,headers:a,body:t.body,method:t.method},"Making HTTP request");let d=await H((async()=>{let p=s?`${l}?${s}`:l;try{return await r(p,{headers:a,method:t.method,body:t.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let p;try{p=await d.text()}catch(g){p=`Failed to read response body: ${g}`}throw new A("ActionFailureError",`Fetch request failed with status ${d.status}: ${p}`)}let u={};d.headers.forEach((p,g)=>{u[g]=p});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 uI=5e3;async function dl({timeout:t=Tn,...e}){let n=Date.now(),r=t*1e3,o=r+1e4,a,i=0,s=500;for(;i-n<r;){if(Date.now()-n>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();a=await bS(e),i=Date.now();let c=i-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!a.success)await J(s,e.signal),s=Math.min(Math.floor(s*1.5),uI);else return a}return a=await bS(e),a}async function bS({assertion:t,browser:e,autoExpandIframes:n}){switch(t.type){case"CONTENT":{let o,a=!1,i;try{let s;if(n){let l=await e.evaluateFunctionInAllFrames(TS,{value:t.value,negated:!!t.negated,returnHtml:!1});a=t.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:a,pageHtml:s}=await e.evaluateFunctionInPage(TS,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!a){let l=t.negated?tn.CONTAINS:nn.CONTAINS;i=new A("AssertionFailureError",`The page ${l} '${t.value}'.`),o=s}}catch(s){i=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:a,err:i,data:a||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function TS({value:t,negated:e,returnHtml:n}){let r=document.documentElement.outerHTML,o=r.includes(t)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&n?r:void 0}}var ou=async t=>{let{step:e,resolvedInputs:n}=t.moduleParams,{logger:r,context:o,storage:a,codeEvalTools:i,controller:s}=t.fixtures,l=s.browser,{orgId:c,runId:d}=t.inputs,u=s.executeAbortController.signal;Object.keys(n).length>0&&(o.setInputs(n),r.info(_d({json:{inputs:n,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let m,p=!1,g,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",y=await jt({orgId:c,s:f,context:o,logger:r,localTools:i,signal:u});h={orgId:c,cacheKeys:[y,...Object.entries(n).map(([w,C])=>`${w}:${C}`)]},r.info({original:f,keyParams:h},"Module cache key params");let b=Date.now();for(;Date.now()-b<wg;){u?.throwIfAborted();let w=await a.getCacheResult(h);if(w){r.info({cacheResult:$e(w,1e3,!0)},"Got result from module execution cache"),m=ul(e,n,"SUCCESS"),m.message="Used cached module result.",m.data=JSON.parse(w),p=!0;break}else r.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let C=await a.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${mI()};runId:${d}`},u);if(C.acquired){g=C.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await J(2500+Math.random()*1e4,u)}}try{if(!m)m=await pI(t);else if(e.autoAuth){let f=us.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 y=!1,b=e.advanced?.cacheInvalidation;if(b&&b.type==="PAGE_CHECK"){let w={type:"CONTENT",value:b.substring},C=await dl({timeout:Tn,assertion:w,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"),y=!0)}if(h&&y)return await a.deleteCacheResult(h),ou(t)}}finally{try{g!==void 0&&!p&&m?.status==="SUCCESS"&&await gI({step:e,result:m,browser:s.browser,cacheKeyPrefix:g,logger:r,storage:a})}finally{g!==void 0&&await a.releaseCacheLock(g)}}return m},pI=async t=>{let{step:e,tracer:n}=t.moduleParams,r=ul(e,t.moduleParams.resolvedInputs,"SUCCESS"),o=await n.startSubSteps(),{status:a,results:i}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return r.results=i,r.status=a,r.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,nestedResults:i,result:r,logger:t.fixtures.logger}),r};function ul(t,e,n){let r={};return Object.entries(e).forEach(([a,i])=>{r[a]=JSON.stringify(i)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:n}}async function wS({orgId:t,step:e,context:n,logger:r,flagStore:o,codeEvalTools:a,signal:i}){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 yr({orgId:t,code:c,fragment:!0,context:n,logger:r,localTools:a,signal:i})}return s}catch(l){throw i?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function gI({step:t,result:e,browser:n,cacheKeyPrefix:r,logger:o,storage:a}){let i=t.cacheConfig?.cacheExpiryMs;(!i||i===nh)&&(i=t.defaultCacheTtl??rh);let s;t.autoAuth?s=JSON.stringify(await n.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:r,ttlMs:i,truncatedCacheResultJson:_d({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await a.setCacheResult({result:s,keyPrefix:r,ttlMs:i})}async function lo(t,e,n){return hI(t,e,n)}async function hI(t,e,n){let r=new Date;try{return n.throwIfAborted(),await e()}catch(o){let a=new Date,i="FAILED",s;if(n.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",i="CANCELLED"):o instanceof A?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let l=ul(t,{},"FAILED");return l.message=s,l.startedAt=r,l.finishedAt=a,l}return{...Xs(t),startedAt:r,finishedAt:a,status:i,data:null,message:s,results:[]}}}async function la(t,e){let n=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,n=!0),await e()}finally{t&&n&&(t.state.failureRecoveryDisabled=void 0)}}import{randomUUID as ES}from"crypto";var ml=async t=>{let{step:e,tracer:n}=t.presetParams,{logger:r,controller:o,context:a,billingReporter:i}=t.fixtures,{collectDebugData:s}=t.options,{testMetadata:l,suiteMetadata:c}=t.inputs,d=e.command.type,u=r.child({commandType:d,stepId:e.id,commandId:e.command.id}),m=Kc(e.command);t.work.asyncTasks.push(i.reportCreditsUsed(u,d,m,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let p=o.browser.url(),g=new Date,h,f=ES(),y=ES();if(s)try{if(h=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let R=await o.browser.getRawCondensedHtml();n.attachBeforeHtmlSnapshot({logger:u,snapshotId:f,html:R})}}catch(R){u.debug({err:R},"Failed to take before screenshot, continuing...")}let b,w,C,v=is();try{let R=await o.executePresetCommand(v,n,e.command,a,l?.advanced.disableAICaching??!1);R.beforeScreenshotOverride&&(h=R.beforeScreenshotOverride),C=R.afterScreenshotOverride;let x=new Date,M=o.browser.url();w={beforeUrl:p,afterUrl:M,startedAt:g,finishedAt:x,viewport:o.browser.getViewport(),status:R.fail?"FAILED":"SUCCESS",elementInteracted:R.elementInteracted},b={...e,message:R.thoughts??"Successfully executed preset action.",beforeUrl:p,afterUrl:M,finishedAt:x,startedAt:g,status:R.fail?"FAILED":"SUCCESS",data:R.data,results:[w],details:v.details},"assertion"in e.command&&(b.message=R.thoughts||"Assertion passed.")}catch(R){u.error({message:R.message,stack:R.stack},`Failed executing preset step ${jn(e.command)}`);let x=o.browser.url(),M=new Date,D=R instanceof Error?R.message:`${R}`;w={beforeUrl:p,afterUrl:x,startedAt:g,finishedAt:M,viewport:o.browser.getViewport(),status:R instanceof DOMException&&R.name==="AbortError"?"CANCELLED":"FAILED",message:D},b={...e,startedAt:g,finishedAt:M,beforeUrl:p,afterUrl:x,status:R instanceof DOMException&&R.name==="AbortError"?"CANCELLED":"FAILED",message:D,failureReason:R instanceof A?R.reason:void 0,results:[w],details:v.details}}if(s)try{if(C||(C=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let R=await o.browser.getRawCondensedHtml();n.attachAfterHtmlSnapshot({logger:u,snapshotId:y,html:R})}}catch(R){u.debug({err:R},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return w.beforeSnapshot=f,b.beforeSnapshot=f,w.afterSnapshot=y,b.afterSnapshot=y,h&&n.attachBeforeScreenshot({logger:u,snapshotId:f,screenshot:h}),C&&n.attachAfterScreenshot({logger:u,snapshotId:y,screenshot:C}),b};async function RS({codePath:t,screenshotBuff:e,storage:n,logger:r}){if(e)try{let o=await n.uploadScreenshot(e);return r.info({screenshotUrl:o,codePath:t},"Saved screenshot for debugging"),o}catch(o){r.error({err:o,codePath:t},"Failed to save screenshot for debugging")}}async function Mn({frameConfig:t,action:e,browser:n}){let r=n.getActiveFrameConfig();t?n.setActiveFrameConfig(t):r?.type==="auto"&&n.setActiveFrameConfig(void 0);try{return await e()}finally{n.setActiveFrameConfig(r)}}var fI=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function CS({beforeUrl:t,beforePages:e,browser:n,command:r,logger:o}){if(fI.includes(r.type))return;let s=("cache"in r&&r.cache&&"target"in r.cache?r.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,l=Date.now(),c=0;for(;c===0||Date.now()-l<s;){await J(250),c++;let d=(await n.getOpenPages()).map(m=>m.url),u=n.url();if(d.length!==e.length)for(let m=d.length-1;m>=e.length;m--){let p=d[m];if(no(p,o)&&p!==t&&p!==u){o.info({beforePages:e,afterPages:d,beforeUrl:t},"Auto-following new tab after preset action"),await n.switchToPage({type:"INDEX",index:String(m)});break}}}}var vS="MOMENTIC_RUN_ID",AS="FINAL_SCREENSHOT_URL";import{cloneDeep as xI}from"lodash-es";async function xS(t){let{step:e,tracer:n}=t.conditionalParams,{logger:r,controller:o}=t.fixtures,a=new Date,i=Xs(e),s=e.elseSteps,l=!0,c=[],d,u=is();for(let f=0;f<e.blocks.length;f++){r.info(`Evaluating condition ${f} in conditional step`);let y=e.blocks[f];try{let b=await ml({...t,presetParams:{tracer:n,step:y.assertion}});c.push(b),r.info(`Condition ${f} resolved to true, executing the corresponding ${y.steps.length} steps`),l=!1,s=y.steps,d=b}catch(b){r.info({err:b},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(s)l&&r.info("No conditions resolved to true, executing the else block steps");else return r.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...i,status:"SUCCESS",startedAt:a,data:c[c.length-1]?.data,message:c[c.length-1]?.message,results:[],finishedAt:new Date,details:u.details};r.info(`Executing ${s.length} steps in the selected conditional block`);let m=await t.conditionalParams.tracer.startSubSteps(),p=await t.executeStepList({...t,listParams:{steps:s,containerName:"conditional block",tracer:m}}),h={...i,assertionResult:d,...p,startedAt:a,finishedAt:new Date};return In({asyncTasks:t.work.asyncTasks,nestedResults:[...c,...p.results],result:h,logger:r}),h}import{randomUUID as IS}from"crypto";var PS=async t=>{let{tracer:e}=t.aiStepParams,{controller:n,logger:r}=t.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({}),a=await SI(t);a.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,result:a,nestedResults:a.results,logger:t.fixtures.logger});let i=await n.browser.screenshot({}),s=IS();a.beforeSnapshot=s,e.attachBeforeScreenshot({logger:r,snapshotId:s,screenshot:o});let l=IS();return a.afterSnapshot=l,e.attachAfterScreenshot({logger:r,snapshotId:l,screenshot:i}),a},SI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{controller:r,context:o,logger:a}=t.fixtures,i={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new A("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await n.startSubSteps(),{status:c}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:"AI action",results:i.results,tracer:l}});return i.finishedAt=new Date,i.status=c,i}catch(l){a.warn({err:l},"Failed executing saved deprecated AI action steps");let c=r.executeAbortController.signal.aborted;i.message=l instanceof Error?l.message:`${l}`,i.status=c?"CANCELLED":"FAILED"}return i};import{randomUUID as au}from"crypto";var MS=15,yI=7,LS=async t=>{let{tracer:e}=t.aiStepParams,{logger:n,controller:r}=t.fixtures;await r.browser.waitForDOMStability();let o=await r.browser.screenshot({quality:75}),a=await bI(t);a.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,result:a,nestedResults:a.results,logger:t.fixtures.logger});let i=await r.browser.screenshot({quality:75}),s=au();a.beforeSnapshot=s,e.attachBeforeScreenshot({logger:n,snapshotId:s,screenshot:o});let l=au();return a.afterSnapshot=l,e.attachAfterScreenshot({logger:n,snapshotId:l,screenshot:i}),a},bI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{testMetadata:r,orgId:o}=t.inputs,{controller:a,context:i,logger:s,codeEvalTools:l}=t.fixtures,{step:c}=t.callbacks,d=`${e.id}-${Date.now()}`,u=s.child({stepId:e.id,langfuseSessionId:d}),m={...e,startedAt:new Date,beforeTestContext:i.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},p=await jt({orgId:o,s:e.text,context:i,logger:u,localTools:l});await a.browser.waitForDOMStability({logger:u});let h=`data:image/jpeg;base64,${(await a.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],y=0,b=0,w,C;for(;;){if(y>MS)return m.message=`Exceeded the maximum number of commands allowed per AI step (${MS})`,m.status="FAILED",m;if(a.executeAbortController.signal.aborted)return m.message="Test execution was cancelled",m.status="CANCELLED",m;c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let v=await a.evaluateAiAction({goal:p,startingScreenshot:y===0?void 0:h,history:f,logger:u,langfuseSessionId:d,lastError:C}),{evaluation:R,reasoning:x,summary:M}=v;u.info(v,"Got AI evaluation");let D=m.results[y-1]?.id;switch(R.type){case"DONE":return m.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,m.status="SUCCESS",D&&c.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"SUCCESS",message:`${M}
33
- ${x}`}),m;case"RIGHT_TRACK":{w=void 0,y===0?c.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:x}):D&&c.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"SUCCESS",message:x});break}case"WRONG_TRACK":{if(w=`${x}
34
- ${R.feedback}`,b++,b>=yI)return m.message=`Our AI agent requires additional information to achieve this goal:
32
+ ${t.code}`;throw t.logger.error({err:e.error,code:t.code,env:t.context.toObjectCopy()},n),new Error(n)}if(e.variableUpdates)for(let[n,r]of Object.entries(e.variableUpdates))t.context.setVariable(n,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await t.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[n,r]of Object.entries(e.persistentVariableUpdates))t.context.setVariable(n,r)}return e.result}import{set as sI}from"lodash-es";async function jt(t){let{orgId:e,s:n,context:r,logger:o,signal:a,retries:i=2,timeoutMs:s=lr,allowUndefined:c=!1}=t,l=/{{(.*?)}}/g,d=n.matchAll(l),u=n;for(let m of d){if(m.length<2)continue;let p=m[1].trim(),g;try{g=await Sr({orgId:e,code:p,fragment:!0,context:r,timeoutMs:s,logger:o,retries:i,localTools:t.localTools,signal:a})}catch(f){throw o.error({err:f,value:n},"Error evaluating template string"),f}if(g===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 h=typeof g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],h)}return u}async function ll(t){return uS(t)}async function uS({obj:t,bannedKeys:e,allowList:n,context:r,prefixPath:o=[],replacements:a=[],...i}){for(let s in t){if(e.includes(s))continue;let c=!1;if(n)if(n.includes(s))c=!0;else continue;let l=t[s],d=[...o,s];if(typeof l=="string"&&l.includes("{{")){let u=await jt({s:l,context:r,...i});if(l===u)continue;a.push({path:d,original:l}),t[s]=u}else typeof l=="object"&&l!==null&&!Array.isArray(l)&&await uS({obj:l,bannedKeys:e,context:r,prefixPath:d,replacements:a,allowList:c?void 0:n,...i})}return a}function mS(t,e){for(let{path:n,original:r}of e)sI(t,n,r)}import lI from"fetch-retry";var B6=process.env.MAILINATOR_API_KEY,z6=lI(global.fetch,{retryOn:function(t,e,n){return t>3?!1:!!(e!==null||n&&n.status>=400)},retryDelay:function(t){return 500}});import{hostname as hI}from"os";async function pS(t){let{command:e,tracer:n,timeoutMs:r,targetingWrapper:o,disableCache:a,fixtures:i}=t,{logger:s,abortSignal:c}=i;if(e.target&&!nr(e.target))throw new Error("Element assertion with x/y is not supported yet");let l=dI(e.assertion),d=Am(e.cache)?e.cache:void 0,u=Date.now(),m=0,p,g=500;for(;m<2||Date.now()-u<r;){m++,m>1&&await J(g,c),c?.throwIfAborted();try{let{elementInteractedDisplayString:h,result:f,thoughts:b}=await o({ctx:i.ctx,tracer:n,command:e,target:e.target,cache:d?.target,action:async y=>cI(y.locator,t),options:{...e,disableCache:a,disableGlobalLocatorRedirect:!0,source:Hr(e),allowZeroOpacityOverride:!0,targetName:"target"}});if(p={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:h,thoughts:b},!f.success){p={...f,thoughts:b},g=Math.min(g*2,1e4);continue}return p}catch(h){if(c?.throwIfAborted(),l)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`,err:void 0,data:void 0};if(s.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof A)||h.reason!="ActionFailureError")throw h;p={success:!1,err:h,data:void 0,thoughts:void 0}}}if(!p)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return p}async function cI(t,{command:e,fixtures:n}){let r=e.assertion;await n.browser.highlight(t);let o=!0,a,i;switch(r.type){case"ELEMENT_CONTENT":{let c=await t.textContent()??"";if(i={elementTextContent:$e(c,500,!0)},!cl(c,r.value,r.operation,!!r.negated)){let l=r.negated?nn[r.operation]:rn[r.operation];o=!1,a=new A("AssertionFailureError",`The content ${l} '${r.value}': ${c}`)}break}case"ELEMENT_ATTRIBUTE":{i={elementOuterHtml:$e(await t.evaluate(l=>l.cloneNode(!1).outerHTML),500,!0)};let c;try{c=await t.getAttribute(r.attr,{timeout:3e3})??""}catch(l){a=new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${l}`),o=!1;break}if(!cl(c,r.value,r.operation,!!r.negated)){let l=r.negated?nn[r.operation]:rn[r.operation];o=!1,r.operation==="EXISTS"?a=new A("AssertionFailureError",`The attribute ${r.attr} ${l}`):a=new A("AssertionFailureError",`The attribute ${r.attr} ${l} '${r.value}': ${c}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await t.evaluate(async(l,d)=>{let u=Date.now();for(;Date.now()-u<d;){await new Promise(p=>setTimeout(p,250));let m=l.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(l).visibility!=="hidden"&&window.getComputedStyle(l).display!=="none")return!0}return!1},Tn*1e3);break}case"EDITABLE":{o=await t.isEditable({timeout:Tn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await t.isEnabled({timeout:Tn*1e3});break}case"FOCUSED":{o=await t.evaluate(l=>l===document.activeElement);break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let c=r.negated?Pd[r.condition]:Md[r.condition];a=new A("AssertionFailureError",`The element ${c}`)}break}case"ELEMENT_NAME":{let c=await t.evaluate(l=>l.tagName);if(!cl(c,r.value,r.operation,!!r.negated)){let l=r.negated?nn[r.operation]:rn[r.operation];o=!1,a=new A("AssertionFailureError",`The element tag name ${l} '${r.value}': ${c}`)}break}case"ELEMENT_STYLE":{let c=await t.evaluate((l,d)=>window.getComputedStyle(l).getPropertyValue(d),r.property);if(!cl(c,r.value,r.operation,!!r.negated)){let l=r.negated?nn[r.operation]:rn[r.operation];o=!1,r.operation==="EXISTS"?a=new A("AssertionFailureError",`The style property ${r.property} ${l}`):a=new A("AssertionFailureError",`The style property ${r.property} ${l} '${r.value}': ${c}`)}break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{success:o,data:i,err:a}}function cl(t,e,n,r){let o;switch(n){case"CONTAINS":{o=t.includes(e);break}case"EQUALS":{o=t.trim()===e.trim();break}case"STARTS_WITH":{o=t.trim().startsWith(e);break}case"EXISTS":{o=t.trim().length>0;break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return r?!o:o}function dI(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function gS(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as uI}from"jimp";async function fi(t,e){let n=await t.screenshot(e),r=await uI.fromBuffer(n);return{buffer:n,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as hS}from"jimp";import tu from"jpeg-js";import mI from"pixelmatch";async function fS({ctx:t,tracer:e,command:n,disableCache:r,browser:o,targetingWrapper:a,logger:i,screenshotStorage:s}){if(n.target&&!nr(n.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:i});let c={clearHighlights:!0,hideCaret:!0},l;n.target?.elementDescriptor?l=(await a({ctx:t,tracer:e,command:n,target:n.target,cache:n.cache?.target,action:async q=>fi(o,{locator:q.locator,...c}),options:{...n,disableCache:r,disableGlobalLocatorRedirect:!0,targetName:"target"}})).result:l=await fi(o,c);let d=await s.prepareGoldenScreenshotForComparison(i,n,l);if((l.height!==d.height||l.width!==d.width)&&i.warn({currHeight:l.height,currWidth:l.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(l.height-d.height)>10||Math.abs(l.width-d.width)>10){let k=`${l.width}x${l.height}`,q=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${k}) does not match saved screenshot dimensions (${q}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:l.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let u=await hS.fromBuffer(l.buffer),m={width:l.width,height:l.height},p=await hS.fromBuffer(d.buffer),g={width:d.width,height:d.height},h,f=m.width*m.height,b=g.width*g.height,y=Math.abs(m.height-g.height),E=Math.abs(m.width-g.width);if(f>b){let k=u.cover({w:g.width,h:g.height});l.buffer=await k.getBuffer("image/jpeg"),h="current",l.width=g.width,l.height=g.height}else if(b>f){let k=p.cover({w:m.width,h:m.height});d.buffer=await k.getBuffer("image/jpeg"),h="saved"}let v={data:Buffer.alloc(l.width*l.height*4),width:l.width,height:l.height},R=n.threshold??.1,x=mI(tu.decode(d.buffer).data,tu.decode(l.buffer).data,v.data,l.width,l.height,{threshold:R,diffColorAlt:[0,255,0]})/(l.width*l.height)*100,I=x>R*100,D=`Visual diff of ${x.toFixed(2)}% detected, which is ${I?"over":"under"} the threshold of ${R*100}%.`;if(h&&(D+=` The ${h} screenshot was cropped since it was taller by ${y} pixels and wider by ${E} pixels.`),I)throw new A("ActionFailureError",D);return{fail:I,thoughts:D,beforeScreenshotOverride:l.buffer,afterScreenshotOverride:tu.encode(v,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var pI=3e4;async function SS({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??pI/1e3,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([p,g])=>p&&g)),i=new URLSearchParams;Object.entries(t.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{i.append(p,g)});let s=i.toString(),c;if(Zo(t.url)&&(c=t.url),n&&ea(t.url,n)&&(c=new URL(t.url,n).toString()),!c)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);e.info({url:c,searchParams:s,headers:a,body:t.body,method:t.method},"Making HTTP request");let d=await j((async()=>{let p=s?`${c}?${s}`:c;try{return await r(p,{headers:a,method:t.method,body:t.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let p;try{p=await d.text()}catch(g){p=`Failed to read response body: ${g}`}throw new A("ActionFailureError",`Fetch request failed with status ${d.status}: ${p}`)}let u={};d.headers.forEach((p,g)=>{u[g]=p});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 gI=5e3;async function dl({timeout:t=Tn,...e}){let n=Date.now(),r=t*1e3,o=r+1e4,a,i=0,s=500;for(;i-n<r;){if(Date.now()-n>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let c=Date.now();a=await yS(e),i=Date.now();let l=i-c;if(l>1e3&&e.logger.warn({pageAssertDuration:l},"Page assertion took longer than expected"),!a.success)await J(s,e.signal),s=Math.min(Math.floor(s*1.5),gI);else return a}return a=await yS(e),a}async function yS({assertion:t,browser:e,autoExpandIframes:n}){switch(t.type){case"CONTENT":{let o,a=!1,i;try{let s;if(n){let c=await e.evaluateFunctionInAllFrames(bS,{value:t.value,negated:!!t.negated,returnHtml:!1});a=t.negated?c.every(l=>l.evaluation):c.some(l=>l.evaluation),s=c.find(l=>l.pageHtml)?.pageHtml}else({evaluation:a,pageHtml:s}=await e.evaluateFunctionInPage(bS,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!a){let c=t.negated?nn.CONTAINS:rn.CONTAINS;i=new A("AssertionFailureError",`The page ${c} '${t.value}'.`),o=s}}catch(s){i=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:a,err:i,data:a||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function bS({value:t,negated:e,returnHtml:n}){let r=document.documentElement.outerHTML,o=r.includes(t)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&n?r:void 0}}var nu=async t=>{let{step:e,resolvedInputs:n}=t.moduleParams,{logger:r,context:o,storage:a,codeEvalTools:i,controller:s}=t.fixtures,c=s.browser,{orgId:l,runId:d}=t.inputs,u=s.executeAbortController.signal;Object.keys(n).length>0&&(o.setInputs(n),r.info(Nd({json:{inputs:n,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let m,p=!1,g,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",b=await jt({orgId:l,s:f,context:o,logger:r,localTools:i,signal:u});h={orgId:l,cacheKeys:[b,...Object.entries(n).map(([E,v])=>`${E}:${v}`)]},r.info({original:f,keyParams:h},"Module cache key params");let y=Date.now();for(;Date.now()-y<Tg;){u?.throwIfAborted();let E=await a.getCacheResult(h);if(E){r.info({cacheResult:$e(E,1e3,!0)},"Got result from module execution cache"),m=ul(e,n,"SUCCESS"),m.message="Used cached module result.",m.data=JSON.parse(E),p=!0;break}else r.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let v=await a.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${hI()};runId:${d}`},u);if(v.acquired){g=v.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await J(2500+Math.random()*1e4,u)}}try{if(!m)m=await fI(t);else if(e.autoAuth){let f=us.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 c.loadAuthState(f.data);let b=!1,y=e.advanced?.cacheInvalidation;if(y&&y.type==="PAGE_CHECK"){let E={type:"CONTENT",value:y.substring},v=await dl({timeout:Tn,assertion:E,browser:c,logger:r,signal:u,autoExpandIframes:!!c.userBrowserSettings.autoExpandIframes});v.success?r.debug({invalResult:v},"Cached result still valid after page check, continuing..."):(r.info({invalResult:v},"Invalidating cached result due to page check failure"),b=!0)}if(h&&b)return await a.deleteCacheResult(h),nu(t)}}finally{try{g!==void 0&&!p&&m?.status==="SUCCESS"&&await SI({step:e,result:m,browser:s.browser,cacheKeyPrefix:g,logger:r,storage:a})}finally{g!==void 0&&await a.releaseCacheLock(g)}}return m},fI=async t=>{let{step:e,tracer:n}=t.moduleParams,r=ul(e,t.moduleParams.resolvedInputs,"SUCCESS"),o=await n.startSubSteps(),{status:a,results:i}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return r.results=i,r.status=a,r.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,nestedResults:i,result:r,logger:t.fixtures.logger}),r};function ul(t,e,n){let r={};return Object.entries(e).forEach(([a,i])=>{r[a]=JSON.stringify(i)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:n}}async function TS({orgId:t,step:e,context:n,logger:r,flagStore:o,codeEvalTools:a,signal:i}){let s={};try{for(let c of e.parameters??[]){let l=e.inputs?.[c]??e.defaultParameters?.[c];if(!l){r.warn(`No value or default found for parameter '${c}' that is required by module '${e.name}'`);continue}s[c]=await Sr({orgId:t,code:l,fragment:!0,context:n,logger:r,localTools:a,signal:i})}return s}catch(c){throw i?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${c}`)}}async function SI({step:t,result:e,browser:n,cacheKeyPrefix:r,logger:o,storage:a}){let i=t.cacheConfig?.cacheExpiryMs;(!i||i===th)&&(i=t.defaultCacheTtl??nh);let s;t.autoAuth?s=JSON.stringify(await n.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:r,ttlMs:i,truncatedCacheResultJson:Nd({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await a.setCacheResult({result:s,keyPrefix:r,ttlMs:i})}async function lo(t,e,n){return yI(t,e,n)}async function yI(t,e,n){let r=new Date;try{return n.throwIfAborted(),await e()}catch(o){let a=new Date,i="FAILED",s;if(n.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",i="CANCELLED"):o instanceof A?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let c=ul(t,{},"FAILED");return c.message=s,c.startedAt=r,c.finishedAt=a,c}return{...Xs(t),startedAt:r,finishedAt:a,status:i,data:null,message:s,results:[]}}}async function la(t,e){let n=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,n=!0),await e()}finally{t&&n&&(t.state.failureRecoveryDisabled=void 0)}}import{randomUUID as wS}from"crypto";var ml=async t=>{let{step:e,tracer:n}=t.presetParams,{logger:r,controller:o,context:a,billingReporter:i}=t.fixtures,{collectDebugData:s}=t.options,{testMetadata:c,suiteMetadata:l}=t.inputs,d=e.command.type,u=r.child({commandType:d,stepId:e.id,commandId:e.command.id}),m=Wc(e.command);t.work.asyncTasks.push(i.reportCreditsUsed(u,d,m,{testId:c?.id,testName:c?.name,suiteId:l?.id,suiteName:l?.name}));let p=o.browser.url(),g=new Date,h,f=wS(),b=wS();if(s)try{if(h=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let C=await o.browser.getRawCondensedHtml();n.attachBeforeHtmlSnapshot({logger:u,snapshotId:f,html:C})}}catch(C){u.debug({err:C},"Failed to take before screenshot, continuing...")}let y,E,v,R=is();try{let C=await o.executePresetCommand(R,n,e.command,a,c?.advanced.disableAICaching??!1);C.beforeScreenshotOverride&&(h=C.beforeScreenshotOverride),v=C.afterScreenshotOverride;let x=new Date,I=o.browser.url();E={beforeUrl:p,afterUrl:I,startedAt:g,finishedAt:x,viewport:o.browser.getViewport(),status:C.fail?"FAILED":"SUCCESS",elementInteracted:C.elementInteracted},y={...e,message:C.thoughts??"Successfully executed preset action.",beforeUrl:p,afterUrl:I,finishedAt:x,startedAt:g,status:C.fail?"FAILED":"SUCCESS",data:C.data,results:[E],details:R.details},"assertion"in e.command&&(y.message=C.thoughts||"Assertion passed.")}catch(C){u.error({message:C.message,stack:C.stack},`Failed executing preset step ${$n(e.command)}`);let x=o.browser.url(),I=new Date,D=C instanceof Error?C.message:`${C}`;E={beforeUrl:p,afterUrl:x,startedAt:g,finishedAt:I,viewport:o.browser.getViewport(),status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:D},y={...e,startedAt:g,finishedAt:I,beforeUrl:p,afterUrl:x,status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:D,failureReason:C instanceof A?C.reason:void 0,results:[E],details:R.details}}if(s)try{if(v||(v=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let C=await o.browser.getRawCondensedHtml();n.attachAfterHtmlSnapshot({logger:u,snapshotId:b,html:C})}}catch(C){u.debug({err:C},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return E.beforeSnapshot=f,y.beforeSnapshot=f,E.afterSnapshot=b,y.afterSnapshot=b,h&&n.attachBeforeScreenshot({logger:u,snapshotId:f,screenshot:h}),v&&n.attachAfterScreenshot({logger:u,snapshotId:b,screenshot:v}),y};async function ES({codePath:t,screenshotBuff:e,storage:n,logger:r}){if(e)try{let o=await n.uploadScreenshot(e);return r.info({screenshotUrl:o,codePath:t},"Saved screenshot for debugging"),o}catch(o){r.error({err:o,codePath:t},"Failed to save screenshot for debugging")}}async function Mn({frameConfig:t,action:e,browser:n}){let r=n.getActiveFrameConfig();t?n.setActiveFrameConfig(t):r?.type==="auto"&&n.setActiveFrameConfig(void 0);try{return await e()}finally{n.setActiveFrameConfig(r)}}var bI=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function RS({beforeUrl:t,beforePages:e,browser:n,command:r,logger:o}){if(bI.includes(r.type))return;let s=("cache"in r&&r.cache&&"target"in r.cache?r.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,c=Date.now(),l=0;for(;l===0||Date.now()-c<s;){await J(250),l++;let d=(await n.getOpenPages()).map(m=>m.url),u=n.url();if(d.length!==e.length)for(let m=d.length-1;m>=e.length;m--){let p=d[m];if(no(p,o)&&p!==t&&p!==u){o.info({beforePages:e,afterPages:d,beforeUrl:t},"Auto-following new tab after preset action"),await n.switchToPage({type:"INDEX",index:String(m)});break}}}}var CS="MOMENTIC_RUN_ID",vS="FINAL_SCREENSHOT_URL";import{cloneDeep as MI}from"lodash-es";async function AS(t){let{step:e,tracer:n}=t.conditionalParams,{logger:r,controller:o}=t.fixtures,a=new Date,i=Xs(e),s=e.elseSteps,c=!0,l=[],d,u=is();for(let f=0;f<e.blocks.length;f++){r.info(`Evaluating condition ${f} in conditional step`);let b=e.blocks[f];try{let y=await ml({...t,presetParams:{tracer:n,step:b.assertion}});l.push(y),r.info(`Condition ${f} resolved to true, executing the corresponding ${b.steps.length} steps`),c=!1,s=b.steps,d=y}catch(y){r.info({err:y},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(s)c&&r.info("No conditions resolved to true, executing the else block steps");else return r.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...i,status:"SUCCESS",startedAt:a,data:l[l.length-1]?.data,message:l[l.length-1]?.message,results:[],finishedAt:new Date,details:u.details};r.info(`Executing ${s.length} steps in the selected conditional block`);let m=await t.conditionalParams.tracer.startSubSteps(),p=await t.executeStepList({...t,listParams:{steps:s,containerName:"conditional block",tracer:m}}),h={...i,assertionResult:d,...p,startedAt:a,finishedAt:new Date};return In({asyncTasks:t.work.asyncTasks,nestedResults:[...l,...p.results],result:h,logger:r}),h}import{randomUUID as xS}from"crypto";var IS=async t=>{let{tracer:e}=t.aiStepParams,{controller:n,logger:r}=t.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({}),a=await TI(t);a.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,result:a,nestedResults:a.results,logger:t.fixtures.logger});let i=await n.browser.screenshot({}),s=xS();a.beforeSnapshot=s,e.attachBeforeScreenshot({logger:r,snapshotId:s,screenshot:o});let c=xS();return a.afterSnapshot=c,e.attachAfterScreenshot({logger:r,snapshotId:c,screenshot:i}),a},TI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{controller:r,context:o,logger:a}=t.fixtures,i={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new A("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let c=await n.startSubSteps(),{status:l}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:"AI action",results:i.results,tracer:c}});return i.finishedAt=new Date,i.status=l,i}catch(c){a.warn({err:c},"Failed executing saved deprecated AI action steps");let l=r.executeAbortController.signal.aborted;i.message=c instanceof Error?c.message:`${c}`,i.status=l?"CANCELLED":"FAILED"}return i};import{randomUUID as ru}from"crypto";var PS=15,wI=7,MS=async t=>{let{tracer:e}=t.aiStepParams,{logger:n,controller:r}=t.fixtures;await r.browser.waitForDOMStability();let o=await r.browser.screenshot({quality:75}),a=await EI(t);a.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,result:a,nestedResults:a.results,logger:t.fixtures.logger});let i=await r.browser.screenshot({quality:75}),s=ru();a.beforeSnapshot=s,e.attachBeforeScreenshot({logger:n,snapshotId:s,screenshot:o});let c=ru();return a.afterSnapshot=c,e.attachAfterScreenshot({logger:n,snapshotId:c,screenshot:i}),a},EI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{testMetadata:r,orgId:o}=t.inputs,{controller:a,context:i,logger:s,codeEvalTools:c}=t.fixtures,{step:l}=t.callbacks,d=`${e.id}-${Date.now()}`,u=s.child({stepId:e.id,langfuseSessionId:d}),m={...e,startedAt:new Date,beforeTestContext:i.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},p=await jt({orgId:o,s:e.text,context:i,logger:u,localTools:c});await a.browser.waitForDOMStability({logger:u});let h=`data:image/jpeg;base64,${(await a.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],b=0,y=0,E,v;for(;;){if(b>PS)return m.message=`Exceeded the maximum number of commands allowed per AI step (${PS})`,m.status="FAILED",m;if(a.executeAbortController.signal.aborted)return m.message="Test execution was cancelled",m.status="CANCELLED",m;l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let R=await a.evaluateAiAction({goal:p,startingScreenshot:b===0?void 0:h,history:f,logger:u,langfuseSessionId:d,lastError:v}),{evaluation:C,reasoning:x,summary:I}=R;u.info(R,"Got AI evaluation");let D=m.results[b-1]?.id;switch(C.type){case"DONE":return m.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,m.status="SUCCESS",D&&l.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"SUCCESS",message:`${I}
33
+ ${x}`}),m;case"RIGHT_TRACK":{E=void 0,b===0?l.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:x}):D&&l.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"SUCCESS",message:x});break}case"WRONG_TRACK":{if(E=`${x}
34
+ ${C.feedback}`,y++,y>=wI)return m.message=`Our AI agent requires additional information to achieve this goal:
35
35
  ${x}
36
- ${R.feedback}`,m.status="FAILED",c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:m.message}),m;D&&c.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"FAILED",message:R.feedback});break}case"IMPOSSIBLE":return m.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,m.status="FAILED",c.onDynamicAIActionEvaluatingEvent?.({stepId:D??e.id,status:"FAILED",message:m.message}),m}let _=setTimeout(()=>{c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);u.info({commandIndex:y,lastActionHint:w},`Generating new sub-command ${y} within AI action`);let K,P;try{({command:K,reasoning:P}=await a.promptToCommand({goal:p,history:f,startingScreenshot:h,disableCache:r?.advanced.disableAICaching??!1,logger:u,actionHint:w,langfuseSessionId:d})),u.info({command:K,reasoning:P},"Got proposed command")}finally{clearTimeout(_)}if(K.type==="FAILURE")return clearTimeout(_),m.status="FAILED",m.message=`Our AI agent determined that no supported actions can fulfill the goals: ${P}`,m;let W={id:au(),type:"PRESET_ACTION",command:K},k={substepIndex:y+1,message:P||"Generated new command."};c.onDynamicCommandGenerated?.({...k,step:W,parentStepId:e.id}),u.info({commandId:K.id},`Executing sub-command ${y} within AI step: ${jn(K)}`);let G=await n.startSubSteps(),Ce=(await t.executeStepList({...t,options:{...t.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[W],tracer:G}})).results[0];c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await a.browser.waitForDOMStability({logger:u});let be=await a.browser.screenshot({clearHighlights:!0,retries:1});m.results.push(Ce),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${be.toString("base64")}`,urlAfterCommand:a.browser.url(),serializedCommand:jn(K),elementInteracted:Ce.results[0]?.elementInteracted,thoughts:P});let wt={substepIndex:y,output:{...Ce,message:Ce.message??"Successfully executed preset action."},step:W,parentStepId:e.id};if(c.onDynamicCommandExecuted?.(wt),await n.finish({output:Ji.parse(Ce),step:Ce,message:Ce.message,attempt:1}),Ce.status==="FAILED")if(m.status="FAILED",m.message=Ce.message,b<3)b++,C=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${Ce.message}`;else return m;else if(Ce.status==="CANCELLED")return m.status="CANCELLED",m.message=Ce.message,m;y++}};import{randomUUID as TI}from"crypto";var wI=3;async function OS(t){let{logger:e}=t.fixtures,{results:n}=t.failureRecoveryParams,r=n[n.length-1],o=RI(t.work,r);if(o)return e.info({failedResult:r,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};t.work.state.failureRecoveryAttempts=(t.work.state.failureRecoveryAttempts??0)+1;try{return await EI(t)}catch(a){return e.warn({err:a},"Error during failure recovery attempt, continuing..."),null}}async function EI(t){let{fixtures:e,work:n,failureRecoveryParams:r}=t,{controller:o,logger:a}=e,{testMetadata:i}=t.inputs,{results:s,failedStep:l,nextSteps:c,tracer:d}=r;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(n.asyncTasks??[]);let u=o.browser.url(),m=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,p=(await o.browser.getBrowserState({})).serialize(),{results:g}=await Qo(a,d,s,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=c.map(M=>hr(M)),f=i?.description?.trim(),y=i?.advanced?.failureRecoveryInstructions?.trim(),{scenario:b,thoughts:w,instructions:C}=await o.getFailureRecoveryPlan({currentUrl:u,currentScreenshot:m,failedResults:g,currentPageState:p,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:y||void 0});if(b!=="RECOVERABLE")return a.info({scenario:b,thoughts:w,instructions:C},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${w}`};if(!C)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let v={id:TI(),type:"AI_ACTION_DYNAMIC",text:C},R=await la(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures},listParams:{steps:[v,l],containerName:"AI-recovered step list",tracer:d}})),x=R.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(Ds({results:R.results,onPresetAction:M=>{M.aiSuggested=!0},onSimpleStepContainer:M=>{M.aiSuggested=!0}}),x.status==="SUCCESS"){let M=`The following steps were automatically executed by the failure recovery agent. Analysis: ${w}`;return x.message=M,a.info({thoughts:w},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:R,message:M}}else{let M=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${w}`;return x.message=M,a.info({thoughts:w,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:R,message:M}}return null}function RI(t,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let n=e.message;return n?n.includes("AbortError:")?"The user aborted the test":Qm.some(r=>n.includes(r))?"The failed step is an irrecoverable configuration error":(t.state.failureRecoveryAttempts??0)>wI?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as pl}from"crypto";import CI from"fast-json-patch";import{cloneDeep as vI}from"lodash-es";async function NS(t){let e=t.failedResults,n=[],{sectionParams:r,fixtures:o,work:a,startingUrl:i,startingContextSnapshot:s,tracer:l}=t,{step:c}=r,{controller:d,logger:u}=o,m=c?.autohealingConfig,p=m?.restartBehavior??{type:"GO_TO_SECTION_START"},g=m?.attempts??1;for(let h=0;h<g;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=vI(c.steps);await Promise.allSettled(a.asyncTasks??[]);let{results:y}=await Qo(u,l,e.results,{numStepsWithScreenshots:4}),b=await d.runSectionAutohealing({results:y,errorMessage:e.terminalResult?.message,goal:c.description});f=CI.applyPatch(f,b.patches).newDocument;let w=Xt.fromSnapshot({snapshot:s,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await AI({logger:u,controller:d,tracer:l,context:w,restartConfig:p,startingUrl:i});let C=await la(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures,context:w},listParams:{steps:f,containerName:"auto-healed step list",tracer:l}}));if(n.push(C.results),C.status==="SUCCESS")return{successfulHealing:{proposedStep:{...c,steps:f},listResult:C,context:w},healingAttempts:n};e=C}return{healingAttempts:n}}async function AI({logger:t,controller:e,tracer:n,restartConfig:r,context:o,startingUrl:a}){switch(r.type){case"NAVIGATE_URL":{let i={id:pl(),type:"PRESET_ACTION",command:{id:pl(),type:"NAVIGATE",url:r.url}},s=await n.startStep({logger:t,step:i,attempt:1});await e.executePresetCommand(null,s,i.command,o,!1);break}case"GO_TO_SECTION_START":{let i={id:pl(),type:"PRESET_ACTION",command:{id:pl(),type:"NAVIGATE",url:a}},s=await n.startStep({logger:t,step:i,attempt:1});await e.executePresetCommand(null,s,i.command,o,!1);break}}}function kS(t,e){switch(t||(t="ON_FAILURE"),t){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Lm(e.command.type))}}async function _S(t){let{step:e,tracer:n}=t.sectionParams,{logger:r,controller:o,context:a}=t.fixtures,i=new Date,s=o.browser.url(),l=a.toObjectCopy(),c=await n.startSubSteps(),d=async()=>t.executeStepList({...t,listParams:{steps:e.steps,containerName:"section step list",tracer:c}}),u=e.autohealingConfig?await la(t.work,d):await d(),m,p;if(u.status==="FAILED"&&e.autohealingConfig&&!t.work.state.autoHealingDisabled&&kS(e.autohealingConfig.trigger,u.terminalResult)){let h=await n.startSubSteps(),f=await NS({...t,startingContextSnapshot:l,startingUrl:s,failedResults:u,tracer:h});f.successfulHealing&&(m=f.successfulHealing.proposedStep,u=f.successfulHealing.listResult,t.fixtures.context=f.successfulHealing.context),p=f.healingAttempts}let g={...e,...u,startedAt:i,finishedAt:new Date,proposedStep:m,healingAttempts:p};return In({asyncTasks:t.work.asyncTasks,nestedResults:u.results,result:g,logger:r}),g}var II=60*60*1e3;async function mn(t){let{results:e=[],containerName:n,steps:r,tracer:o}=t.listParams,{logger:a}=t.fixtures,i=o.getParentStepIdChain(),{fromStep:s,toStep:l}=t.inputs,c=t.work,d="SUCCESS",u,m=0;for(m;m<r.length;m++){let p=r[m];if(p.skipped)continue;if(c.fastForwardingToStep&&s){let w=JSON.stringify(i);if(p.id===s.fromStepId&&w===JSON.stringify(s.parentStepIdChain))c.fastForwardingToStep=!1;else if(!Nh(p,i,s.fromStepId,s.parentStepIdChain))continue}let g=hr(p),h=0,f=1,y=Date.now();"retries"in p&&p.retries&&p.retries>0&&(f+=p.retries);let b;for(;h<f&&Date.now()-y<II;){h++,a.info({step:p,currentAttempt:h},`Executing step ${m+1}/${r.length} in ${n}: ${g}`);let w=Date.now(),{stepResult:C,status:v,failureRecoveryResults:R,shouldStopExecuting:x}=await PI({attempt:h,params:t,step:p,i:m,steps:r,results:e,currentParentIdChain:i,work:c,fromStep:s,toStep:l,lastRetry:h===f});if(v==="FAILED"&&h<f){b=[...b??[],C],Date.now()-w<1e3&&await J(1e3-(Date.now()-w));continue}else e.push(C),b&&(C.previousAttempts=b);if(R&&e.push(...R),x)return d=v,u=C,{status:d,results:e,terminalResult:u};break}}return{status:d,results:e,terminalResult:u}}async function PI({attempt:t,params:e,step:n,i:r,steps:o,results:a,currentParentIdChain:i,work:s,fromStep:l,toStep:c,lastRetry:d}){let{tracer:u}=e.listParams,{logger:m,context:p,controller:g,codeEvalTools:h,billingReporter:f}=e.fixtures,{orgId:y}=e.inputs,b=new Date,w=await u.startStep({logger:m,step:n,attempt:t}),C=xI(n),v=p.toRedactedDisplayCopy(),R=g.browser.url(),x=g.executeAbortController.signal,M=qc(n.type);s.asyncTasks.push(f.reportCreditsUsed(m,n.type,M,{testId:e.inputs.testMetadata?.id,testName:e.inputs.testMetadata?.name,suiteId:e.inputs.suiteMetadata?.id,suiteName:e.inputs.suiteMetadata?.name}));let D,_;switch(n.type){case"PRESET_ACTION":{D="Preset action",_=await lo(n,async()=>await ml({...e,presetParams:{tracer:w,step:n}}),x);break}case"AI_ACTION":{D="AI action",_=await lo(n,()=>PS({...e,aiStepParams:{step:n,tracer:w},executeStepList:mn}),x);break}case"AI_ACTION_DYNAMIC":{D="AI action",_=await lo(n,()=>LS({...e,aiStepParams:{step:n,tracer:w},executeStepList:mn}),x);break}case"RESOLVED_MODULE":{D=`Module (${n.name})`,_=await lo(n,async()=>{let G=await wS({orgId:y,step:n,context:p,logger:m,flagStore:g.flagStore,codeEvalTools:h,signal:x});return ou({...e,executeStepList:mn,moduleParams:{step:n,resolvedInputs:G,tracer:w}})},x);break}case"CONDITIONAL":{D="Conditional step",_=await lo(n,()=>xS({...e,conditionalParams:{step:n,tracer:w},executeStepList:mn}),x);break}case"SECTION":{D="Section",_=await lo(n,()=>_S({...e,sectionParams:{step:n,tracer:w},executeStepList:mn}),x);break}default:return(we=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}_.beforeUrl=_.beforeUrl??R,_.beforeTestContext=v,n.envKey&&p.setVariable(n.envKey,_.data);let K=g.browser.url();p.setCurrentUrl(K),_.afterUrl=_.afterUrl??K,_.afterTestContext=p.toRedactedDisplayCopy(),await MI({startedAt:b,stepTypeName:D,result:_,callbacks:e.callbacks,globalWorkRef:e.work,tracer:w,attempt:t});let P,W;if(d&&_.status==="FAILED"&&!s.state.failureRecoveryDisabled&&l?.fromStepId===void 0&&c?.toStepId===void 0){let G=await OS({...e,executeStepList:mn,failureRecoveryParams:{failedStep:C,nextSteps:o.slice(r+1),results:a.concat(_),tracer:u}});G&&(G.type==="ATTEMPTED"?(P=G.result.results,W=G.status):G.type==="NOT_ELIGIBLE"&&(_.message=_.message?`${_.message} ${G.message}`:G.message),_.type==="PRESET_ACTION"&&(_.failureRecoveryStatus={type:G.type,message:G.message}))}return s.fastForwardingToStep&&l&&(l.fromStepId===n.id&&JSON.stringify(i)===JSON.stringify(l.parentStepIdChain)&&(s.fastForwardingToStep=!1),n.type==="RESOLVED_MODULE"&&Id(i,l.parentStepIdChain)&&(s.fastForwardingToStep=!1)),_.status!=="SUCCESS"&&W!=="SUCCESS"||g.closed?{shouldStopExecuting:!0,status:_.status,stepResult:_,failureRecoveryResults:P}:c&&n.id===c.toStepId&&JSON.stringify(i)===JSON.stringify(c.parentStepIdChain)?(g.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:_,failureRecoveryResults:P}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:_,failureRecoveryResults:P}}async function MI({stepTypeName:t,result:e,tracer:n,attempt:r}){let o=t.toLowerCase(),a=t.charAt(0).toUpperCase()+t.slice(1),i="";switch(e.status){case"SUCCESS":i=e.message??`${a} executed successfully.`;break;case"FAILED":i=e.message??`${a} failed.`;break;case"CANCELLED":i=e.message??`${a} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await n.finish({step:e,message:i,output:Ji.parse(e),attempt:r})}import{randomUUID as DS}from"crypto";async function FS({browser:t,signal:e}){let n=new Date;try{return await t.navigate({url:t.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(r){let o={id:DS(),type:"PRESET_ACTION",status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:r.message,startedAt:n,finishedAt:new Date,results:[],command:{id:DS(),type:"NAVIGATE",url:t.baseUrl}};return{status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var gl=async t=>{let{orgId:e,runId:n,testMetadata:r,suiteMetadata:o,steps:a,beforeSteps:i,afterSteps:s}=t.inputs;await t.fixtures.billingReporter.reportBillableEvent(t.fixtures.logger,"test-run",{eventId:n,testId:r?.id,testName:r?.name,suiteId:o?.id,suiteName:o?.name}),t.fixtures.logger=t.fixtures.logger.child({orgId:e,runId:n,testId:r?.id});let{logger:l,controller:c}=t.fixtures,{onTestComplete:d,onTestSuccess:u,onTestFailure:m}=t.callbacks.test,p=aS(l);if(t.options.reinitializeBrowser){let h=await FS({browser:c.browser,signal:c.executeAbortController.signal});if(h.status!=="PASSED")return await d?.(),clearInterval(p?.interval),h}let g;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:r?.labels,orgSettings:t.inputs.orgSettings},`Starting run for Momentic test '${r?.name??"Unnamed test"}'`),g=await OI(t),g}finally{l.info({status:g?.status,labels:r?.labels},"Momentic test final result"),clearInterval(p?.interval),await d?.(),g?.status==="PASSED"?await u?.({steps:a,beforeSteps:i,afterSteps:s}):g?.status==="FAILED"&&await m?.({steps:a,beforeSteps:i,afterSteps:s})}};function LI({beforeStatus:t,mainStatus:e,afterStatus:n}){return t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var OI=async t=>{let{tracer:e}=t.testParams,{fromStep:n,toStep:r,steps:o,beforeSteps:a,afterSteps:i}=t.inputs,{logger:s,controller:l,context:c,storage:d}=t.fixtures,{collectDebugData:u,disableHealing:m}=t.options;c.setCurrentUrl(l.browser.url());let p="test",g=o,h=[],f=m||n!==void 0||r!==void 0||void 0,y={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},b=!1;n?.fromStepId&&n.fromStepId===r?.toStepId?(p="filtered step",y.fastForwardingToStep=!0):n?.fromStepId?(p="partial steps list from step",y.fastForwardingToStep=!0):r?p="partial steps list until step":(p="entire test",b=!0);let w,C;if(b&&a&&a.length>0){let _=await US(a,"beforeSteps",t);w=_.status,C=_.results}let v,R;if(w===void 0||w==="PASSED"){s.info({fromStep:n,toStep:r},`Starting execution of ${p}`);let _=await e.startMainStepList(),K=await mn({...t,work:y,listParams:{steps:g,containerName:p,results:h,tracer:_}});v=K.status,R=K.terminalResult}let x,M;if(b&&i&&i.length>0){let _=await US(i,"afterSteps",t);x=_.status,M=_.results}let D=LI({beforeStatus:w,mainStatus:v,afterStatus:x});return u&&NI({tracer:e,work:y,controller:l,storage:d,context:c,logger:s,status:D}),await Promise.allSettled(y.asyncTasks),y.asyncTasks.push(Promise.resolve(t.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:C,afterResults:M}))),D==="FAILED"?{status:"FAILED",results:h,beforeResults:C,afterResults:M,failedStepResult:R}:D==="CANCELLED"?{status:"CANCELLED",results:h,beforeResults:C,afterResults:M}:{status:"PASSED",failureRecoveryDetails:y.state.failureRecoveryAttempts?{attempts:y.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:C,afterResults:M}};async function US(t,e,n){let r=n.fixtures.logger,o=e==="beforeSteps"?await n.testParams.tracer.startBeforeStepList():await n.testParams.tracer.startAfterStepList();r.info(`Starting step execution for ${e}`);let a={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},i={...n.callbacks,test:{...n.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:s,results:l}=await mn({...n,work:a,callbacks:i,listParams:{steps:t,containerName:e,tracer:o}});await Promise.allSettled(a.asyncTasks);let c;return s==="SUCCESS"?c="PASSED":s==="CANCELLED"?c="CANCELLED":c="FAILED",{status:c,results:l}}function NI({tracer:t,work:e,controller:n,storage:r,logger:o,context:a,status:i}){let s=n.browser.retrieveAndClearDebugData(),l=Bh(s.logsPerPage),c=nd(s.harPages||{},s.harEntries||{});t.attachConsoleLogs({logger:o,logs:l}),t.attachNetworkLogs({logger:o,logs:c}),e.asyncTasks.push((async()=>{try{let d=await n.browser.screenshot({quality:75}),u=await RS({codePath:"test-complete-final",storage:r,screenshotBuff:d,logger:o}),m=await H(n.browser.html(),{milliseconds:2e3});a.setVariable(AS,u),i!=="PASSED"&&i!=="SUCCESS"&&(o.debug({finalPageHtml:m},"Final page state HTML"),o.debug({finalScreenshotUrl:u},"Uploaded final screenshot URL"))}catch{}})())}async function hl({settings:t,customHeaders:e,envVariables:n,envName:r,testName:o,baseUrl:a,logger:i,localTools:s,orgId:l}){let c=es.parse(t);e&&(c.extraHeaders={...c.extraHeaders,...e});let d=new Xt({baseUrl:a,envName:r,testName:o,variablesFromEnvironment:n,currentUrl:a});await ll({obj:c,context:d,bannedKeys:[],allowList:np,localTools:s,logger:i,orgId:l});try{return es.parse(c)}catch(u){throw new A("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${u.message}`)}}import{cloneDeep as jM}from"lodash-es";var BS={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[E.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var T={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=y(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=y(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=E.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch{}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:h}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&h===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return T.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||n?.parentNode,n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var R={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(R.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=A;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`// src/html/cache-evaluation.ts
36
+ ${C.feedback}`,m.status="FAILED",l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:m.message}),m;D&&l.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return m.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,m.status="FAILED",l.onDynamicAIActionEvaluatingEvent?.({stepId:D??e.id,status:"FAILED",message:m.message}),m}let k=setTimeout(()=>{l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);u.info({commandIndex:b,lastActionHint:E},`Generating new sub-command ${b} within AI action`);let q,$;try{({command:q,reasoning:$}=await a.promptToCommand({goal:p,history:f,startingScreenshot:h,disableCache:r?.advanced.disableAICaching??!1,logger:u,actionHint:E,langfuseSessionId:d})),u.info({command:q,reasoning:$},"Got proposed command")}finally{clearTimeout(k)}if(q.type==="FAILURE")return clearTimeout(k),m.status="FAILED",m.message=`Our AI agent determined that no supported actions can fulfill the goals: ${$}`,m;let _={id:ru(),type:"PRESET_ACTION",command:q},M={substepIndex:b+1,message:$||"Generated new command."};l.onDynamicCommandGenerated?.({...M,step:_,parentStepId:e.id}),u.info({commandId:q.id},`Executing sub-command ${b} within AI step: ${$n(q)}`);let z=await n.startSubSteps(),oe=(await t.executeStepList({...t,options:{...t.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[_],tracer:z}})).results[0];l.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await a.browser.waitForDOMStability({logger:u});let ke=await a.browser.screenshot({clearHighlights:!0,retries:1});m.results.push(oe),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${ke.toString("base64")}`,urlAfterCommand:a.browser.url(),serializedCommand:$n(q),elementInteracted:oe.results[0]?.elementInteracted,thoughts:$});let je={substepIndex:b,output:{...oe,message:oe.message??"Successfully executed preset action."},step:_,parentStepId:e.id};if(l.onDynamicCommandExecuted?.(je),await n.finish({output:Ji.parse(oe),step:oe,message:oe.message,attempt:1}),oe.status==="FAILED")if(m.status="FAILED",m.message=oe.message,y<3)y++,v=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${oe.message}`;else return m;else if(oe.status==="CANCELLED")return m.status="CANCELLED",m.message=oe.message,m;b++}};import{randomUUID as RI}from"crypto";var CI=3;async function LS(t){let{logger:e}=t.fixtures,{results:n}=t.failureRecoveryParams,r=n[n.length-1],o=AI(t.work,r);if(o)return e.info({failedResult:r,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};t.work.state.failureRecoveryAttempts=(t.work.state.failureRecoveryAttempts??0)+1;try{return await vI(t)}catch(a){return e.warn({err:a},"Error during failure recovery attempt, continuing..."),null}}async function vI(t){let{fixtures:e,work:n,failureRecoveryParams:r}=t,{controller:o,logger:a}=e,{testMetadata:i}=t.inputs,{results:s,failedStep:c,nextSteps:l,tracer:d}=r;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(n.asyncTasks??[]);let u=o.browser.url(),m=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,p=(await o.browser.getBrowserState({})).serialize(),{results:g}=await Qo(a,d,s,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=l.map(I=>gr(I)),f=i?.description?.trim(),b=i?.advanced?.failureRecoveryInstructions?.trim(),{scenario:y,thoughts:E,instructions:v}=await o.getFailureRecoveryPlan({currentUrl:u,currentScreenshot:m,failedResults:g,currentPageState:p,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:b||void 0});if(y!=="RECOVERABLE")return a.info({scenario:y,thoughts:E,instructions:v},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${E}`};if(!v)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let R={id:RI(),type:"AI_ACTION_DYNAMIC",text:v},C=await la(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures},listParams:{steps:[R,c],containerName:"AI-recovered step list",tracer:d}})),x=C.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(Ds({results:C.results,onPresetAction:I=>{I.aiSuggested=!0},onSimpleStepContainer:I=>{I.aiSuggested=!0}}),x.status==="SUCCESS"){let I=`The following steps were automatically executed by the failure recovery agent. Analysis: ${E}`;return x.message=I,a.info({thoughts:E},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:C,message:I}}else{let I=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${E}`;return x.message=I,a.info({thoughts:E,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:C,message:I}}return null}function AI(t,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let n=e.message;return n?n.includes("AbortError:")?"The user aborted the test":Jm.some(r=>n.includes(r))?"The failed step is an irrecoverable configuration error":(t.state.failureRecoveryAttempts??0)>CI?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as pl}from"crypto";import xI from"fast-json-patch";import{cloneDeep as II}from"lodash-es";async function OS(t){let e=t.failedResults,n=[],{sectionParams:r,fixtures:o,work:a,startingUrl:i,startingContextSnapshot:s,tracer:c}=t,{step:l}=r,{controller:d,logger:u}=o,m=l?.autohealingConfig,p=m?.restartBehavior??{type:"GO_TO_SECTION_START"},g=m?.attempts??1;for(let h=0;h<g;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=II(l.steps);await Promise.allSettled(a.asyncTasks??[]);let{results:b}=await Qo(u,c,e.results,{numStepsWithScreenshots:4}),y=await d.runSectionAutohealing({results:b,errorMessage:e.terminalResult?.message,goal:l.description});f=xI.applyPatch(f,y.patches).newDocument;let E=Jt.fromSnapshot({snapshot:s,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await PI({logger:u,controller:d,tracer:c,context:E,restartConfig:p,startingUrl:i});let v=await la(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures,context:E},listParams:{steps:f,containerName:"auto-healed step list",tracer:c}}));if(n.push(v.results),v.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:f},listResult:v,context:E},healingAttempts:n};e=v}return{healingAttempts:n}}async function PI({logger:t,controller:e,tracer:n,restartConfig:r,context:o,startingUrl:a}){switch(r.type){case"NAVIGATE_URL":{let i={id:pl(),type:"PRESET_ACTION",command:{id:pl(),type:"NAVIGATE",url:r.url}},s=await n.startStep({logger:t,step:i,attempt:1});await e.executePresetCommand(null,s,i.command,o,!1);break}case"GO_TO_SECTION_START":{let i={id:pl(),type:"PRESET_ACTION",command:{id:pl(),type:"NAVIGATE",url:a}},s=await n.startStep({logger:t,step:i,attempt:1});await e.executePresetCommand(null,s,i.command,o,!1);break}}}function NS(t,e){switch(t||(t="ON_FAILURE"),t){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Mm(e.command.type))}}async function kS(t){let{step:e,tracer:n}=t.sectionParams,{logger:r,controller:o,context:a}=t.fixtures,i=new Date,s=o.browser.url(),c=a.toObjectCopy(),l=await n.startSubSteps(),d=async()=>t.executeStepList({...t,listParams:{steps:e.steps,containerName:"section step list",tracer:l}}),u=e.autohealingConfig?await la(t.work,d):await d(),m,p;if(u.status==="FAILED"&&e.autohealingConfig&&!t.work.state.autoHealingDisabled&&NS(e.autohealingConfig.trigger,u.terminalResult)){let h=await n.startSubSteps(),f=await OS({...t,startingContextSnapshot:c,startingUrl:s,failedResults:u,tracer:h});f.successfulHealing&&(m=f.successfulHealing.proposedStep,u=f.successfulHealing.listResult,t.fixtures.context=f.successfulHealing.context),p=f.healingAttempts}let g={...e,...u,startedAt:i,finishedAt:new Date,proposedStep:m,healingAttempts:p};return In({asyncTasks:t.work.asyncTasks,nestedResults:u.results,result:g,logger:r}),g}var LI=60*60*1e3;async function gn(t){let{results:e=[],containerName:n,steps:r,tracer:o}=t.listParams,{logger:a}=t.fixtures,i=o.getParentStepIdChain(),{fromStep:s,toStep:c}=t.inputs,l=t.work,d="SUCCESS",u,m=0;for(m;m<r.length;m++){let p=r[m];if(p.skipped)continue;if(l.fastForwardingToStep&&s){let E=JSON.stringify(i);if(p.id===s.fromStepId&&E===JSON.stringify(s.parentStepIdChain))l.fastForwardingToStep=!1;else if(!Oh(p,i,s.fromStepId,s.parentStepIdChain))continue}let g=gr(p),h=0,f=1,b=Date.now();"retries"in p&&p.retries&&p.retries>0&&(f+=p.retries);let y;for(;h<f&&Date.now()-b<LI;){h++,a.info({step:p,currentAttempt:h},`Executing step ${m+1}/${r.length} in ${n}: ${g}`);let E=Date.now(),{stepResult:v,status:R,failureRecoveryResults:C,shouldStopExecuting:x}=await OI({attempt:h,params:t,step:p,i:m,steps:r,results:e,currentParentIdChain:i,work:l,fromStep:s,toStep:c,lastRetry:h===f});if(R==="FAILED"&&h<f){y=[...y??[],v],Date.now()-E<1e3&&await J(1e3-(Date.now()-E));continue}else e.push(v),y&&(v.previousAttempts=y);if(C&&e.push(...C),x)return d=R,u=v,{status:d,results:e,terminalResult:u};break}}return{status:d,results:e,terminalResult:u}}async function OI({attempt:t,params:e,step:n,i:r,steps:o,results:a,currentParentIdChain:i,work:s,fromStep:c,toStep:l,lastRetry:d}){let{tracer:u}=e.listParams,{logger:m,context:p,controller:g,codeEvalTools:h,billingReporter:f}=e.fixtures,{orgId:b}=e.inputs,y=new Date,E=await u.startStep({logger:m,step:n,attempt:t}),v=MI(n),R=p.toRedactedDisplayCopy(),C=g.browser.url(),x=g.executeAbortController.signal,I=Gc(n.type);s.asyncTasks.push(f.reportCreditsUsed(m,n.type,I,{testId:e.inputs.testMetadata?.id,testName:e.inputs.testMetadata?.name,suiteId:e.inputs.suiteMetadata?.id,suiteName:e.inputs.suiteMetadata?.name}));let D,k;switch(n.type){case"PRESET_ACTION":{D="Preset action",k=await lo(n,async()=>await ml({...e,presetParams:{tracer:E,step:n}}),x);break}case"AI_ACTION":{D="AI action",k=await lo(n,()=>IS({...e,aiStepParams:{step:n,tracer:E},executeStepList:gn}),x);break}case"AI_ACTION_DYNAMIC":{D="AI action",k=await lo(n,()=>MS({...e,aiStepParams:{step:n,tracer:E},executeStepList:gn}),x);break}case"RESOLVED_MODULE":{D=`Module (${n.name})`,k=await lo(n,async()=>{let z=await TS({orgId:b,step:n,context:p,logger:m,flagStore:g.flagStore,codeEvalTools:h,signal:x});return nu({...e,executeStepList:gn,moduleParams:{step:n,resolvedInputs:z,tracer:E}})},x);break}case"CONDITIONAL":{D="Conditional step",k=await lo(n,()=>AS({...e,conditionalParams:{step:n,tracer:E},executeStepList:gn}),x);break}case"SECTION":{D="Section",k=await lo(n,()=>kS({...e,sectionParams:{step:n,tracer:E},executeStepList:gn}),x);break}default:return(ue=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}k.beforeUrl=k.beforeUrl??C,k.beforeTestContext=R,n.envKey&&p.setVariable(n.envKey,k.data);let q=g.browser.url();p.setCurrentUrl(q),k.afterUrl=k.afterUrl??q,k.afterTestContext=p.toRedactedDisplayCopy(),await NI({startedAt:y,stepTypeName:D,result:k,callbacks:e.callbacks,globalWorkRef:e.work,tracer:E,attempt:t});let $,_;if(d&&k.status==="FAILED"&&!s.state.failureRecoveryDisabled&&c?.fromStepId===void 0&&l?.toStepId===void 0){let z=await LS({...e,executeStepList:gn,failureRecoveryParams:{failedStep:v,nextSteps:o.slice(r+1),results:a.concat(k),tracer:u}});z&&(z.type==="ATTEMPTED"?($=z.result.results,_=z.status):z.type==="NOT_ELIGIBLE"&&(k.message=k.message?`${k.message} ${z.message}`:z.message),k.type==="PRESET_ACTION"&&(k.failureRecoveryStatus={type:z.type,message:z.message}))}return s.fastForwardingToStep&&c&&(c.fromStepId===n.id&&JSON.stringify(i)===JSON.stringify(c.parentStepIdChain)&&(s.fastForwardingToStep=!1),n.type==="RESOLVED_MODULE"&&Ad(i,c.parentStepIdChain)&&(s.fastForwardingToStep=!1)),k.status!=="SUCCESS"&&_!=="SUCCESS"||g.closed?{shouldStopExecuting:!0,status:k.status,stepResult:k,failureRecoveryResults:$}:l&&n.id===l.toStepId&&JSON.stringify(i)===JSON.stringify(l.parentStepIdChain)?(g.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:k,failureRecoveryResults:$}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:k,failureRecoveryResults:$}}async function NI({stepTypeName:t,result:e,tracer:n,attempt:r}){let o=t.toLowerCase(),a=t.charAt(0).toUpperCase()+t.slice(1),i="";switch(e.status){case"SUCCESS":i=e.message??`${a} executed successfully.`;break;case"FAILED":i=e.message??`${a} failed.`;break;case"CANCELLED":i=e.message??`${a} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await n.finish({step:e,message:i,output:Ji.parse(e),attempt:r})}import{randomUUID as _S}from"crypto";async function DS({browser:t,signal:e}){let n=new Date;try{return await t.navigate({url:t.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(r){let o={id:_S(),type:"PRESET_ACTION",status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:r.message,startedAt:n,finishedAt:new Date,results:[],command:{id:_S(),type:"NAVIGATE",url:t.baseUrl}};return{status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var gl=async t=>{let{orgId:e,runId:n,testMetadata:r,suiteMetadata:o,steps:a,beforeSteps:i,afterSteps:s}=t.inputs;await t.fixtures.billingReporter.reportBillableEvent(t.fixtures.logger,"test-run",{eventId:n,testId:r?.id,testName:r?.name,suiteId:o?.id,suiteName:o?.name}),t.fixtures.logger=t.fixtures.logger.child({orgId:e,runId:n,testId:r?.id});let{logger:c,controller:l}=t.fixtures,{onTestComplete:d,onTestSuccess:u,onTestFailure:m}=t.callbacks.test,p=oS(c);if(t.options.reinitializeBrowser){let h=await DS({browser:l.browser,signal:l.executeAbortController.signal});if(h.status!=="PASSED")return await d?.(),clearInterval(p?.interval),h}let g;try{return c.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:r?.labels,orgSettings:t.inputs.orgSettings},`Starting run for Momentic test '${r?.name??"Unnamed test"}'`),g=await _I(t),g}finally{c.info({status:g?.status,labels:r?.labels},"Momentic test final result"),clearInterval(p?.interval),await d?.(),g?.status==="PASSED"?await u?.({steps:a,beforeSteps:i,afterSteps:s}):g?.status==="FAILED"&&await m?.({steps:a,beforeSteps:i,afterSteps:s})}};function kI({beforeStatus:t,mainStatus:e,afterStatus:n}){return t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var _I=async t=>{let{tracer:e}=t.testParams,{fromStep:n,toStep:r,steps:o,beforeSteps:a,afterSteps:i}=t.inputs,{logger:s,controller:c,context:l,storage:d}=t.fixtures,{collectDebugData:u,disableHealing:m}=t.options;l.setCurrentUrl(c.browser.url());let p="test",g=o,h=[],f=m||n!==void 0||r!==void 0||void 0,b={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},y=!1;n?.fromStepId&&n.fromStepId===r?.toStepId?(p="filtered step",b.fastForwardingToStep=!0):n?.fromStepId?(p="partial steps list from step",b.fastForwardingToStep=!0):r?p="partial steps list until step":(p="entire test",y=!0);let E,v;if(y&&a&&a.length>0){let k=await FS(a,"beforeSteps",t);E=k.status,v=k.results}let R,C;if(E===void 0||E==="PASSED"){s.info({fromStep:n,toStep:r},`Starting execution of ${p}`);let k=await e.startMainStepList(),q=await gn({...t,work:b,listParams:{steps:g,containerName:p,results:h,tracer:k}});R=q.status,C=q.terminalResult}let x,I;if(y&&i&&i.length>0){let k=await FS(i,"afterSteps",t);x=k.status,I=k.results}let D=kI({beforeStatus:E,mainStatus:R,afterStatus:x});return u&&DI({tracer:e,work:b,controller:c,storage:d,context:l,logger:s,status:D}),await Promise.allSettled(b.asyncTasks),b.asyncTasks.push(Promise.resolve(t.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:v,afterResults:I}))),D==="FAILED"?{status:"FAILED",results:h,beforeResults:v,afterResults:I,failedStepResult:C}:D==="CANCELLED"?{status:"CANCELLED",results:h,beforeResults:v,afterResults:I}:{status:"PASSED",failureRecoveryDetails:b.state.failureRecoveryAttempts?{attempts:b.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:v,afterResults:I}};async function FS(t,e,n){let r=n.fixtures.logger,o=e==="beforeSteps"?await n.testParams.tracer.startBeforeStepList():await n.testParams.tracer.startAfterStepList();r.info(`Starting step execution for ${e}`);let a={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},i={...n.callbacks,test:{...n.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:s,results:c}=await gn({...n,work:a,callbacks:i,listParams:{steps:t,containerName:e,tracer:o}});await Promise.allSettled(a.asyncTasks);let l;return s==="SUCCESS"?l="PASSED":s==="CANCELLED"?l="CANCELLED":l="FAILED",{status:l,results:c}}function DI({tracer:t,work:e,controller:n,storage:r,logger:o,context:a,status:i}){let s=n.browser.retrieveAndClearDebugData(),c=Uh(s.logsPerPage),l=ed(s.harPages||{},s.harEntries||{});t.attachConsoleLogs({logger:o,logs:c}),t.attachNetworkLogs({logger:o,logs:l}),e.asyncTasks.push((async()=>{try{let d=await n.browser.screenshot({quality:75}),u=await ES({codePath:"test-complete-final",storage:r,screenshotBuff:d,logger:o}),m=await j(n.browser.html(),{milliseconds:2e3});a.setVariable(vS,u),i!=="PASSED"&&i!=="SUCCESS"&&(o.debug({finalPageHtml:m},"Final page state HTML"),o.debug({finalScreenshotUrl:u},"Uploaded final screenshot URL"))}catch{}})())}async function hl({settings:t,customHeaders:e,envVariables:n,envName:r,testName:o,baseUrl:a,logger:i,localTools:s,orgId:c}){let l=es.parse(t);e&&(l.extraHeaders={...l.extraHeaders,...e});let d=new Jt({baseUrl:a,envName:r,testName:o,variablesFromEnvironment:n,currentUrl:a});await ll({obj:l,context:d,bannedKeys:[],allowList:tp,localTools:s,logger:i,orgId:c});try{return es.parse(l)}catch(u){throw new A("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${u.message}`)}}import{cloneDeep as KM}from"lodash-es";var US={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[E.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var T={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=y(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=y(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=E.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch{}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:h}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&h===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return T.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||n?.parentNode,n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var R={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(R.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=A;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`// src/html/cache-evaluation.ts
37
37
  function isEligibleForAttrRemoval(bestCandidate, attrToRemove) {
38
38
  const customWindow = window;
39
39
  if (bestCandidate.textContent?.trim()) {
@@ -3688,9 +3688,7 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
3688
3688
  if (nYCoordsToCheck % 2 === 0) {
3689
3689
  nYCoordsToCheck += 1;
3690
3690
  }
3691
- logs.push(
3692
- \`Checking \${nXCoordsToCheck} x \${nYCoordsToCheck} points on original element\`
3693
- );
3691
+ logs.push(\`Checking \${nXCoordsToCheck} x \${nYCoordsToCheck}\`);
3694
3692
  const xStep = boundingBox.width / (nXCoordsToCheck - 1);
3695
3693
  const yStep = boundingBox.height / (nYCoordsToCheck - 1);
3696
3694
  const candidateElements = [];
@@ -3777,7 +3775,7 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
3777
3775
  };
3778
3776
  }
3779
3777
  if (originalElementFound) {
3780
- logs.push(\`A visible point on the original element was found\`);
3778
+ logs.push(\`Visible point on original found\`);
3781
3779
  } else {
3782
3780
  logs.push(
3783
3781
  \`Found \${candidateElements.length} candidates that are not the original element\`
@@ -3788,7 +3786,7 @@ function findVisibleMomenticIdAndPoint(documentRoot, originalElement, logs) {
3788
3786
  originalElement
3789
3787
  );
3790
3788
  logs.push(
3791
- \`Suggesting specific click point (\${mostCommonCandidate.point.x}, \${mostCommonCandidate.point.y}) on element: \${mostCommonCandidate.element.outerHTML.slice(0, 100)}\`
3789
+ \`Suggesting specific click point (\${mostCommonCandidate.point.x}, \${mostCommonCandidate.point.y}) on element: \${mostCommonCandidate.element.outerHTML.slice(0, 300)}\`
3792
3790
  );
3793
3791
  return {
3794
3792
  foundElement: mostCommonCandidate.element,
@@ -3885,34 +3883,34 @@ function registerAllMomenticListeners() {
3885
3883
 
3886
3884
  // src/html/index.ts
3887
3885
  registerAllMomenticListeners();
3888
- `};var qn={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"]};var zS="BoundingBoxMovedError",HS="ZeroOpacityError",fl="visual_actions",Kn="data-momentic-id";function $S(t,e,n){if(t.length<n)return t;let r=t.indexOf(e);if(r===-1)return t;let o=Math.max(0,r-n/3),a=Math.min(r+n/3,t.length),i=t.indexOf(`
3889
- `,o);i>0&&i<r&&(o=i);let s=a,l=0;for(;l<1e3&&s>r&&t[s]!==`
3890
- `;)l++,s--;return s>r&&t[s]===`
3891
- `&&(a=s),t.slice(o,a)}function pn(t){let e=typeof t=="string"?t:t.toString();return`[${Kn}="${e}"]`}import{execSync as iM}from"child_process";import{randomUUID as Lu}from"crypto";import{diff as Ou}from"deep-object-diff";import{existsSync as Il,mkdirSync as sM,readFileSync as lM,writeFileSync as cM}from"fs";import{Jimp as Gy}from"jimp";import dM from"js-beautify";import{cloneDeep as yi}from"lodash-es";import uM from"mime";import{homedir as ku,hostname as mM,platform as pM}from"os";import{basename as gM,extname as hM,join as ua,resolve as fM}from"path";import{chromium as Vy,devices as SM}from"playwright";import{addExtra as yM}from"playwright-extra";import bM from"puppeteer-extra-plugin-recaptcha";import{v4 as TM}from"uuid";import{rmSync as cy}from"fs";import{basename as oP,join as aP}from"path";import{errors as iP}from"playwright-core";var jS=new Set(["about:blank","chrome-error://chromewebdata/"]);var iu=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],su=1e4,fi=500;import{mkdirSync as _I,rmSync as GS,statSync as DI}from"fs";import*as uu from"node:fs";import FI from"nodejs-file-downloader";import{tmpdir as UI}from"os";import br,{basename as BI,dirname as zI}from"path";var mu="file://",du=br.join(UI(),"momentic","downloads"),cu=1e4,HI=50*1024*1024;async function WS(t){let{uri:e}=t;return e.startsWith(mu)?jI(t):e.startsWith("http")?WI(t):GI(t)}function $I(t,e){let n=br.join(du,t,e.slice(mu.length)),r=br.join(du,t),o=n.startsWith(r);if(!uu.existsSync(n)||!o)throw new A("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return n}async function jI({uri:t,orgId:e}){let n=$I(e,t);return{filePath:n,cleanup:()=>{GS(zI(n),{recursive:!0,force:!0})}}}async function GI({uri:t}){let e=br.resolve(t);if(!uu.existsSync(e))throw new A("UserConfigurationError",`The referenced file (${t}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function WI({uri:t,logger:e,orgId:n}){let r=new URL(t);r.search&&(r.search="");let o=BI(r.href),a=gu(o),i=br.extname(a);if(og.includes(i))throw new Error(`Downloading files with extension ${i} is not allowed.`);let s=pu(n),l=new FI({url:t,fileName:a,directory:s,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:cu}),{downloadStatus:c,filePath:d}=await H(l.download(),{milliseconds:cu,message:`Download timed out after ${cu}ms`});if(c!=="COMPLETE")throw new Error(`Download ended in non-success status: ${c}`);if(!d)throw new Error("File path of successfully downloaded file was empty");let m=DI(d).size;if(m>HI)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:d,fileName:a},"Downloaded file to disk");let p;return{filePath:d,cleanup:()=>{clearTimeout(p),p=setTimeout(()=>GS(s,{recursive:!0,force:!0}),10*60*1e3)}}}function VS(t,e){return`${mu}${t}/${e}`}function pu(t){let e=Math.random().toString(36).substring(4),n=br.join(du,t,e);return _I(n,{recursive:!0}),n}function gu(t){let e=br.extname(t),n=br.basename(t,e);return t=(n.length>100?n.slice(n.length-100):n)+e,t=t.trim().replaceAll(" ","_"),t}async function Yn(t,e){try{return await t.evaluate(r=>window.serializeElementOnlyWithText?.(r,{truncateToLength:500}),void 0,{timeout:1e3})}catch(n){e.debug({err:n},"Failed to get HTML from locator for Playwright error translation");return}}async function qS(t,e){let n=t.evaluate(async()=>{let a=window,i={};try{let s=await indexedDB.databases();for(let l of s){if(!l.name)continue;let c=await a.exportIdbToObject?.(l.name,l.version);c&&(i[l.name]=c)}return[i,void 0]}catch(s){return[void 0,s.message]}}),[r,o]=await H(n,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),r}async function KS(t,e,n){if(e){n.debug("Importing indexedDB data");try{let r=t.evaluate(async o=>{let a=window;for(let[i,s]of Object.entries(o))await a.importObjectToIdb?.(i,s)},e);await H(r,{milliseconds:3e3})}catch(r){n.warn({err:r},"Failed to import indexedDB data")}}}async function YS(t,e){try{let n=t.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(r=>{r.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await H(n,{milliseconds:3e3})}catch(n){e.debug({err:n},"Failed clearing index db data, continuing...")}}async function XS(t,e,n,r,o){try{await VI(t,e,n,r)}catch(a){o.error({err:a,tabIndex:e},"Error handling new console log")}}async function VI(t,e,n,r){let o=r.text();o.length>fi&&(o=o.slice(0,fi)+"...(TRUNCATED)");let a=[];for(let i of r.args())try{let s=await i.jsonValue(),l=JSON.stringify(s);l.length>fi?a.push(l.slice(0,fi)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&a.push(s)}catch{}hu(t,n,e,{url:t.url(),location:r.location(),type:r.type(),text:r.text(),args:a})}function hu(t,e,n,r){let o=Date.now(),a=e.logsPerPage;if(a.length<=n||a[n]===void 0){a[n]=[];for(let i=0;i<n;i++)a[i]===void 0&&(a[i]=[])}a[n].length>su&&(a[n]=a[n].slice(Math.floor(su/2)),a[n]?.push({url:t.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:n})),a[n].push({...r,tabIndex:n,timestamp:o})}async function on({fn:t,codePath:e,logObject:n,signal:r,logger:o}){r?.throwIfAborted();let a=Date.now(),i=await ai({promiseGenerator:t,signal:r,codePath:e,logger:o}),s=Date.now();return n[e]=s-a,i}var qI="[redacted due to size]",KI=1e4;async function QS(t,e,n){let r=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[t]={id:t,startedDateTime:r,title:void 0,pageTimings:{}}}async function fu(t,e){let n=e.timing(),r=new URL(e.url()),o=[...r.searchParams.entries()].map(([s,l])=>({name:s,value:l})),a={...await ey(e),url:r.toString(),method:e.method(),queryString:o,postData:await XI(e)};return{pageref:t,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:a,timings:ty(n).timings}}async function ZS(t,e,n){await n.finished();let r={};try{r=await JI(n)}catch{}let o={...await ey(n),status:n.status(),statusText:n.statusText(),content:r,redirectURL:n.headers().location};t.response=o;let a;try{a=await e.sizes(),t.request.bodySize=a.requestBodySize,t.request.headersSize=a.requestHeadersSize}catch{}t.response&&a&&(t.response.bodySize=a.responseBodySize,t.response.headersSize=a.responseHeadersSize,t.response.content.size=a.responseBodySize);let i=e.timing();t.startedDateTime=new Date(i.startTime).toISOString();let{timings:s,total:l}=ty(i);t.time=l,t.timings=s}function Si(t,e,n){t.harEntries||(t.harEntries={}),t.harEntries[n]=e}function JS(t){try{return new Date(t).toISOString()}catch{return}}function YI(t){let e={name:"",value:""},n=!0;for(let r of t.split(/; */)){let o=r.indexOf("="),a=o!==-1?r.substring(0,o).trim():r.trim(),i=o!==-1?r.substring(o+1,r.length).trim():"";if(n){n=!1,e.name=Ln(a),e.value=Ln(i);continue}a==="Domain"&&(e.domain=Ln(i)),a==="Expires"&&(e.expires=JS(i)),a==="HttpOnly"&&(e.httpOnly=!0),a==="Max-Age"&&(e.expires=JS(Date.now()+ +i*1e3)),a==="Path"&&(e.path=Ln(i)),a==="Secure"&&(e.secure=!0)}return e}async function ey(t){let e=await t.allHeaders(),n=e.cookie?.split(";").map(YI)??[];return{headers:Object.entries(e).map(([r,o])=>({name:Ln(r),value:Ln(o)})),cookies:n}}async function XI(t){let e=t.postData();if(!e)return;let n=await t.headerValue("content-type"),r={mimeType:n??"application/octet-stream",text:Ln(e),params:[]};if(n==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[a,i]of o.entries())r.params.push({name:Ln(a),value:i?Ln(i):void 0})}return r}async function JI(t){return{mimeType:await t.headerValue("content-type")??void 0,text:Ln(await t.text()),encoding:await t.headerValue("content-encoding")??void 0}}function Ln(t){return t.length>KI?qI:t}function co(t){return t<0?0:t}function ty(t){return{timings:{blocked:co(t.domainLookupStart),dns:co(t.domainLookupEnd-t.domainLookupStart),connect:co(t.connectEnd-t.connectStart),send:co(t.responseStart-t.requestStart),wait:0,receive:co(t.responseEnd-t.responseStart),ssl:co(t.connectEnd-t.secureConnectionStart)},total:co(t.responseEnd)}}function ny(){return async t=>{let{fragment:e,code:n,context:r}=t,{env:o}=r||{},a=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new a("env",e?`return ${n}`:n)(o))}}}async function Qe({root:t,fn:e,arg:n,timeout:r,waitForPageLoad:o,codePath:a}){return await o(),await H(t.evaluate(e,n),{milliseconds:r,message:`Timed out ${a} after ${r}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function Su(){return window.lastCursorPos}import{errors as QI}from"playwright-core";async function uo({func:t,action:e,logger:n,callbacks:r,retryTimeoutMs:o,targetingResult:a}){let i=Date.now(),s;for(;Date.now()-i<o;)try{return await t(a)}catch(l){let c=l;if(Ga(c)){n.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[d]=await Promise.all([t(a),r.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return d}else if(c instanceof QI.TimeoutError)n.warn({err:c,rootUrl:(await r.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await ZI(c,a.locator,r,n);else throw c}throw s instanceof A?s:new A("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function ZI(t,e,n,r){return t.message.includes("attempt #")?eP(t,e,n,r):tP(t)}async function eP(t,e,n,r){let o=t.message.split(/- retrying \w+ action, attempt #\d+/).filter(l=>l.length>0);if(!o.length)return r.warn({err:t},"Failed to parse Playwright error message for translation, returning raw message"),t;let a=o.length>2?o[o.length-2]:o[0];a=a.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3892
- `,";").replace(/\s+/g," ");let i="",s=await Yn(e,r);if(s&&(i=`Target element HTML: ${$e(s,100,!0)}`),a.includes("element is not enabled"))return new A("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${i}`,{errOptions:{cause:t}});if(a.includes("intercepts pointer events")){let l="",c=a.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(c){let d=(await n.state.getRoot()).locator(pn(c)),u=await Yn(d,r);u&&(l=`Covering element HTML: ${$e(u,100,!0)}`)}return new A("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${i}
3893
- ${l}`,{errOptions:{cause:t}})}if(a.includes("element is not visible")){let l="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let c=await e.boundingBox({timeout:3e3});c?c.height===0?l="The element you attempted to interact with has zero height.":c.width===0&&(l="The element you attempted to interact with has zero width."):l="The element you attempted to interact with has no bounding box."}catch{}return new A("ActionFailureError",`${l} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${i}`,{errOptions:{cause:t}})}return a.includes("element is outside of the viewport")?new A("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${i}`):t}function tP(t){let e=t.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new A("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:t}});return t}async function ry(t){try{return await nP(t)}catch(e){t.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function nP({locator:t,logger:e}){let[n,r]=await t.evaluate(l=>[l.id,l.tagName.toLowerCase()],{timeout:1e3}),o=await Yn(t,e),a=await t.boundingBox({timeout:1e3});if(a===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(a.width>5||a.height>5||r!=="input")return;if(n)try{let l=t.page().locator(`label[for=${JSON.stringify(n)}]`);return await l.waitFor({state:"visible",timeout:1e3}),{locator:l,relativePoint:void 0}}catch{}let i=await t.evaluate(l=>{let c=window,d=l.parentElement;if(!d)return{type:"error",error:"Input click target has no parent for redirection"};let u=l.getBoundingClientRect(),m=d.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let p={x:Math.min(Math.max(1,u.left-m.left),m.width-1),y:Math.min(Math.max(1,u.top-m.top),m.height-1)},g=c._MOMENTIC_FEATURE_FLAGS?.[fl],h=l.getAttribute(Kn),f=!g&&h?pn(h):c.getMPath?.(l)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,serializedForm:d.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(i.type==="error")throw new Error(i.error);let s=t.page().locator(i.selector);return await s.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:i,originalElementDisplayString:o},`Redirected click to parent element with selector: ${i.selector}`),{locator:s,relativePoint:i.relativePoint}}var ay=["date","datetime-local","month","time","week"],oy={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function iy(t){try{await H(rP(t),{milliseconds:3e3})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function rP({root:t,text:e,options:n,logger:r,callbacks:o}){let a=(await Qe({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!oy[a])return;oy[a].test(e)&&r.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),n.clearContent=!1,r.info("Transforming datetime input to use sequential key presses")}import{z as Ft}from"zod";var sy=Ft.object({doubleClick:Ft.boolean().optional(),rightClick:Ft.boolean().optional(),force:Ft.boolean().optional(),waitForDownload:Ft.boolean().optional(),delayMs:Ft.number().optional(),downloadTimeoutMs:Ft.number().optional(),relativePosition:Ft.object({x:Ft.number(),y:Ft.number()}).optional()}),$ee=Ft.object({repeat:Ft.number().optional(),convertMeta:Ft.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Ft.number().optional()});async function Sl({locator:t,callbacks:e,logger:n,timeoutMs:r=1e3}){try{await yu(e,r);let o=t.evaluate(a=>{let i=window;i.momenticIsEligible=u=>{let p=window.getComputedStyle(u,null).getPropertyValue("display");if(p==="none"||p==="contents")return!1;let g=u.getBoundingClientRect();return!(!g.height||!g.width)},i.removeHighlightTimers=i.removeHighlightTimers||[],i.removeHighlightFunctions=i.removeHighlightFunctions||{};let s=0;for(;!i.momenticIsEligible(a)&&s<3;){if(!a.parentElement)throw new Error("No eligible non-empty parent found for highlighting");a=a.parentElement,s++}let l=a.style.getPropertyValue("outline"),c=a.style.getPropertyPriority("outline");a.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let d=`momentic${Math.floor(Math.random()*1e7)}`;i[d]=()=>{a.style.removeProperty("outline"),a.style.setProperty("outline",l,c),a.getAttribute("style")||a.removeAttribute("style")},i.removeHighlightTimers.push(setTimeout(()=>{i[d](),i.removeHighlightFunctions?.[d]&&delete i.removeHighlightFunctions[d]},5e3)),i.removeHighlightFunctions[d]=i[d]},void 0,{timeout:r});return await H(o,{milliseconds:r}),!0}catch(o){return n.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function yu(t,e=1e3){let n=await t.state.getRoot();await Qe({root:n,fn:()=>{let o=window,a=o.removeHighlightTimers||[];for(;a.length;){let i=a.pop();clearTimeout(i)}Object.values(o.removeHighlightFunctions??{}).forEach(i=>{i()})},timeout:e,arg:void 0,waitForPageLoad:t.waitForPageLoad,codePath:"removing element highlights"})}async function bu(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return uo({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async n=>dy({...t,targetingResult:n,useVisualClick:e})})}async function sP(t,e){let{redirectionAttempts:n=0}=e;if(n>=2)throw t;try{return await lP(t,e)}catch(r){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t):r}}async function lP(t,e){let{logger:n,redirectionAttempts:r=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let a=await o.getAttribute("id",{timeout:1e3});if(!a)throw t;let i=o.page().locator(`[for=${JSON.stringify(a)}]`);return await i.waitFor({state:"visible",timeout:1e3}),n.warn({err:t},"Attempting locator redirection due to input being covered by label"),dy({...e,targetingResult:{locator:i},redirectionAttempts:r+1})}else throw n.error({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function cP(t){let{browserCallbacks:e,logger:n,targetingResult:r,position:o,options:a}=t,i=await e.state.getRoot(),s=i&&i!==r.locator.page()&&"frameElement"in i?await i.frameElement():null,l;try{l=s?await to({promiseGenerator:async()=>s.boundingBox(),timeoutMs:3e3,logger:n}):null}catch(g){throw new A("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await s?.dispose()}let c=Date.now(),{clickX:d,clickY:u,reason:m}=await mP({frameCoordinates:l,logger:n,targetingResult:r,position:o,options:a}),p=sy.safeParse(a);n.info({frameCoordinates:l,position:o,options:p.success?p.data:void 0,clickLocation:{clickX:d,clickY:u,reason:m},duration:Date.now()-c},"Visual click")}async function dP(t){let{actionSource:e,targetingResult:n,options:r,logger:o}=t,a=t.targetingResult.locator,i=r?.relativePosition??t.position;if(e==="click"&&!i){let l=await ry({locator:a,logger:o});l&&(a=l.locator,i=l.relativePoint??i)}let s=r?.force||n.hints?.force||!1;try{r?.doubleClick?await a.dblclick({button:r.rightClick?"right":"left",timeout:3e3,position:i,delay:r?.delayMs??25,force:s}):await a.click({button:r?.rightClick?"right":"left",timeout:3e3,position:i,delay:r?.delayMs??25,force:s})}catch(l){let c=l;if(gP(c))o.warn({err:c},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:c},"Error clicking on locator, attempting to recover..."),sP(c,{...t,targetingResult:{...a,locator:a}})}}async function dy(t){let{options:e,logger:n,browserCallbacks:r,controllerCallbacks:o,useVisualClick:a,targetingResult:i}=t,s;e?.waitForDownload&&(s=(async()=>{let l=e.downloadTimeoutMs??3e4;try{return await i.locator.page().waitForEvent("download",{timeout:l})}catch(c){return c instanceof iP.TimeoutError?new A("ActionFailureError",`Download did not complete in ${l}ms`):new A("ActionFailureError",`Download failed: ${c.message}`)}})());try{await Sl({locator:i.locator,callbacks:r,logger:n,timeoutMs:1e3})}catch(l){n.warn({err:l},"Error highlighting locator in click, continuing...")}if(a?await cP(t):await dP(t),e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new A("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");n.info("Waiting for download to start and complete");let l=await H(s,{milliseconds:e.downloadTimeoutMs??3e4});if(l instanceof Error)throw l;return{downloadedFile:await pP(l,o.createIsolatedFolder,n)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function uP(t,e){if(e.hints?.clickableXY){let a=(t?.x??0)+e.hints.clickableXY.x,i=(t?.y??0)+e.hints.clickableXY.y;return[{x:a,y:i},"targeting hint"]}let n=await e.locator.boundingBox({timeout:3e3});if(!n)throw new A("ActionFailureError","Element does not have a bounding box");let r=n.x+n.width/2,o=n.y+n.height/2;return[{x:r,y:o},"halfway point of the bounding box"]}async function mP({frameCoordinates:t,logger:e,options:n,targetingResult:r,position:o}){let a,i,s;if(o){let u=await r.locator.boundingBox({timeout:3e3});a=(t?.x??0)+(u?.x??0)+o.x,i=(t?.y??0)+(u?.y??0)+o.y,s="predefined position"}else{let[u,m]=await uP(t,r);a=u.x,i=u.y,s=m}let l=r.locator.page(),c=n?.rightClick?"right":"left",d=n?.delayMs??25;return n?.doubleClick?await l.mouse.dblclick(a,i,{button:c,delay:d}):await l.mouse.click(a,i,{button:c,delay:d}),{clickX:a,clickY:i,reason:s}}async function pP(t,e,n){n.info("Download detected, saving file to disk");let r=await t.path(),o=gu(t.suggestedFilename()),a=e();await t.saveAs(aP(a,o)),cy(r,{force:!0}),setTimeout(()=>{cy(a,{recursive:!0,force:!0})},5*60*1e3);let i=VS(oP(a),o);return n.info({uri:i,downloadFolder:a},"Saved download to isolated folder"),i}function gP(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as hP}from"os";var fP={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function SP(){let t=hP();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function uy(t){return JSON.stringify(t.split("+").sort())}function yl(t){let e=SP(),n=uy(t);for(let r of Object.values(fP))if(Object.values(r).some(o=>uy(o)===n))return r[e];return process.platform==="darwin"?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function Tu({frame:t,page:e,deltaX:n,directionX:r,deltaY:o,directionY:a,signal:i,callbacks:s,logger:l}){if(!n&&!o)return;let c=r==="left"?-1:1,d=a==="up"?-1:1;if(t)await Qe({root:t,fn:([u,m,p,g])=>window.scrollTo(window.scrollX+(u??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[n,o,c,d],waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let u=e.viewportSize()||Nt,m=await Qe({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[p,g,h]=await Qe({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let y=f.getBoundingClientRect();return[f.scrollTop,y.x,y.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((n??u.width)*c,(o??u.height)*d);try{let f=Date.now();for(;Date.now()-f<2e3;){i?.throwIfAborted();let y=await H(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[b,w,C]=await H(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let R=v.getBoundingClientRect();return[v.scrollTop,R.x,R.y]}),{milliseconds:1e3});if(y===m&&b===p&&w===g&&C===h)break;m=y,p=b,g=w,h=C,await J(500)}}catch(f){l.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function wu(t,e){let n,r;for(let o=0;o<4;o++)try{return n=t.pages(),await Promise.all(n.map(async a=>{let i="";try{i=e?.getTitles?await a.title():""}catch{i="Unknown page"}return{title:i,url:a.url()}}))}catch(a){r=a,await J(500)}throw new Error(`Failed to get tab titles after all retries: ${r?.message}`)}import{randomUUID as AP}from"crypto";import{cloneDeep as Ru}from"lodash-es";function Tr(t,e){let n=t.findIndex(r=>r===e);if(!(n===-1||!t[n+1]))return t[n+1]}import{createHash as yP}from"crypto";var bP="v1";function bl(t,e){if(t.tagName.toLowerCase()==="svg"&&!wP(t))try{let n=my(t,e),r=TP(JSON.stringify(n));return{version:bP,json:n,hash:r}}catch{return}}function TP(t){return yP("md5").update(t).digest("hex")}function my(t,e){let n=t.tagName.toLowerCase(),r=EP(t);if(n==="image"&&r["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:n,props:r,children:[]};for(let a of t.childrenBackendIds){let i=e.backendIdToNode[a];if(i&&i.nodeType===1){let s=my(i,e);s&&o.children.push(s)}}return o}function wP(t){let e=t.computedStyles.display,n=t.computedStyles.visibility,r=t.computedStyles.opacity;return e==="none"||n==="hidden"||r==="0"}function EP(t){let e={},n=t.attributes;for(let r of Object.keys(n))qn.visualAttributesForSvgSerialization.includes(r)&&(e[r]=n[r]);return n.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=n.id),e}var mo={r:147,g:196,b:125,a:.55},gy={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:mo,paddingColor:mo,borderColor:mo,marginColor:mo,eventTargetColor:mo,shapeColor:mo,shapeMarginColor:mo,showInfo:!0,showAccessibilityInfo:!0},Tl=["display","opacity","visibility","height","position"];function hy({snapshot:t,devicePixelRatio:e,logger:n}){let r=t.strings,o=t.documents,a={},i={},s={roots:[],backendIdToNode:a,frameIndexToIframeNode:i};return o.forEach((l,c)=>{let d=RP({allDocuments:o,stringConstants:r,frameIndex:c,devicePixelRatio:e,backendIdToNode:a,frameIndexToIframeNode:i,logger:n});s.roots.push(d)}),s}function RP({allDocuments:t,stringConstants:e,devicePixelRatio:n,frameIndex:r,frameIndexToIframeNode:o,backendIdToNode:a,logger:i}){let s=t[r],l=s.layout,c={};l.nodeIndex.forEach((R,x)=>{c[R]=x});let d=l.styles,u=l.bounds??[],m=s.nodes,p=m.contentDocumentIndex??{index:[],value:[]},g=m.backendNodeId??[],h=m.attributes??[],f=m.parentIndex??[],y=m.nodeName??[],b=m.nodeType??[],w=m.pseudoType??{index:[],value:[]},C=m.inputChecked??{index:[]},v=e[s.frameId];for(let R=0;R<g.length;R++){let x=g[R],M=b[R],D=h[R]??[],_=f[R]!==void 0&&f[R]>=0?f[R]:void 0,K=_!==void 0?g[_]:void 0,P=K!==void 0?a[K]:void 0,W=w.index.indexOf(R),k=W!==-1?e[w.value[W]]:void 0,G=c[R],we;G?we=u[G]??[]:we=[];let Ce=y[R]!==void 0?e[y[R]]?.toLowerCase():void 0;if(!Ce){i.warn({backendNodeId:x,frameId:v,frameIndex:r,nodeBounds:we},"DOM node has no tag name");continue}let be={backendNodeId:x,psuedoType:k,nodeType:M,frameIndex:r,parentFrameId:v,ownedFrameId:void 0,bounds:{x:we[0]??null,y:we[1]??null,width:we[2]??null,height:we[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:K??null,tagName:Ce,parent:P??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};P&&P.childrenBackendIds.push(x);let wt=p.index.indexOf(R);if(wt!==-1){let de=p.value[wt];o[de]=be;let oe=t[de]?.frameId;be.ownedFrameId=oe!==void 0?e[oe]:void 0}for(let de of Object.keys(be.bounds)){let oe=de;be.bounds[oe]!==null&&(be.bounds[oe]/=n)}let Sn=G!==void 0?d[G]??[]:[];for(let de=0;de<Sn.length&&!(de>=Tl.length);de++){let oe=Sn[de];if(oe===void 0||isNaN(oe))continue;let ot=e[oe];if(ot===void 0)continue;let Pe=Tl[de];be.computedStyles[Pe]=ot}for(let de=0;de<D.length;de+=2){let oe=D[de],ot=D[de+1];if(!oe||!ot)continue;let Pe=e[oe],_n=e[ot];!Pe||!_n||(be.attributes[Pe]=_n)}C.index.includes(R)&&(be.attributes.checked="true"),a[be.backendNodeId]=be}return a[g[0]]}function Eu(t,e){if(t.mPathSelector)return t.mPathSelector;let n=t.parent,r;if(!n)r=t.tagName;else if(t.tagName==="body")r="body";else{let a=n.childrenBackendIds.filter(l=>e.backendIdToNode[l]?.nodeType===1&&!e.backendIdToNode[l]?.psuedoType).indexOf(t.backendNodeId),i=` > ${t.tagName}:nth-child(${a+1})`;r=`${Eu(n,e)}${i}`}return t.mPathSelector=r,r}function py(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var CP=["html","#document","#document-fragment"];function fy({node:t,domGraph:e}){let n=[],r=t,o=py(t,e);if(!o)return[t.tagName];let a=()=>{if(r=o,o=py(o,e),!o&&r.frameIndex!==0)throw new Error("No parent node but not in main frame")},i=0;for(;o&&i<1e6;){if(i++,CP.includes(r.tagName)){a();continue}if(r.tagName==="body")n.push("body");else{let l=!1,c=1;for(let d=0;d<o.childrenBackendIds.length;d++){let u=o.childrenBackendIds[d],m=e.backendIdToNode[u];if(u===r.backendNodeId){n.push(`${r.tagName}:nth-child(${c})`),l=!0;break}else m?.nodeType===1&&!m.psuedoType&&c++}if(!l)throw new Error(`Could not find child (${r.tagName}) in parent's children list (${o.tagName})`)}a()}return n.reverse()}function Sy(t,e){let n=t.locator("html"),r=[];for(let o=0;o<e.length;o++){let a=e[o];if(r.push(a),a.startsWith("iframe")){let i=r.join(" > ");r=[],o<e.length-1?n=n.frameLocator(i):n=n.locator(i)}}if(r.length&&(n=n.locator(r.join(" > "))),"owner"in n)throw new Error("Final locator from mpath is a frame locator");return n}async function yy(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:n.nodeId},timeout:2e3})).attributes,a=Tr(o,Kn);if(!a)throw new Error(`Could not find attribute ${Kn} for object ${e}`);return a}function by(t){let e=[];for(let n=0;n<t.domGraph.roots.length;n++){let r=t.domGraph.roots[n],o=vP({root:r,domGraph:t.domGraph,existingHashes:t.existingHashes,flagStore:t.flagStore,logger:t.logger});e=e.concat(o)}return e}function vP(t){let{root:e,domGraph:n,existingHashes:r}=t,o=[],a=[e];for(;a.length;){let i=a.pop();if(i.nodeType===1&&i.tagName.toLowerCase()==="svg"){let s=bl(i,n);s&&!r[s.hash]&&o.push(s)}for(let s of i.childrenBackendIds){let l=n.backendIdToNode[s];l&&a.push(l)}}return o}var xP=["focusable","keyshortcuts","controls","live","relevant","orientation"],IP=["selected","readonly","modal","required","invalid"],PP=["id","name","role","content"],Ty=["absolute","fixed","sticky"],MP=["path"],LP=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],Ry=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Cy=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],OP=["menulistpopup","statictext","inlinetextbox"],NP=80,wy=100,vy=50,wl=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],kP=["cite"],_P={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},DP={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Ey={indentLevel:0},Cu=class t{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;pathFromRoot;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,e.properties&&e.properties.forEach(n=>{n.name==="keyshortcuts"?this.dataMomenticId=parseInt(n.value.value):this.properties[n.name]=n.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let n=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(n&&n.length<vy?n:""),this.role=this.role||(e.domNode.attributes.role??""),zP(this.properties,e.domNode)}$P(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(){if(this.domNode&&MP.includes(this.domNode.tagName))return!1;if(LP.includes(this.role.toLowerCase()))return!0;if(this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Cy.includes(n)))return!1;if(this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||qn.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let e=this.properties.class;return typeof e=="string"&&e.split(" ").some(n=>Py(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}serialize(e=Ey){let n=Object.assign({},Ey,e),{indentLevel:r,noChildren:o,noProperties:a,noId:i,noContent:s,condensedMode:l}=n,c=Ru(this.properties),d=" ".repeat(r),u=this.role||"",m=this.tagName??"unknown",p=this.name;u==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===p&&(p="")}let f=wl.includes(this.role)||kP.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${d}${p}
3894
- `;let y=`${d}<${m}`;!i&&!f&&(y+=` id="${this.id}"`);let b=s??!1;(c.multiline||c.contenteditable)&&this.children.length>0&&(b=!0),u&&u!=="generic"&&u!==m&&!(_P[u]??[]).includes(m)&&(y+=` role=${JSON.stringify(u)}`),p&&(y+=` name=${JSON.stringify(p)}`),this.content&&!b&&(y+=` content=${JSON.stringify(this.content)}`);let w=Date.now();if(Object.keys(c).length>0&&!a){if(Date.now()-w>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(c).forEach(([v,R])=>{if(!xP.includes(v)){{if(IP.includes(v)&&(!R||R==="false"))return;if(v==="value"&&b&&(c.type==="text"||this.role==="textbox"))return;if(v==="level"&&`${R}`=="1")return;if(v==="url"&&c.src&&m==="img")return;if(v==="url"&&c.href&&m==="a")return;if(v==="editable"&&R==="plaintext")return;if(v==="type"&&R===m)return;if(l&&!DP[v])return}typeof R=="string"?y+=` ${v}="${$e(R,wy,!0)}"`:typeof R=="boolean"?R?y+=` ${v}`:y+=` ${v}={false}`:typeof R<"u"&&(y+=` ${v}={${$e(JSON.stringify(R),wy,!0)}}`)}})}if(m==="::before"||m==="::after"){let v="";for(let R of this.children)v+=R.serialize({...e,indentLevel:r,neighbors:0});return v}let C=e.maxLevel!==void 0&&r/2>=e.maxLevel;if(this.children.length===0||o||C)y+=` />
3895
- `;else{let v="";for(let x of this.children)v+=x.serialize({...e,indentLevel:r+2,neighbors:0});let R=v.trim();R.length<=NP&&!R.includes(`
3896
- `)?y+=`>${R}</${m}>
3897
- `:y+=`>
3898
- ${v}${d}</${m}>
3899
- `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let v=this.parent.children.findIndex(M=>M.id===this.id),R=v>0?this.parent.children[v-1]?.serialize({...e,neighbors:0}):"",x=v<this.parent.children.length-1?this.parent.children[v+1]?.serialize({...e,neighbors:0}):"";return`${R||""}
3900
- ${y}
3901
- ${x||""}`}return y}shallowClone(){let e=new t({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:Ru(this.internalProperties),parentFrame:this.parentFrame});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Ru(this.properties),e}},vu=class t{constructor(e,n,r,o){this.root=e;this.a11yIdNodeMap=n;this.dataMomenticIdMap=r;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingRelevantIds(e){let n=this.root;if(!n)throw new Error("Cannot prune a11y tree with no root");function r(a,i=!1){let s=e.has(`${a.id}`)||a.id===n?.id,l=a.shallowClone(),c=a.children,d=!1,u=[];for(let m of c){let p=r(m,s||d);p&&(u.push(p),p.parent=l,d=!0)}if(l.children=u,s||d)return l;if(wl.includes(a.role)&&i)return l}let o=r(n);return new t(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function FP(t){return t.name?.value?`"${t.name.value}"`:t.role?.value&&t.role.value!=="none"&&t.role.value!=="generic"?`"${t.role.value}"`:`"${t.nodeId}"`}function UP(t,e,n,r){return t.bounds.x===null||t.bounds.y===null||t.bounds.height===null||t.bounds.width===null||t.bounds.width===0||t.bounds.height===0?!0:t.bounds.x+t.bounds.width<e.leftBound||t.bounds.x>e.rightBound?(Cs({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport horizontally"),!1):t.bounds.y+t.bounds.height<e.upperBound||t.bounds.y>e.lowerBound?(Cs({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport vertically"),!1):t.computedStyles.display==="none"?(n.debug({domNode:t},"Filtering out node since it has display none"),!1):!0}async function Ay({node:t,parent:e,frameId:n,frameContext:r,axGraph:o,domGraph:a,inputNodeMap:i,showZeroOpacityElements:s,filterByViewport:l,viewportDetails:c,useMPaths:d,cdpClient:u,logger:m,callId:p}){if(!e&&t.parentId)throw new Error(`Got no parent for accessibility node ${t.nodeId}: ${JSON.stringify(t)}`);let g=(P,W={})=>{},h=t.backendDOMNodeId,f=OP.includes((t.role?.value).toLowerCase());if(!f&&h===void 0)return g("Filtering out node since it doesn't exist in the DOM"),[];let y=h?a.backendIdToNode[h]:void 0;if(!f&&!y)try{let P=await H(u.send({method:"DOM.describeNode",params:{backendNodeId:h}}),{milliseconds:750,fallback:()=>{m.debug("Timeout getting node from CDP while processing a11y tree")}});if(P&&P.node.nodeName.toLowerCase()==="slot"&&P.node.distributedNodes?.length)m.debug({redirectedDomNode:y,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:t,cdpResult:P},"Redirecting node to assigned slot");else return g("Filtering out node since it doesn't exist in the DOM",{cdpResult:P}),[]}catch(P){return g("Filtering out node since it doesn't exist in the DOM",{err:P}),[]}if(y&&e&&l&&c&&t.backendDOMNodeId&&!UP(y,c,m,p))return y.momenticIgnored=!0,[];if(y&&y.computedStyles.display==="none")return y.momenticIgnored=!0,[];if(y&&y.computedStyles.opacity==="0"&&s!==!0){if(s==="inputs-only"&&y.tagName.toLowerCase()!=="input")return y.momenticIgnored=!0,[];if(s===!1)return y.momenticIgnored=!0,[]}let b=t.name?.value?typeof t.name.value=="string"?t.name.value:`${t.name.value}`:"",w=t.value?.value?typeof t.value.value=="string"?t.value.value:`${t.value.value}`:"",C=new Cu({domNode:y,id:parseInt(t.nodeId),role:t.role?.value||"",name:b,nameSources:t.name?.sources,content:w,properties:t.properties,children:[],ignoredReasons:t.ignoredReasons?.filter(P=>Ry.includes(P.name)||Cy.includes(P.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+FP(t),backendNodeID:t.backendDOMNodeId,ignoredByCDP:t.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},parentFrame:r.type==="root"?void 0:r}),v=r,R=i[n],x=n;if(y?.tagName.toLowerCase()==="iframe"&&y.ownedFrameId){let P=r.childFrames.find(G=>G.frameId===y.ownedFrameId),W=o[P?.frameId??""]?.root,k=i[P?.frameId??""];if(P&&W&&k){t.childIds&&t.childIds.length>0&&m.debug("Replacing existing node's children with children from the iframe");let G=W;t.childIds=G.childIds,v=P,R=k,x=P.frameId}}let M=y?.childrenBackendIds?.length??0,D=(t.childIds??[]).filter(P=>!!R.get(parseInt(P))).length;if(M>D){let P=t.childIds?.map(k=>R.get(parseInt(k))).filter(Boolean).map(k=>k?.backendDOMNodeId).filter(k=>k!==void 0)??[],W=0;for(let k of y?.childrenBackendIds??[]){if(P.includes(k)){W=(t.childIds?.findIndex(wt=>R.get(parseInt(wt))?.backendDOMNodeId===k)??0)+1;continue}let G=a.backendIdToNode[k];if(!G||G?.tagName.toLowerCase()!=="svg")continue;let we=Math.floor(-1*Math.random()*1e7),Ce={nodeId:we.toString(),parentId:t.nodeId,ignored:!1,backendDOMNodeId:k,frameId:x,role:{type:"string",value:"graphics-symbol"}};R.set(we,Ce),t.childIds||(t.childIds=[]),t.childIds.splice(W,0,we.toString()),W++}}for(let P of t.childIds??[]){if(!P)continue;let W=R.get(parseInt(P));if(!W)continue;let k=await Ay({node:W,parent:C,domGraph:a,axGraph:o,frameId:x,frameContext:v,inputNodeMap:i,cdpClient:u,logger:m,callId:p,filterByViewport:l,showZeroOpacityElements:s,viewportDetails:c,useMPaths:d});k.length&&(C.children=C.children.concat(k))}if(C.role==="StaticText"&&(C.children=[]),C.children.length===1&&C.children[0].role==="StaticText"){let P=C.name,W=C.children[0]?.name;(P===W||!W)&&(C.children=[])}let _=[];for(let P=C.children.length-1;P>=0;P--){let W=C.children[P];if(W.role!=="StaticText"){_.push(W);continue}if(P===0||C.children[P-1].role!=="StaticText"){_.push(W);continue}C.children[P-1].name+=W.name}if(C.children=_.reverse(),C.role==="generic"&&C.children.length===1){let P=C.children[0];if(C.name&&!wl.includes(P.role)&&C.name===P.name)return y&&(y.momenticIgnored=!0),C.children}if(!C.isInteresting()&&t.parentId)return y&&(y.momenticIgnored=!0),C.children;for(let P of C.children)P.parent=C;return HP(C),y&&d&&Eu(y,a),[C]}function xy({node:t,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,domGraph:a,useMPaths:i,selectorToNodeMap:s,iconKnowledgeBase:l,startId:c=1}){t.id=c,c+=1,e[t.id]=t,t.dataMomenticId?n[t.dataMomenticId]=t:wl.includes(t.role);let d=t.backendNodeId,u=d!==void 0?a.backendIdToNode[d]:void 0;if(i&&u&&u.mPathSelector&&(s[u.mPathSelector]=t),l&&u&&u.tagName?.toLowerCase()==="svg"){let m=bl(u,a),p=m?l[m.hash]:void 0,g=p?p.description:void 0;p&&(t.properties["data-momentic-description"]=g)}for(let m of t.children)c=xy({node:m,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,startId:c,useMPaths:i,domGraph:a,selectorToNodeMap:s,iconKnowledgeBase:l});return c}async function Iy({rawA11yGraph:t,domGraph:e,startingFrameId:n,logger:r,cdpClient:o,filterByViewport:a,showZeroOpacityElements:i,viewportDetails:s,useMPaths:l,frameContext:c,iconKnowledgeBase:d}){let u=n??"root",m=t[u]?.root;if(!m)throw new Error("A11y tree has no root");let p=AP(),g=C=>{let v=C.allNodes.filter(x=>!x.ignoredReasons?.find(D=>Ry.includes(D.name))),R=new Map;return v.forEach(x=>{R.set(parseInt(x.nodeId),x)}),R},h={};Object.entries(t).forEach(([C,v])=>{h[C]=g(v)});let f=await Ay({node:m,domGraph:e,parent:null,inputNodeMap:h,axGraph:t,frameId:u,frameContext:c,cdpClient:o,logger:r,callId:p,showZeroOpacityElements:i,filterByViewport:a,viewportDetails:s,useMPaths:l});if(f.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(f)}`);if(f.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let y={},b={},w={};return xy({node:f[0],a11yIdNodeMap:y,dataMomenticIdMap:b,selectorToNodeMap:w,domGraph:e,logger:r,callId:p,useMPaths:l,iconKnowledgeBase:d}),new vu(f[0],y,b,w)}function BP(t,e,n){if(t==="class"){if(n.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<vy&&!qn.bannedClassSubstrings.some(i=>a.includes(i))).slice(0,3).join(" ");let r=e.split(" "),o=[];for(let a of r)if(Py(a)){o.push(a);continue}return o.length?o.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let r=parseInt(e);if(!isNaN(r))return r}catch{}return t==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function zP(t,e){if(!e)return;Object.entries(e.attributes).forEach(([a,i])=>{if(qn.relevantElementAttributes.includes(a)&&!PP.includes(a)&&!t[a]&&!a.startsWith("aria")){let s=BP(a,i,e);s!==null&&(t[a]=s)}});let n,r=[];if(e.computedStyles.position&&Ty.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of Ty)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&r.push(`position: ${n}`);let o;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(o="opacity: 0"),o&&r.push(o),r.length>0&&(t.style=r.join("; "))}function HP(t){let e=t.properties.class;if(typeof e=="string"&&e.includes("cm-content")){t.children.forEach((a,i)=>{a.properties["cm-line-number"]=`${i+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){t.children.forEach((a,i)=>{a.properties["block-number"]=`${i+1}`}),t.children.length>0&&(t.children[t.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(t.tagName==="table"){let a=[],i=t.children.find(l=>l.tagName==="thead");if(i){let l=i.children.find(c=>c.tagName==="tr");if(l){let c=l.children.filter(d=>d.tagName==="th");c.forEach((d,u)=>{d.properties["col-index"]||(d.properties["col-index"]=u+1),a?.push($e(d.name,100,!1))}),a?.length!==c.length&&(a=void 0)}}let s=0;for(let l of t.children)if(l.tagName==="tbody")for(let c=0;c<l.children.length;c++){let d=l.children[c];if(d.tagName!=="tr")continue;if(c===0&&!a?.length){let p=d.children.filter(g=>g.tagName==="th");if(p.length){if(a=p.map(g=>$e(g.name,100,!1)),a.length===p.length)continue;a=void 0}}s+=1,d.properties["row-index"]||(d.properties["row-index"]=s);let u=d.children.filter(p=>p.tagName==="td"||p.tagName==="th"),m=u.length===a?.length;u.forEach((p,g)=>{p.tagName!=="th"&&(p.properties["col-index"]||(p.properties["col-index"]=g+1),m&&(p.properties.col||(p.properties.col=a[g])))})}}}function $P(t){let e=t.properties.class,n=typeof e=="string"&&e.includes("cm-content");t.internalProperties.inCodeMirrorEditor=t.internalProperties?.inCodeMirrorEditor||n}function Py(t){if(qn.bannedClassSubstrings.some(e=>t.includes(e)))return!1;if(qn.alwaysInterestingClassNames.includes(t))return!0;for(let e of qn.alwaysInterestingClassPrefixes)if(t.startsWith(e))return!0;return!1}var El=class t{constructor(e,n,r,o,a){this.session=e;this.logger=n;this.contextGetter=r;this.pageGetter=o;this.defaultTimeoutMs=a}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:n,pageGetter:r,defaultTimeoutMs:o}){let a=n(),i=r(),s,l;for(let d=0;d<2;d++)try{s=await H(a.newCDPSession(i),{milliseconds:o*d,fallback:()=>{throw new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${i.url()})`)}});break}catch(u){await J(500),l=u}if(!s)throw l;let c=new t(s,e,n,r,o);try{await H(c.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(d){throw c.cdpFullyDead=!0,new A("UserInfrastructureError",`Failed to initialize CDP client: ${d}`)}return c}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(n){this.logger.warn({err:n},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(n)}`)}),e.on("Page.navigatedWithinDocument",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(n)}`)}),e.on("Page.lifecycleEvent",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(n)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:n,timeout:r=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await H(this.cdpInitializingPromise,{milliseconds:r});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new A("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await H(this.session.send(e,n),{milliseconds:r,message:o??`Chrome command ${e} timed out after ${r}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(a){throw["Internal error","Target crashed"].some(i=>a.message.includes(i))&&!this.cdpInitializingPromise&&(this.logger.warn({err:a},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),a}}async createRawCDPSession(e=this.defaultTimeoutMs){let n=e,r=this.pageGetter(),o=await H(this.contextGetter().newCDPSession(r),{milliseconds:n,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${r.url()})`),new A("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${r.url()})`)}});return this.logger.debug(`Created new CDP session for ${r.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let n=this.session;this.session=await this.createRawCDPSession(e),await H(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await H(n.detach(),{milliseconds:1e3})}catch(r){this.logger.warn({err:r},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(n){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${n}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,n){return this.session.on(e,n),this.session}off(e,n){return this.session.off(e,n),this.session}addListener(e,n){return this.session.addListener(e,n),this.session}removeListener(e,n){return this.session.removeListener(e,n),this.session}};var ca="<empty>";function jP(t){return t.includes("doubleclick.net")||t.includes("googletagmanager.com")||t.includes("googlesyndication.com")||t.includes("s.amazon-adsystem.com")||t.includes("smartadserver.com")||t.includes("omnitagjs.com")||t.includes("x.adroll.com")}function Ly(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||jP(t.url)}async function GP(t,e){let n=await t.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await t.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[n.backendNodeId]}})).nodeIds[0],i=(await t.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:n.backendNodeId}})).node;return i.nodeId=o,i}async function da({cdpClient:t,page:e,logger:n}){let r={type:"root",childFrames:[],page:e},o=[],[a,i]=await Promise.all([t.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),t.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),c=(a.frameTree.childFrames??[]).map(async(u,m)=>{if(Ly(u.frame))return null;try{return await Oy({cdpClient:t,rawFrameTree:u,indices:[m],parent:r,warnings:o,logger:n})}catch(p){return o.push(`Failed to get child frame: ${p}`),null}}),d=await Promise.all(c);return r.childFrames=d.filter(u=>u!==null),o.length&&n?.warn({warnings:o},"Got warnings when fetching frame tree"),r}async function Oy({cdpClient:t,rawFrameTree:e,indices:n,parent:r,warnings:o,logger:a}){let i=e.frame.id,s=await GP(t,i),l=s.attributes??[],c=null,d=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=Tr(l,g);h&&(d.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(c=h))}let u={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:i,locationData:{indices:n,attributeSelectors:d},src:c,childFrames:[],parent:r,domNode:s},p=(e.childFrames??[]).map(async(g,h)=>{if(Ly(g.frame))return null;try{return await Oy({cdpClient:t,rawFrameTree:g,indices:[...n,h],parent:u,warnings:o,logger:a})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return u.childFrames=(await Promise.all(p)).filter(g=>g!==null),u}async function WP(t){try{return await t.owner().count()===1}catch{return!1}}async function VP(t){try{return await t.count()===1}catch{return!1}}async function On(t,e){let n=[],r=t;for(;r.parent.type==="frame";)n.push(r.parent),r=r.parent;n.reverse();let o=e,a=[];for(let c of n){let d=!1;for(let u of[...c.locationData.attributeSelectors,ca]){let m=o.frameLocator(u===ca?"iframe":`iframe[${u}]`);if(await WP(m)){d=!0,o=m,a.push(u);break}}if(!d)throw new A("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${c.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let i;for(let c of[...t.locationData.attributeSelectors,ca]){let d=o.locator(c===ca?"iframe":`iframe[${c}]`);if(await VP(d)){i=d,a.push(c);break}}if(!i)throw new A("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${t.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await i.evaluateHandle(c=>c,{timeout:1e3}),l=await s.asElement().contentFrame();if(!l)throw new A("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${t.url}'`);return await s.dispose(),{frame:l,mPathSelectorTokens:a}}function My(t,e){let n=[...t],r=[];for(;n.length;){let o=n.shift();e(o)&&r.push(o),n.push(...o.childFrames)}return r}async function Ny({page:t,frameTree:e,cache:n}){let r,o=e.childFrames,a=[];if(n.mPathSelectorTokens.length){let s=o;for(let d=0;d<n.mPathSelectorTokens.length-1;d++){let u=n.mPathSelectorTokens[d];u===ca?s=s.length===1?s[0].childFrames:[]:s=s.filter(m=>m.locationData.attributeSelectors.includes(u)).map(m=>m.childFrames).flat()}let l=[],c=n.mPathSelectorTokens[n.mPathSelectorTokens.length-1];if(c===ca?l=s:l=s.filter(d=>d.locationData.attributeSelectors.includes(c)),l.length===1)return r=l[0],a.push(`Found unique frame with mpath ${n.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${l.length} frames with mpath ${n.mPathSelectorTokens.join(" > ")}`)}if(n.frameSrcRegex){let s=new RegExp(n.frameSrcRegex),l=My(o,c=>!!c.src&&s.test(c.src));if(l.length===1)return r=l[0],a.push(`Found unique frame with src regex ${n.frameSrcRegex}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${l.length} frames with src regex ${n.frameSrcRegex}`),n.frameSrcRegex=void 0}if(n.frameUrlRegex){let s=new RegExp(n.frameUrlRegex),l=My(o,c=>!!c.url&&s.test(c.url));if(l.length===1)return r=l[0],a.push(`Found unique frame with url regex ${n.frameUrlRegex}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${l.length} frames with url regex ${n.frameUrlRegex}`),n.frameUrlRegex=void 0}let i=o;for(let s=0;s<n.indices.length-1;s++)i=i[n.indices[s]]?.childFrames??[];if(r=i[n.indices[n.indices.length-1]],r)return a.push(`Found unique frame with indices ${n.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};throw a.push(`Found ${i.length} frames with indices ${n.indices}`),new En("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:a}])}function Rl(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function Au(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function ky(t){let e=Au(t),n=t.src??"",r=t.url??"",o=[],a=[],i=[...e.childFrames];for(;i.length;){let s=i.shift();s.src&&o.push(s.src),s.url&&a.push(s.url),i.push(...s.childFrames)}return{srcs:o,urls:a,desiredSrc:n,desiredUrl:r}}function _y(t){return t.type==="auto"?{type:"auto",frameId:t.handle.frameId,url:t.handle.url,src:t.handle.src??"",mPathSelectorTokens:t.mPathSelectorTokens.join(" > ")}:{type:"url",url:t.url}}async function Dy({frame:t,logger:e,signal:n}){let r;try{r=await t.frameElement(),await qP({frameElementHandle:r,logger:e,signal:n})}catch(o){e.warn({err:o},"Failed to scroll iframe into view, continuing...")}finally{await r?.dispose()}}async function qP({frameElementHandle:t,logger:e,signal:n}){let r=await t.boundingBox();if(!r){e.warn("Active frame element has null bounding box, skipping scroll");return}await to({promiseGenerator:async()=>t.evaluate(async(a,{x:i,y:s})=>{window.scrollTo(window.scrollX+i,window.scrollY+s);let l=Date.now(),c,d,u;for(;Date.now()-l<1500;){let m=document.activeElement,p,g,h;if(!m)p=void 0,g=void 0,h=void 0;else{let f=m.getBoundingClientRect();p=m.scrollTop,g=f.x,h=f.y}if(c!==void 0&&d!==void 0&&u!==void 0&&p===c&&g===d&&h===u)break;c=p,d=g,u=h,await new Promise(f=>setTimeout(f,250))}},r),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:n}),e.info({bb:r},"Successfully scrolled iframe into view")}function Fy(t,e){return async(n,r)=>{try{let o=await r.allHeaders();for(let{key:a,value:i,matcher:s}of t)(!s||s.matches({url:r.url(),method:r.method()}))&&(o[a]=i);await n.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as KP}from"crypto";function Uy(t,e){for(let n of Object.values(e))if(n.matcher.matches({url:t.url(),method:t.method()}))return n}async function By(t){let{route:e,mock:n,entry:r,debugData:o,requestId:a,requestRecorders:i,logger:s}=t,l={url:r.request.url,options:{method:r.request.method,headers:r.request.headers.map(p=>[p.name,p.value]),body:r.request.postData?.text}},c;if(n.fetchOriginalResponse){let p=await e.fetch();c={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let d=await n.generateResponse(l,c),u={};d.headers.forEach((p,g)=>{u[g]=p});let m={body:await d.text(),contentType:d.headers.get("content-type")||"text/plain",headers:u,status:d.status};await e.fulfill(m);try{r.response={status:m.status,statusText:d.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body}},Si(o,r,a);for(let p of Object.values(i))p.onRequestComplete(a,r)}catch(p){p.message.includes("has been closed")||s.warn({err:p},"Failed to add response to HAR")}}async function xu(t){try{await YP(t)}catch(e){t.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function YP(t){let{pageId:e,route:n,request:r,debugData:o,logger:a,requestRecorders:i,mocks:s}=t,l=KP(),c=await fu(e,r);try{Si(o,c,l);for(let u of Object.values(i))u.onRequestStart(l,c)}catch(u){a.warn({err:u},"Failed to add request to HAR")}let d=Uy(r,s);d?await By({logger:a,route:n,mock:d,entry:c,debugData:o,requestId:l,requestRecorders:i}):await XP({route:n,request:r,debugData:o,logger:a,requestRecorders:i,entry:c,requestId:l})}async function XP({route:t,request:e,debugData:n,logger:r,requestRecorders:o,entry:a,requestId:i}){await t.continue();try{let s=await e.response();if(!s||!a)return;await ZS(a,e,s),Si(n,a,i);for(let l of Object.values(o))l.onRequestComplete(i,a)}catch(s){s.message.includes("has been closed")||r.warn({err:s},"Failed to add response to HAR")}}async function JP(t){let e=t.postData();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:t.postDataJSON()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function QP(t){let e=await t.text();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:await t.json()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Cl(t){return{request:{url:t.request.url,method:t.request.method,headers:t.request.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.request.postData?t.request.postData.mimeType.includes("json")?{json:JSON.parse(t.request.postData.text)}:{text:t.request.postData.text}:{}},response:t.response?{status:t.response.status,headers:t.response.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.response.content?t.response.content.mimeType?.includes("json")&&t.response.content.text?{json:JSON.parse(t.response.content.text)}:{text:t.response.content.text}:{}}:void 0}}async function Iu(t){let e=t.request(),n=t.status(),r=t.headers(),o=await QP(t);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await JP(e)},response:{status:n,headers:r,...o},status:n,headers:r,...o}}var wr=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:n,method:r}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==r.toLowerCase()?!1:Js(n,this.requestMatcher.urlMatcher)}};async function zy({event:t,transformer:e,enricher:n,frame:r,lastScreenshotForRecording:o,logger:a}){let{warnings:i,error:s,properties:l}=t.target;if(s){a.error({error:s,warnings:i},"Error while capturing passive click");return}if(i.length&&a.warn({warnings:i},"Warnings while capturing passive click"),!l)return;let c=r.parentFrame()?r.url():void 0,u=r.page().frames().map(g=>g.url());a.debug({frameUrl:c,...t},"Passive click event captured on element");let m,p;if(c)try{let g=await r.frameElement();m=await H(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await n.constructIframeRegex({urls:u,srcs:[],desiredUrl:c});if(h.urlRegex)p={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){a.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),p={type:"url",url:c}}(async()=>{try{await e.recordElementAction({...t,screenshotBase64:o,frameConfig:p,frameBoundingBox:m})}catch(g){a.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as Nn}from"crypto";import ZP from"js-beautify";var eM=["Dead"],vl=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:n,generator:r,testId:o,orgId:a,logger:i}){this.signal=e,this.logger=i,this.testId=o,this.orgId=a,this.callbacks={onStepRecorded:(s,l)=>{this.recordedSteps.set(l,{step:s}),n.onStepRecorded(s,l)},onActionReceived:(s,l)=>{this.recordedSteps.set(l,{step:s}),n.onActionReceived?.(s,l)}},this.generator=r}reserveIndexForCommand(e){let n=this.nextStepOffset;return this.recordedSteps.set(n,{step:{id:Nn(),type:"PRESET_ACTION",command:Un(e)}}),this.nextStepOffset++,n}async recordElementAction(e){let{type:n,target:r,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let a,i,s=r.properties.attributes.nodeOnlySerializedHtml.trim(),l=s,c;switch(e.frameConfig?e.frameBoundingBox?c={x:e.frameBoundingBox.x+r.properties.boundingBox.x,y:e.frameBoundingBox.y+r.properties.boundingBox.y,width:r.properties.boundingBox.width,height:r.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):c=r.properties.boundingBox,n){case"CLICK":{a="CLICK";let h=Un(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:l},iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}}}};break}case"SELECT":{a="SELECT_OPTION";let h=Un(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:l},cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{a="MOUSE_DRAG";let h=Un(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:l},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:Oe(this.logger),boundingBox:c}}}};break}default:throw new Error(`Unknown action type: ${n}`)}let d;e.offset===void 0?(d=this.nextStepOffset,this.nextStepOffset++):d=e.offset,this.callbacks.onActionReceived?.(i,d);let u=e.target.browserState;try{u=ZP.html(u,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),u=$S(u,"data-momentic-interacted",4e4)}catch{}let m;try{m=(await this.generator.getReverseMappedDescription({target:u,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:r.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...Oe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=s}let p=this.recordedSteps.get(d)?.step??i,g=p?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...p,command:g},d)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:n,combinable:r}=e;if(eM.includes(n)||this.signal.aborted)return;let o="normal";n.length>1&&(o="special");let a;if(o==="normal"){let u=Un("TYPE");a={id:Nn(),type:"PRESET_ACTION",command:{...u,target:void 0,value:n,clearContent:!1}}}else{let u=Un("PRESS");a={id:Nn(),type:"PRESET_ACTION",command:{...u,value:n}}}let i,s=this.nextStepOffset-1,l=this.recordedSteps.get(s),c=l?.step,d=c?.command;if(r){if(d?.type===a.command.type){let u=d.value,m=a.command.value;a={id:Nn(),type:"PRESET_ACTION",command:{...d,value:a.command.type==="PRESS"?`${u}+${m}`:`${u}${m}`}},i=s}else if(d?.type==="CLICK"&&a.command.type==="TYPE")c.command={...a.command,target:d.target,cache:d.cache},a=l.step,i=s;else if(d?.type==="TYPE"&&a.command.type==="PRESS"&&a.command.value==="Backspace"){let u=d.value;a={id:Nn(),type:"PRESET_ACTION",command:{...d,value:u.slice(0,u.length-1)}},i=s}}i===void 0&&(i=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(a,i)}recordScroll(e){if(this.signal.aborted)return;let n=()=>{let{deltaY:a}=e;if(!a)return;let i=this.nextStepOffset-1,s=this.recordedSteps.get(i)?.step.command,l;s?.type==="SCROLL_DOWN"&&s.deltaY?(a+=s.deltaY,l=i):s?.type==="SCROLL_UP"&&s.deltaY?(a-=s.deltaY,l=i):(l=this.nextStepOffset,this.nextStepOffset++);let c=a>0?"SCROLL_DOWN":"SCROLL_UP",d=Un(c);d.deltaY=Math.abs(a);let u={id:Nn(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,l)},r=()=>{let{deltaX:a}=e;if(!a)return;let i=this.nextStepOffset-1,s=this.recordedSteps.get(i)?.step.command,l;s?.type==="SCROLL_RIGHT"&&s.deltaX?(a+=s.deltaX,l=i):s?.type==="SCROLL_LEFT"&&s.deltaX?(a-=s.deltaX,l=i):(l=this.nextStepOffset,this.nextStepOffset++);let c=a>0?"SCROLL_RIGHT":"SCROLL_LEFT",d=Un(c);d.deltaX=Math.abs(a);let u={id:Nn(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,l)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(r(),e.deltaY>=20&&n()):(n(),e.deltaX>=20&&r())}};import{z as Pu}from"zod";var ore=Pu.object({type:Pu.literal("url"),url:Pu.string()});var Al=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:n,allowPartialAccessibilityTree:r,logger:o,cdpClient:a,pageGetter:i,abortSignalGetter:s,enricher:l,iconKnowledgeBase:c,userBrowserSettings:d}){this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=n,this.allowPartialAccessibilityTree=r,this.logger=o,this.cdpClient=a,this.pageGetter=i,this.abortSignalGetter=s,this.enricher=l,this.iconKnowledgeBase=c,this.userBrowserSettings=d}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let n={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,n),n}async getAutoFrameDetailsFromHandle(e){let n=this.pageGetter(),r=Au(e),{frame:o,mPathSelectorTokens:a}=await On(e,n),i={indices:e.locationData.indices,mPathSelectorTokens:a};return this.constructIframeRegexAsync(e,i),{cache:i,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:a,frameTree:r,cache:i}}}async resolveAutoFrameCache(e){let n=this.pageGetter(),r=await da({cdpClient:this.cdpClient,page:n,logger:this.logger}),{resolution:o,logs:a}=await Ny({page:n,frameTree:r,cache:e});return this.logger.info({logs:a},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:n=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(Rl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let r;return this.frameConfig.type==="url"?r=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:n}):r={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:Rl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Dy({frame:r.frame,logger:e,signal:n}),this.activeFrameCache=r,r}async executeFunctionInAllFrames(e,n){let r=this.pageGetter(),o=await da({cdpClient:this.cdpClient,page:r,logger:this.logger}),a=[H(r.evaluate(e,n),{milliseconds:2e3})],i=Array.from(o.childFrames);for(;i.length>0;){let l=i.shift(),c=l.url;c==="about:blank"||c.startsWith("chrome-error://")||(i.push(...l.childFrames),a.push(On(l,r).then(({frame:d})=>H(d.evaluate(e,n),{milliseconds:2e3})).catch(d=>(this.logger.warn({err:d,frameUrl:l.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(a)).filter(l=>l!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),n=await da({cdpClient:this.cdpClient,page:e,logger:this.logger}),r=Array.from(n.childFrames),o=[];for(;r.length>0;){let a=r.shift();r.push(...a.childFrames),o.push(a.src??a.url)}return o}async getDomGraph({devicePixelRatio:e,signal:n,logger:r}){return this.getDOMTree({devicePixelRatio:e??1,signal:n,logger:r??this.logger})}async getA11yTree(e){let n={},r=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),a=this.pageGetter(),i,s,l=null;if(this.frameConfig?.type==="url"){if(i=await on({fn:()=>this.resolveActiveFrameConfig({logger:r,signal:o}),codePath:"getActiveFrameDetails",logObject:n,signal:o,logger:r})??void 0,!i)throw new A("ActionFailureError","Got null frame details despite active frame config");s=i.handle,l=s.frameId}else this.userBrowserSettings.autoExpandIframes?(s=await on({fn:()=>da({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),codePath:"getMomenticFrameTree",logObject:n,signal:o,logger:r}),l=null):(s={type:"root",page:a,childFrames:[]},l=null);await on({fn:async()=>this.addMomenticIds({rootPage:a,childFrames:s.childFrames,frameFilter:i?.frame,logger:r}),codePath:"addIdsToElement",logObject:n,signal:o,logger:r});let c=await on({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:r}),codePath:"domFetch",logObject:n,signal:o,logger:r}),d=await on({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:l,childFrames:s.childFrames,logTimings:n,logger:r,signal:o}),codePath:"totalA11yFetch",logObject:n,signal:o,logger:r}),{tree:u}=await on({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:d,domGraph:c,startingFrameId:l,frameContext:s,logger:r,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements}),codePath:"a11yProcess",logObject:n,signal:o,logger:r});return Object.values(n).some(m=>m>750)&&r.warn({logTimings:n},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=u.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=u.dataMomenticIdMap,this.lastA11yTreeRoot=u.root,this.lastDomGraph=c,this.lastSelectorToNodeMap=u.selectorToNodeMap,u}async fetchA11yTreeForRecording(e,n){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:n,logger:Xr,filterByViewport:!1}),Math.random()<.1){let r=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:r&&r.length>4e5?"REDACTED_DUE_TO_SIZE":r},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:n,node:r}){if(r.backendNodeId===void 0)throw new Error(`Node with a11y id ${r.id} has no backend node ID: ${r.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[r.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${r.backendNodeId}`);let a=fy({node:o,domGraph:this.domGraph});return Sy(e,a)}else return this.getLocatorFromBackendId(n,r.backendNodeId)}async getLocatorFromBackendId(e,n){let r=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:n},timeout:2e3});if(!r||!r.object.objectId)throw new Error(`Could not resolve backend node ${n}`);let o;try{o=await yy(this.cdpClient,r.object.objectId)}catch(a){throw this.logger.debug({err:a,object:JSON.stringify(r.object)},"Failed to get ID attribute"),a}return e.locator(pn(o))}getNodeUsingMPathSelector(e){let n=this.selectorToNodeMap[e];if(n)return n;let r=e.split(" > "),o="";for(let a=r.length-1;a>=0;a--){let i=r.slice(a).join(" > ");if(this.selectorToNodeMap[i]){o=i;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:n=this.abortSignalGetter(),logger:r=this.logger}){let o=Date.now(),a,i,s,l=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{a=await da({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),i=await this.getMatchingFrameByUrlWithCdp(a,e),r.info({frameId:i.handle.frameId,url:i.handle.url,src:i.handle.src,locationData:i.handle.locationData},`Found matching frame using ${i.matchType}`);break}catch(c){if(s=c,c instanceof A&&c.reason==="UserInfrastructureError")throw c;l%3===0&&this.logger.warn({attempt:l,err:c},"Failed to resolve active frame, retrying..."),await J(500,n)}finally{l++}if(i)return{source:"url",frame:i.frame,handle:i.handle,frameIdentifierStringified:Rl(e),cacheTime:Date.now(),frameTree:a,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,n){let r=n.url,o=this.pageGetter(),a=Array.from(e.childFrames),i=[];for(;a.length>0;){let s=a.shift(),l=s.domNode;a.push(...s.childFrames);let c=Tr(l.attributes??[],"src"),d=l.contentDocument?.documentURL;if(!c&&!d){this.logger.debug("Skipping frame with no URL or src");continue}for(let u of[c,d])if(u){if(r.startsWith("/")&&r.endsWith("/")){if(new RegExp(r.slice(1,-1)).test(u)){i.push({handle:s,matchType:"regex",...await On(s,o)});break}}else if(r.trim()===u.trim()){i.push({handle:s,matchType:"url",...await On(s,o)});break}}}if(i.length===1){let s=i[0];return this.userBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw i.length>1?new Error(`Found multiple frames with src matching '${r}'. Please use a more specific selector.`):new A("ActionFailureError",`Failed to find frame with src matching: ${r}`)}async composeA11yDomGraph({opts:e,a11yGraph:n,domGraph:r,startingFrameId:o,frameContext:a,logger:i,iconKnowledgeBase:s,showZeroOpacityElements:l}){let c=await Iy({rawA11yGraph:n,startingFrameId:o,frameContext:a,domGraph:r,logger:i,cdpClient:this.cdpClient,showZeroOpacityElements:l,filterByViewport:e.filterByViewport,viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userBrowserSettings.visualActions});if(!c||!c.root)throw new Error("Accessibility tree appears empty");return{tree:c}}async addMomenticIds({rootPage:e,childFrames:n,frameFilter:r,logger:o}){if(this.userBrowserSettings.visualActions)return;let a=await this.addMomenticIdsHelper(r??e,1);if(!this.userBrowserSettings.autoExpandIframes||r)return;let i=Array.from(n),s=[];for(;i.length>0;){let l=i.shift();i.push(...l.childFrames);let c=async()=>{try{let{frame:d}=await On(l,e);a=await this.addMomenticIdsHelper(d,a)}catch(d){l.url!=="about:blank"&&o.warn({err:d},"Error adding momentic IDs to child frame, continuing...")}};s.push(c())}await Promise.all(s)}async addMomenticIdsHelper(e,n){if(this.userBrowserSettings.visualActions)return n;let r=this.logger;return await Qe({root:e,fn:a=>window.addIdsToElement?.(document.body,a),arg:n,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(a){r.warn({err:a},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??n}getPageDomain(e){try{let n=new URL(e);if(!n.hostname)return null;let r=n.hostname.split("."),o=r.length>2?r.slice(-2).join("."):n.hostname;return`${n.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:n,handle:r}){try{let{shouldUnroll:o,reason:a}=await this.decideChildFrameUnrollEligibilityHelper({domNode:r.domNode});return{shouldUnroll:o,reason:a}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let a=`Got error when determining whether to filter frame ${r.frameId} with url ${r.url}, allowing it to be fetched: ${o}`;return n?.push(a),e?.warn({err:o},a),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let n=e.attributes??[];if(Tr(n,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let r=Tr(n,"style");if(r?.includes("display: none")||r?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,a]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let i of a.computedStyle){if(i.name==="display"&&i.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(i.name==="visibility"&&i.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(i.name==="opacity"&&i.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:n,childFrames:r,logTimings:o,logger:a=this.logger,signal:i=this.abortSignalGetter()}){let s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(p){a.warn({err:p},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let l,c;for(let p=0;p<3;p++)try{c=await on({fn:()=>this.getRawA11yTreeForFrame({frameId:n,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:i,logger:a});break}catch(g){l=g,a.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!c)throw new Error(`Failed to fetch accessibility tree for root page: ${l}`);let d={};if(d[n??"root"]=c,!this.userBrowserSettings.autoExpandIframes)return d;let u=Array.from(r),m=[];for(;u.length>0;){let p=u.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:p,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${p.frameId} with url ${p.url}, allowing it to be fetched: ${h}`)}u.push(...p.childFrames);let g=async()=>{try{let h=await on({fn:()=>this.getRawA11yTreeForFrame({frameId:p.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${p.frameId}`,logObject:o,signal:i,logger:a});d[p.frameId]=h}catch(h){a.warn({err:h,url:p.url,src:p.src},`Error getting raw a11y tree for child frame ${p.frameId}, continuing...`)}};m.push(g())}return await Promise.all(m),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),d}async getRawA11yTreeForFrame({frameId:e,timeoutMs:n,logTimings:r}){let o;if(this.allowPartialAccessibilityTree)o=(await on({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let i=(await on({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await on({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:i},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:n,logger:r}){let o,a=0,i;for(;!o&&a<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:Tl},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await J(500,n),a++,i=s}if(!o||!o.documents.length)throw r.error({err:i},"Fatal error fetching DOM tree"),new A("UserInfrastructureError","Received an empty HTML snapshot from the browser. This indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code.");return hy({snapshot:o,devicePixelRatio:e,logger:r})}constructIframeRegexAsync(e,n){if(n.frameSrcRegex||n.frameUrlRegex)return;let r=ky(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(r);o?.srcRegex&&(n.frameSrcRegex=o.srcRegex),o?.urlRegex&&(n.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:r},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function Mu(t){let e=[],n="";for(let r of t)r==="+"&&n?(e.push(n),n=""):n+=r;return e.push(n),e}var Nu=ua(ku(),"momentic","chromium"),wM=ua(ku(),"video"),Pl=process.env.TWO_CAPTCHA_KEY,qy=yM(Vy);qy.use(bM({provider:{id:"2captcha",token:Pl},visualFeedback:!0}));var kn=class t{static USER_AGENT=SM["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:n,enricher:r,browser:o,context:a,page:i,baseUrl:s,logger:l,userBrowserSettings:c,viewport:d,properties:u,clientCallbacks:m,iconKnowledgeBase:p}){if(mh(c),this.storage=e,this.flagStore=n,this.enricher=r,this.browser=o,this.context=a,this.page=i,this.baseUrl=s,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=d,this.properties=u,this.clientCallbacks=m,u.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:n}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let r={[fl]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:BS.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(r)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];n&&await this.page.reload();let a=s=>this.handleNewPageEvent(s);this.context.on("page",a),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",a)});let i=Promise.all(o);await Promise.all([i]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&pM()==="darwin"&&iM("system_profiler SPDisplaysDataType").toString().includes("Retina")?(S.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await El.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Al({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let n=e.sessionId,r=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=r,this.clientCallbacks?.onScreencastFrame?.(r,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:n}})}catch{}})()})}))}static async init({baseUrl:e,logger:n,storage:r,flagStore:o,enricher:a,userBrowserSettings:i,contextArgs:s,recordVideo:l,iconKnowledgeBase:c,callbacks:d}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let u;switch(i.browserType){case"Google Chrome":u="chrome";break;case"Chrome for Testing":u=void 0;break;case"Chromium":u="chromium";break;default:u="chromium";break}let m={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:u},p={...s??{},geolocation:s?.geolocation||Fo,locale:s?.locale||_o,timezoneId:s?.timezoneId||Do,colorScheme:s?.colorScheme,httpCredentials:i.basicAuthorization?{username:i.basicAuthorization.username??"",password:i.basicAuthorization.password??""}:void 0,javaScriptEnabled:i.disableJavaScript?!1:void 0,ignoreHTTPSErrors:i.ignoreHttpsErrors??!1,userAgent:i.userAgent??t.USER_AGENT,viewport:s?.viewport??Nt},g=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],h=null,f,y,b={systemDevicePixelRatio:s?.deviceScaleFactor,recordVideo:l,isNewHeadless:!1};(u==="chrome"||u==="chromium")&&(b.isNewHeadless=!0,m.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),i.disableGpu&&g.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let w=i.localChromeExtensionPaths?.map(v=>v.startsWith("~")?ua(ku(),v.slice(1)):v);if(w?.length){if(u===void 0)throw new A("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let M of w){let D=ua(M,"manifest.json");if(!Il(D))throw new A("UserConfigurationError",`Chrome extension path ${D} does not exist.`)}let v=ua(Nu,`momentic-session-${Date.now()}`);if(!Il(v))try{sM(v,{recursive:!0})}catch(M){throw new A("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Nu} folder: ${M}`)}let R=[...g],x=w.map(M=>fM(M)).join(",");R.push(`--disable-extensions-except=${x}`),p?.deviceScaleFactor&&R.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&R.push(`--window-size=${p.viewport.width},${p.viewport.height}`),f=await Vy.launchPersistentContext(ua(Nu,`momentic-session-${Date.now()}`),{...m,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:R,baseURL:e}),n.debug({sharedContextOptions:p,sharedBrowserOptions:m,userBrowserSettings:i,chromeArgs:R,flags:o.getAllFlags(),properties:b,baseUrl:e},"Browser initialization context args (persistent)"),y=f.pages()[0]}else{h=await qy.launch({...m,args:g});let v={...p,baseURL:e,recordVideo:l?{dir:wM}:void 0};f=await h.newContext(v),n.debug({contextArgs:v,sharedBrowserOptions:m,chromeArgs:g,userBrowserSettings:i,flags:o.getAllFlags(),properties:b,baseUrl:e},"Browser initialization context args (standard)"),y=await f.newPage()}let C=new t({browser:h,context:f,page:y,baseUrl:e,logger:n,storage:r,flagStore:o,enricher:a,userBrowserSettings:i,viewport:p.viewport||Nt,properties:b,clientCallbacks:d,iconKnowledgeBase:c});return await C.initialize({grantPermissions:!0,runInitScripts:!1}),C}static async fromExistingContext({context:e,storage:n,flagStore:r,enricher:o,userBrowserSettings:a,logger:i}){let s=e.pages()[0];if(!s)throw new Error("No page found in existing context");let l=s.viewportSize(),c=s?.url(),d=new t({browser:e.browser(),context:e,page:s,baseUrl:c,logger:i,storage:n,flagStore:r,enricher:o,userBrowserSettings:a,viewport:l,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0}),d}async handleAvailableTabsChangeHelper(){try{let e=await wu(this.context,{getTitles:!0}),n=this.page.url();this.clientCallbacks?.onTabsChange?.(e,n)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,n){let r=Lu(),o=`${e}-${r}`,a=Date.now(),i=!1,s=async()=>{try{await H(n(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-a},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],i=!0}};this.pageLoadPromises[o]=s().catch(()=>{}),i&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let n=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let r=this.context.pages();for(let o=r.length-1;o>=0;o--){let a=r[o];if(!(!a||a.isClosed()||!no(a.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${a.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>n())}handleNewPageEvent(e){let n=e.url();if(this.logger.info({url:n},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let r=e.video();r&&this.videos.push(r)}try{this.handleNewPageEventHelper(e)}catch(r){this.logger.warn({err:r},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let n=Lu(),r="new-page-load-handler";e.on("close",i=>this.handlePageClosedEvent(i)),e.on("framenavigated",i=>this.handleFrameNavigationEvent(i)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",i=>{XS(e,o,this.debugData,i,this.logger)});let a=async()=>{await QS(n,this.debugData,e),await e.route("**/*",async(i,s)=>{await xu({pageId:n,route:i,request:s,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",Fy(this.customHeaders,this.logger)),await this.loadFrameAndRecordUrl({root:e,codePath:r}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(r,async()=>a())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let n=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),r=by({domGraph:n,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(r.forEach(s=>{this.iconKnowledgeBase[s.hash]=s}),!r.length)return;let o=Oe(this.logger),a={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:mM()};for(let s of["runId","testId"])o[s]&&(a[s]=o[s]);let i={metadata:a,newSvgs:r};this.clientCallbacks.onSvgsCollected(i)}handleFrameNavigationEvent(e){let n=e.url(),r=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${n.slice(0,50)}-${r}`;if(!n||n==="about:blank"||!no(n)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let a=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(i){i.name!=="AbortError"&&this.logger.warn({err:i},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>a())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let r={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(r[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let a=window;a._MOMENTIC_ICON_KNOWLEDGE_BASE=o},r)}catch(n){this.logger.warn({err:n},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await H(yu(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,n,r){let o=Date.now(),a=0,i=0;for(;Date.now()-o<8e3;){i++,r?.throwIfAborted();try{if(await Qe({fn:()=>{let l=window;return!!(l.generateCssSelectors&&l.evaluateCssSelectors&&l.evaluatePrimaryCaches&&l.generateHtmlCacheAttributes&&l.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(a++,a>=3){n.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await J(500),i%2===0&&n.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),Qe({root:e,fn:()=>{let n=window;if(!n?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return n.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,n=[],r=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{r.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),n.push(()=>{for(let[o,a]of r)o.style.setProperty("caret-color",a.value,a.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of n)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:n=1,stabilizeBeforeScreenshot:r=!1}=e,o=this.page.url();r&&await this.stabilizePageForScreenshot();let a=Date.now();try{await this.fixViewportForNewHeadless();let i=await this.screenshotHelper({...e,retries:n});if(i.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(i.length===0)throw new Error("Got empty screenshot");return i}catch(i){if(n<=0||i.message.includes("has been closed"))throw i;return this.logger.warn({err:i,pageUrl:o},"Failed taking screenshot, retrying..."),await J(250),this.screenshot({...e,retries:n-1})}finally{Date.now()-a>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-a},"Screenshot took longer than expected"),r&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:n,saveToDiskPath:r,timeout:o,respectActiveFrame:a,clearHighlights:i=!1}){i&&await this.clearHighlights(),a&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:n,optimizeForSpeed:!0},timeout:o??2e3}),l=Buffer.from(s.data,"base64"),c=await Gy.fromBuffer(l),{width:d,height:u}=this.getViewport()??{};if(d&&u&&(c.bitmap.width!==d||c.bitmap.height!==u)&&(l=await c.resize({w:d,h:u}).getBuffer("image/jpeg")),r&&cM(r,l),this.lastScreenshotForRecording=l,!e)return l;let m=await e.boundingBox({timeout:3e3});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:p,y:g,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");if(p<0||g<0)throw new Error("Attempted to screenshot an element with negative coordinates");p=Math.floor(p),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{l=await(await Gy.fromBuffer(l)).crop({x:p,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(y){throw new Error(`Failed taking element screenshot at coordinates (${p}, ${g}) with size (${h}, ${f}): ${y}`)}return"dispose"in e&&await e?.dispose(),l}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:n=!1,loadTimeoutMs:r=this.pageLoadTimeout}){xf(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();n||(await this.waitForPageLoad(),await this.waitForDOMStability());let a=!1,i;for(let l=0;l<3;l++)try{await this.page.goto(e,{timeout:r,waitUntil:"domcontentloaded"}),a=!0;break}catch(c){if(i=c,this.abortSignal?.throwIfAborted(),this.logger.warn({err:c},`Error occurred during navigation${l===0?", retrying...":" (fatal)"}`),await J(500),i.message.includes("Timeout")&&i.message.includes("exceeded")||i.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!a)throw new A("UserInfrastructureError",i?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(jS.has(s))throw new A("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(n)try{await this.exposeRecordingBindings()}catch(l){l instanceof Error&&l.message.includes("already registered")||this.logger.error({err:l},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,n={},r=!1){await this.directTypeHelper(e,n,r)}async getActiveElement(e){try{return await Qe({root:e,fn:()=>{let r=document.activeElement?.textContent??void 0;return r&&r.length>100&&(r=r.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:r}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(n){this.logger.warn({err:n},"Failed to get active element");return}}async directTypeHelper(e,n={},r=!1){let o=await this.getActivePageOrFrame();await iy({root:o,text:e,options:n,logger:this.logger,callbacks:this.getBrowserCallbacks()});let a=await this.getActiveElement(o);if(r){let i=Date.now();for(;Date.now()-i<this.smartWaitingTimeout&&(!a||a.tag==="body");)await J(250),this.abortSignal?.throwIfAborted(),a=await this.getActiveElement(o);a||this.logger.warn("No active element found to type into, attempting anyways")}n.clearContent&&(n.forceClearContent||a?.tag==="input"||a?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:a},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:n.delay??Im}),n.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async r=>{let o=r.scrollTop;r.scrollIntoView(),await new Promise(i=>setTimeout(i,250));let a=Date.now();for(;Date.now()-a<1e3;){let i=r.scrollTop;if(i===o)break;o=i,await new Promise(s=>setTimeout(s,250))}},void 0,{timeout:2e3})}catch(r){this.logger.warn({err:r},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:n}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(n.locator),!0}catch(n){return this.logger.debug({err:n,id:e},"Failed to highlight target"),!1}}async highlight(e){return Sl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let n=new URL(e).origin;if(n==="null")return;this.originsVisited.add(n)}catch(n){this.logger.warn({err:n},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises),o=-1,a=0;for(;n.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Still waiting on page load promises"),Date.now()-o<20&&(a++,a>2)){this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(n),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let n=this.context.pages().indexOf(this.page),r=[...this.context.pages()];for(let o=0;o<r.length;o++){let a=r[o];if(a.isClosed())continue;let i=a.url();try{this.originsVisited.delete(new URL(i).origin)}catch{}await YS(a,this.logger),o!==n&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${i}`),await a.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let n=[];for(let a of e.cookies??[]){let i=await this.setCookie(a);n=n.concat(i)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let r=0;for(let a of e.origins??[])for(let i of a.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(a.origin).origin,isLocalStorage:!0},key:i.name,value:i.value}}),r++}catch(s){this.logger.warn({err:s,origin:a},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${r} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await KS(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let n=0,r=null;for(;n<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await qS(this.page,this.logger),o}catch(o){if(r=o,n++,n<=2){this.logger.warn({err:o,retryCount:n,maxRetries:2},`Error saving auth state, retrying (${n}/2)...`);let a=Math.pow(2,n)*100;await new Promise(i=>setTimeout(i,a))}}throw this.logger.error({err:r},"Failed to save auth state after 2 retries"),new A("ActionFailureError",`Failed to save auth state: ${r?.message}`)}async getOpenPages(e){return wu(this.context,e)}saveA11yDetailsToCache(e,n){n.content=e.content,n.name=e.name,n.role=e.role,n.numChildren=e.children.length,delete n.serializedForm,delete n.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:n,locator:r,forceSaveNewCssSelectors:o,startingBoundingBox:a,allowZeroOpacityOverride:i,logger:s=this.logger}){if(e&&this.saveA11yDetailsToCache(e,n),n.frameCache=this.stateManager.saveAutoFrameCacheDetails(n.frameCache),r)try{let l=await this.fetchHtmlAttributes({locator:r,logger:s,startingBoundingBox:a,allowZeroOpacityOverride:i}),c=!1;for(let d of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let u=l?.[d];if(u&&!n[d]){c=!0;break}if(u&&JSON.stringify(u)!==JSON.stringify(n[d])){c=!0;break}}l&&(o||c)&&(n.generatedSelectors=l.generatedSelectors,n.serializedHtml=l.serializedHtml,n.nodeOnlySerializedHtml=l.nodeOnlySerializedHtml,n.hybridSelector=l.hybridSelector)}catch(l){if(l instanceof Rn)throw l;s.warn({err:l},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:n,locator:r,logger:s,boundingBox:a})}catch(l){s.debug({err:l},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:n,logger:r,boundingBox:o}){if(!n)return{scrollPerformed:!1};if(!iu.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(n),o||(o=await n.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return r.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:a=0,y:i=0,width:s=0,height:l=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-l)<1&&Math.abs((e.boundingBox.x??0)-a)<1&&Math.abs((e.boundingBox.y??0)-i)<1)return{scrollPerformed:!0};e.boundingBox=o;let c=await this.screenshot({locator:n,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(c),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async createTargetFromA11yId({id:e,description:n,targetSource:r,skipSaveToCache:o,logger:a=this.logger}){if(e<0)throw new A("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let i=this.stateManager.a11yIdToNodeMap[e];if(!i)throw new A("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,l,c,d,u;if(this.userBrowserSettings.autoExpandIframes&&!s&&i.parentFrame){let f=i.parentFrame,{cache:y,config:b}=await this.stateManager.getAutoFrameDetailsFromHandle(f);c=y,d=b,l=b.frame,u="auto iframe"}else i.parentFrame&&s?(d=s,l=await this.getActivePageOrFrame(),u="hardcoded url already on the state manager"):(l=await this.getActivePageOrFrame(),u="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:l,node:i}),p={id:e,inputDescription:n??void 0,targetSource:r,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Oe(a),frameCache:c},g,h=!1;o||(d&&(a.info({frameConfigSource:u,frameConfig:_y(d)},"A11y node was resolved to a target within an iframe"),g=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(d),h=!0),await this.updateCacheWithNewNodeDetails({node:i,target:p,locator:m,logger:a,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:!0}));try{return{resolution:{locator:m,a11yNode:i,displayString:i.getNodeOnlySerializedForm(),decisions:[]},target:p,frameConfig:d,frameConfigSource:u}}finally{h&&this.stateManager.setActiveFrameConfig(g)}}async resolveTarget(e,n,r={}){let{targetName:o,logger:a=this.logger,signal:i=this.abortSignal,allowZeroOpacityOverride:s}=r;if(n.frameCache&&this.userBrowserSettings.autoExpandIframes){let p,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(n.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){p=f,await J(500,i)}if(!g)throw p}let l=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(l,a,i);let c=Date.now(),d=0,u=0,m;for(;Date.now()-c<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),d++;let p=d===2||Date.now()-c>this.smartWaitingTimeout-2e3&&d%2===0;try{m=await this.resolveTargetHelper({root:l,target:n,primaryOnly:!0,logger:p?a:Xr,allowZeroOpacityOverride:s,signal:i});break}catch(g){if(g instanceof ja)break;if(g instanceof Rn){if(u++,u>2)throw a.error({err:g},"Got multiple cache disqualification errors, giving up"),g;a.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await J(500,i)}i?.throwIfAborted(),p&&a.info({err:g},`Could not resolve target using primary cache only (x${d})`),await J(500,i)}}return m||(m=await this.resolveTargetHelper({root:l,target:n,primaryOnly:!1,logger:a,signal:i,allowZeroOpacityOverride:s}),n.targetSource="HEURISTIC_HEALED",n.targetUpdateTime=new Date().toISOString(),n.targetUpdateLoggerTags=Oe(a),a.info({decisions:m.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:m?.decisions??[],pageState:void 0,targetSource:n.targetSource,targetUpdateTime:n.targetUpdateTime}),m}async resolveTargetHelper({root:e,target:n,primaryOnly:r,logger:o,signal:a,allowZeroOpacityOverride:i}){let s=[],l=(await this.getBrowserState({logger:o,abortSignal:a,skipWait:!0,allowZeroOpacityOverride:i})).serialize(),c;if(n.generatedSelectors||n.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:n,logger:o,allowZeroOpacityOverride:i})}catch(u){c=u,u instanceof En&&s.push(...u.decisions)}if(d)return{...d,pageState:void 0,decisions:[...s,...d.decisions]};r||(s.push({type:"CSS_SELECTOR",matched:!1,reason:c?.message,selectors:yi(n.generatedSelectors??[])}),n.generatedSelectors=void 0,n.hybridSelector=void 0)}if(r)throw c;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:l,target:n,decisions:s,logger:o,signal:a,allowZeroOpacityOverride:i});if(d)return d}throw new En(`Could not find any relevant node given target: ${JSON.stringify(n)}`,s)}async resolveTargetWithPrimaryMethods({root:e,target:n,logger:r,allowZeroOpacityOverride:o}){if(!n.nodeOnlySerializedHtml)throw new ja("Insufficient data to resolve target using primary methods (missing node HTML)");let a=this.userControlledBrowserSettings.hybridSelectorMode,i={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?n.boundingBox:void 0},{css:s,hybrid:l}=await Qe({fn:w=>window.evaluatePrimaryCaches(w),arg:{cssParams:{selectors:n.generatedSelectors??[],cachedElementSerialized:n.nodeOnlySerializedHtml,opts:i},hybridParams:a&&n.hybridSelector?{nodes:n.hybridSelector,cachedElementSerialized:n.nodeOnlySerializedHtml,opts:i}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),c,d,u,m=[];if(a==="prefer"&&l?.result){c=l,d=l.result;let w={type:"HYBRID_SELECTOR",matched:!0,logs:l.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(w),u="HYBRID_SELECTOR"}else if(s?.result)c=s,d=s.result,m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,selectors:d.workingSelectors.slice(0,5)}),u="CSS_SELECTOR";else throw m.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.logs}),l&&m.push({type:"HYBRID_SELECTOR",matched:!1,reason:l.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:l.logs}),new En("Cache evaluation failed",m);let p,g,h,f=!1;if(this.userBrowserSettings.visualActions){let w=d.mPath;if(!w)throw new Error("Found element did not have an mPath despite using visual actions");let C=w.join(" > ");p=e.locator(C),g=this.stateManager.getNodeUsingMPathSelector(C)}else if(d.dataMomenticId!==void 0)h=parseInt(d.dataMomenticId),g=this.stateManager.dataMomenticIdToNodeMap[h],"workingSelectors"in d?(p=e.locator(d.workingSelectors[0]),f=d.workingSelectors.length<5):p=e.locator(pn(h));else throw new A("InternalWebAgentError","Received an element resolution result with no identifying attributes");a&&n.hybridSelector&&(l?.logs.length===1?r.warn({hybridResult:l,cssResult:s,hybridMode:a},"Hybrid selector resolution rejected, continuing..."):l?.result?s?.result&&l?.result&&l.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(l.result.mPath)?r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:a,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==l.result.dataMomenticId&&r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:a,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:a},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let y=yi(n);await this.updateCacheWithNewNodeDetails({node:g,target:n,locator:p,logger:r,startingBoundingBox:d.boundingBox,forceSaveNewCssSelectors:f,allowZeroOpacityOverride:o});let b=Ou(y,n);return b&&Object.keys(b).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Oe(r),n.cacheResolutionUpdateSource=u),{a11yNode:g,displayString:d.serializedElement,locator:p,decisions:m}}async resolveHardcodedCssSelector(e){let{ctx:n,selector:r,logger:o=this.logger,signal:a=this.abortSignal,timeoutMs:i=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),l=Date.now(),c=0,d,u=[];for(;Date.now()-l<i;){a?.throwIfAborted(),c++;let m=s.locator(r),p;try{return await m.waitFor({state:"attached",timeout:1e3}),p=await Yn(m,o)??"",u.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${r} matched an element on the page.`}),n?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:u,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:m,displayString:p,decisions:u}}catch(g){let h=g.message;d=new A("ActionFailureError",`CSS selector '${r}' failed to resolve after ${c} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await J(500,a)}}throw d}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:n,y:r,width:o,height:a}=e.target.boundingBox,i=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!i)return;let s=await i.locator.boundingBox({timeout:3e3});if(!s){this.logger.debug({proposedNode:i.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:l,y:c,width:d,height:u}=s;if(Math.abs(d-o)>10||Math.abs(u-a)>10){this.logger.debug({newW:d,oldW:o,newH:u,oldH:a,proposedNode:i.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!n||!r||!l||!c){this.logger.debug({oldX:n,oldY:r,newX:l,newY:c,proposedNode:i.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(l-n)>100||Math.abs(c-r)>100){this.logger.debug({newX:l,newY:c,oldX:n,oldY:r,proposedNode:i.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return i}async resolveTargetWithSecondaryMethodsHelper({root:e,target:n,decisions:r,logger:o,signal:a,allowZeroOpacityOverride:i}){if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.trim().length<10){let c="Refusing to attempt HTML comparison since the saved element is too short.";r.push({type:"HTML_DISTANCE",matched:!1,reason:c})}else if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.length>50)try{let c=await Qe({fn:u=>window.findClosestElementByLDist?.(u),arg:{nodeOnlySerializedHtml:n.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),d=Math.floor(.05*n.nodeOnlySerializedHtml.length);if(c&&c.closestDistance&&c.closestDistance>=d){let u=`Closest HTML candidate still has too far distance (${c.closestDistance}) from threshold (${d})`;r.push({type:"HTML_DISTANCE",matched:!1,reason:u,distance:c.closestDistance,closestElement:c.closestNodeSerialized})}else{if(c?.error)throw new Error(c.error);if(c?.dataMomenticId||c?.mPathSelector){let u=c.dataMomenticId?parseInt(c.dataMomenticId):void 0,m,p;if(u)m=this.stateManager.dataMomenticIdToNodeMap[u],p=e.locator(pn(u));else if(c.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(c.mPathSelector),p=e.locator(c.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=c.closestNodeSerialized??await Yn(p,o)??"unknown element";o.warn({result:c,originalTarget:n,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=yi(n);await this.updateCacheWithNewNodeDetails({node:m,target:n,locator:p,logger:o,startingBoundingBox:c.boundingBox,allowZeroOpacityOverride:i,forceSaveNewCssSelectors:!0});let f=Ou(h,n);return f&&Object.keys(f).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Oe(o),n.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:c},"Updated cache after l-dist resolution")),r.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${d} string comparison distance of the saved element.`,logs:c.logs,distance:c.closestDistance,closestElement:g,savedElement:n.nodeOnlySerializedHtml}),{locator:p,a11yNode:m,displayString:g,decisions:r,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(c)}`)}}catch(c){o.info({err:c},"Failed to find closest HTML node using levenshtein distance"),r.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${c}`})}let s=n.screenshotUrl,l=n.role??"";if(s&&iu.includes(l))try{let c=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:n,screenshotUrl:s,signal:a,allowZeroOpacityOverride:i});return{...c,decisions:[...r,...c.decisions],pageState:void 0}}catch(c){a?.throwIfAborted(),r.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${c}`,elementImageUrl:s}),o.warn({err:c},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:n,oldTarget:r,signal:o,allowZeroOpacityOverride:a}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let s=await this.screenshot({retries:0}),c=await(await fetch(n)).arrayBuffer(),d=TM(),u=await this.enricher.runTemplateMatching({id:d,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:s.toString("base64")},{signal:o}),{target:m,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowZeroOpacityOverride:a}),g=m.boundingBox?.width,h=m.boundingBox?.height;if(!g||!h)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let f=m.id,y=this.stateManager.a11yIdToNodeMap[f],b=yi(r);await this.updateCacheWithNewNodeDetails({target:r,node:y,locator:p,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:a});let w=Ou(b,r);return w&&Object.keys(w).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=Oe(this.logger),r.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:d,diffs:w,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:y,displayString:m.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:n}]}}async typeIntoTarget(e,n,r={}){await this.highlight(n.locator);let o=await n.locator.getAttribute("type",{timeout:1e3})??"",a=ay.some(i=>i===o.toLowerCase());return await bu({targetingResult:n,options:{force:r.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:a?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,r)}async click(e,n,r={}){return bu({targetingResult:e,options:r,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:n,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:n},r){let o=r?.timeout??this.pageLoadTimeout,a=Date.now(),i=!1,s=e;for(;Date.now()-a<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Js(s,n,r)){i=!0;break}await J(500,this.abortSignal)}if(!i)throw new A("ActionFailureError",`The active page URL ${r?.negated?"still does":"does not"} ${js(n)} in ${o}ms.
3902
- Current tab: ${s}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(l){this.logger.warn({err:l},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,n,r={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await n.boundingBox({timeout:3e3});if(!o)throw new A("ActionFailureError","Could not get bounding box of target element");let a=o.x+o.width/2,i=o.y+o.height/2,s=r.steps??5;await this.page.mouse.move(a,i,{steps:s}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,n,r,o){o&&await this.hover({locator:o});let a=await(await this.getActivePageOrFrame()).evaluate(Su);a||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),a={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+a.left,n+a.top,{steps:r}),await J(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await uo({func:async n=>{await this.scrollIntoViewIfNeeded(n.locator);let r=await n.locator.boundingBox({timeout:3e3});if(!r)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(r.x+r.width/2,r.y+r.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await uo({func:n=>n.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let n=await this.getActivePageOrFrame();await Qe({fn:()=>{let r=document.activeElement;r&&r.nodeType===1&&r.blur()},root:n,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await uo({func:n=>n.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,n,r=!1){await this.highlight(e.locator),await uo({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(n.type==="INDEX"){let a=Number(n.index);if(isNaN(a))throw new A("UserConfigurationError",`Page index ${n.index} is not a number`)}await o.locator.selectOption({value:n.type==="VALUE"?n.value:void 0,label:n.type==="LABEL"?n.label:void 0,index:n.type==="INDEX"?Number(n.index):void 0},{force:r,timeout:3e3})},targetingResult:e})}async press(e,n){let r=n.repeat??1;if(n.convertMeta){let o=yl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<r;o++)await this.page.keyboard.press(e,{delay:n.delayMs??0})}async keyDown(e,n){if(n.convertMeta){let r=yl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of Mu(e))await this.page.keyboard.down(r)}async keyUp(e,n){if(n.convertMeta){let r=yl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of Mu(e))await this.page.keyboard.up(r)}async refresh(e){let n=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let r=0,o=2;for(;r<o;){r++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:n});break}catch(a){this.logger.warn({err:a,attempt:r},`Failed to reload page${r<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:n=2,logger:r=this.logger,skipWaitForPageLoad:o,allowZeroOpacityOverride:a}=e,i=e.abortSignal??this.abortSignal,s=a?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:r,signal:i});let l=0,c;for(;l<n;){l++;try{return await H(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:i,logger:r,filterByViewport:e.filterByViewport,showZeroOpacityElements:s}),{milliseconds:this.pageLoadTimeout*l,signal:i,message:"Getting browser state took too long"})}catch(d){if(i?.throwIfAborted(),c=d instanceof Error?d.message:`${d}`,l>=n)throw d;r.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new A("ActionFailureError",`Getting page content failed after ${n} attempts. Error: ${c}`)}async getViewportOffsetDetails(e){let[n,r,o,a,i]=await Qe({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:n,lowerBound:n+a,leftBound:r,rightBound:r+o,width:o,height:a,devicePixelRatio:this.properties.systemDevicePixelRatio??i}}async waitForDOMStability(e){let{logger:n=this.logger,timeout:r=this.smartWaitingTimeout,signal:o}=e??{},a={value:Date.now()},i=m=>{a.value=Date.now()},s=()=>i("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let l=()=>i("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>l);let c=()=>i("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",c);let d=()=>i("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",d);let u=()=>i("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",u);try{await this.waitForDOMStabilityHelper(a,n,r,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",l),this.cdpClient.removeListener("Page.frameStartedLoading",c),this.cdpClient.removeListener("Page.navigatedWithinDocument",d),this.cdpClient.removeListener("Page.frameRequestedNavigation",u)}}async waitForDOMStabilityHelper(e,n,r,o){let a=!1,i=Date.now(),s,l={quality:25,retries:0,stabilizeBeforeScreenshot:!0},c=!1,d=0;for(;Date.now()-i<r;){if(o?.throwIfAborted(),await J(500,this.abortSignal),s)try{let m=await this.screenshot(l);if(!m.equals(s)){s=m,c=!1;continue}c=!0}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(l)}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){a=!0;break}}let u={duration:Date.now()-i,a11yStableReceived:a,lastTreeUpdateMillisecondsAgo:Date.now()-e.value,screenshotStable:c};a||n.warn(u,"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,n){let{x:r,y:o}=e;this.logger.debug({x:r,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(r,o,{button:n.rightClick?"right":"left",clickCount:n.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,n,r){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(n.x,n.y,{steps:3}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,n,r,o){await this.hoverUsingVisualCoordinates(o);let a=await(await this.getActivePageOrFrame()).evaluate(Su);a||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),a={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+a.left,n+a.top,{steps:r}),await J(250),await this.page.mouse.up()}async getElementLocation(e){let n=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),r=await H(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&r===1&&(r=2);let o=n.documents[0],a=o.layout,i=o.nodes,s=i.nodeName||[],l=i.backendNodeId||[],c=a.nodeIndex,d=a.bounds,u=-1;for(let b=0;b<s.length;b++)if(l[b]===e){u=c.indexOf(b);break}if(u===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,p=0,g=0,h=0]=d[u];m/=r,p/=r,g/=r,h/=r;let f=m+g/2,y=p+h/2;return{centerX:f,centerY:y}}async scrollVertical(e){return Tu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return Tu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async createRawCDPSession(e){let n=await H(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),n}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,n){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(n??this.pageLoadTimeout)}async createNewTab(e,n){let r=await this.context.newPage();await this.changeActivePage(r,n?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...n}),this.handleAvailableTabsChange()}async switchToPage(e,n){let r=!0,o,a=Date.now();for(;r||n?.retry&&Date.now()-a<this.smartWaitingTimeout;){r=!1;try{await this.switchToPageHelper(e,n);return}catch(i){this.logger.warn({err:i},"Error switching to page, retrying..."),o=i,await J(500)}}throw o}async switchToPageHelper(e,n){let r=this.context.pages().map((a,i)=>({page:a,url:a.url(),index:i})),o;if(e.type==="INDEX"){let a=Number(e.index);if(isNaN(a))throw new A("UserConfigurationError",`Page index ${e.index} is not a number`);if(a<0||a>=r.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(r.map(i=>i.url))}`);o=r[a]}else{let a=r.filter(i=>e.type==="SUBSTRING"?i.url.includes(e.substring):i.url.match(e.pattern));a.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(a.map(i=>i.url))}`),o=a[a.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
3903
- Available pages:${JSON.stringify(r.map(a=>a.url))}`);if(!no(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,n?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let n;return typeof e=="string"?n=ds(e):n=[e],await this.context.addCookies(n),n}async setLocalStorage(e,n){let r;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([a,i])=>{a&&localStorage.setItem(a,i||"")},[e,n],`setting local storage key ${e}`);return}catch(a){r=a}if(r)throw r}async solveCaptcha(){await this.getBrowserState({allowZeroOpacityOverride:!0});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let n=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),r=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Pl,task:{type:"ImageToTextTask",body:n.toString("base64"),case:!0},languagePool:"en"})});if(!r.ok){let s=`Captcha solver API returned error response: ${r.statusText}`;throw this.logger.error({text:await r.text()},s),new Error(s)}let{taskId:o}=await r.json(),a=Date.now(),i="";for(;Date.now()-a<6e4;){await J(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Pl,taskId:o})});if(!s.ok){let c=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},c),new Error(c)}let l=await s.json();if(l.errorId){let c=`Captcha solution API returned error ID ${l.errorId}`;throw this.logger.error(c),new Error(c)}if(l.status==="ready"){i=l.solution.text;break}}if(!i)throw new Error("Captcha solution timed out");return i}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},n)=>{this.transformer&&zy({event:n,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,n)=>{this.transformer&&this.transformer.recordKeystroke(n)})}async startRecordingCrons(e){if(e.aborted)return;let n,r=(await this.getOpenPages()).map(s=>s.url),o=0,a=!1,i=async()=>{if(e.aborted||o>8){clearTimeout(n);return}a=!0;let s;try{s=(await this.getOpenPages()).map(c=>c.url),o=0}catch(c){this.logger.debug({err:c},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let c=s.length-1;c>=r.length;c--){let d=s[c];no(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:r,currentUrl:l,newOpenPages:s},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(c)});break}r=s};n=setInterval(async()=>{if(!a){a=!0;try{await i()}catch(s){this.logger.error({err:s},"Error while checking pages during recording")}finally{a=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(n)})}async startRecording(e,n,r){this.logger.debug({isClickToRecord:r},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=o},r),this.transformer=n,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(r=>Array.from(r.querySelectorAll("option")).map(a=>({value:a.value,label:a.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:n,codePath:r}){let o=this.pageLoadTimeout,a=e.url();if(!a.includes("chrome-error://")){try{await to({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlDomContentLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(i){let s=i;if(s.name==="AbortError")throw new A("UserInfrastructureError",`The page with URL ${$e(a,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await to({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlPageLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(i){this.logger.warn({err:i,codePath:r,url:a},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:n=!1}=e??{};return n||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return dM.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:n,error:r}=await Qe({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(r)throw new Error(`Failed to process page HTML: ${r}`);if(!n)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return n}registerDialogHandler(e){let n=async r=>{try{e==="ACCEPT"?await r.accept():await r.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",n)}async evaluateFunctionInAllFrames(e,n){return this.stateManager.executeFunctionInAllFrames(e,n)}async evaluateFunctionInPage(e,n,r,o=2e3){let a=await this.getActivePageOrFrame();return Qe({root:a,fn:e,arg:n,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:r})}async evaluateCodeInPage({code:e,fragment:n,context:r,timeoutMs:o=cr}){let a=ny(),i={code:e,fragment:n,context:r},{result:s}=await H(this.page.evaluate(a,i),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new A("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,n){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let r;try{r=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:n},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:n},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return r}async getDomNodeFromPositionPercentages(e,{percentX:n,percentY:r}){if(n<0||n>1||r<0||r>1)throw new A("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:a,upperBound:i,leftBound:s}=await this.getViewportOffsetDetails(e),l=Math.round(i),c=Math.round(s),d=Math.ceil(o*n),u=Math.ceil(a*r),m=d+c,p=u+l;return this.getDomNodeFromPixelPosition(m,p)}async highlightFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r;try{r=await this.getDomNodeFromPositionPercentages(n,e)}catch{}return r?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:gy,backendNodeId:r.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:r?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r=await this.getDomNodeFromPositionPercentages(n,e);return this.getTargetFromBackendNodeId({root:n,backendNodeId:r.backendNodeId,allowZeroOpacityOverride:e.allowZeroOpacityOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:n,allowZeroOpacityOverride:r}){let o=this.stateManager.domGraph?.backendIdToNode[n];if(!o)throw new Error("No DOM node was found with the given backend ID");let a=o?.attributes[Kn],i=parseInt(a??"");if(!a||isNaN(i))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(pn(i)),l;o.bounds.x!==null&&o.bounds.y!==null&&(l={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let c=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:l,allowZeroOpacityOverride:r}),d={id:-1,dataMomenticId:i,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...c};return this.logger.debug({target:d},"Tied backend ID to HTML node"),{target:d,locator:s}}async performTargetRedirection(e,n,r){try{return await this.scrollIntoViewIfNeeded(e),await H(this.performTargetRedirectionHelper(e,n,r),{milliseconds:3e3})??{locator:e}}catch(o){return n.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,n,r){let o=Date.now(),a=await Yn(e,n);if(r===void 0&&(r=await e.boundingBox({timeout:3e3})??void 0),!r){n.error(`Attempted to click on element with no bounding box: ${a}`);return}let{x:i,y:s,width:l,height:c}=r,d=this.getViewport();if(i<0||s<0||!d||i+l>d.width||s+c>d.height){n.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:m,mPathSelector:p,error:g,serializedElement:h,point:f,force:y,logs:b}=await e.evaluate(C=>{let v=window;if(!v.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return v.performTargetRedirection(C)},void 0,{timeout:1e3}),w=Date.now()-o;if(g){n.warn({error:g,serializedElement:h,duration:w,force:y,logs:b},"Got error from target redirection with bounding box");return}else{if(m)return n.info({newDataMomenticId:m,serializedElement:h,duration:w,force:y,logs:b},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(pn(m)),hints:{clickableXY:f,force:y}};if(p)return n.info({newMPathSelector:p,serializedElement:h,duration:w,force:y,logs:b},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(p),hints:{clickableXY:f,force:y}};if(f)return n.info({point:f,serializedElement:h,duration:w,force:y,logs:b},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:y}};if(y)return n.info({serializedElement:h,duration:w,force:y,logs:b},"Forcing click on original element"),{locator:e,hints:{force:y}}}}async fetchHtmlAttributes({locator:e,logger:n=this.logger,startingBoundingBox:r,allowZeroOpacityOverride:o}){let{hybridSelectorMode:a,showZeroOpacityElements:i}=this.userControlledBrowserSettings,s=await e.evaluate((l,c)=>{let d=window;return d.generateHtmlCacheAttributes?d.generateHtmlCacheAttributes(l,c):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:a==="test"||a==="prefer",startingBoundingBox:r,showZeroOpacityElements:o?!0:i},{timeout:2e3});if("error"in s&&s.error)throw s.error.startsWith(zS)?new ys(s.error):s.error.startsWith(HS)?new bs(s.error):new Error(s.error);return s.warnings.length&&n.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,n){let r=this.getViewport();if(!r)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(r.width*e),a=Math.ceil(r.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:a,button:"left",clickCount:0}}),{x:o,y:a}}async clickMouseFromPositionPercentages(e,n,r){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let a=Math.ceil(o.width*n),i=Math.ceil(o.height*r);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:a,y:i,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,n,r,o){let a=this.getViewport();if(!a)throw new Error("Cannot scroll using percentages without viewport");let i=Math.ceil(a.width*e),s=Math.ceil(a.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:i,deltaY:s,x:r,y:o}}),{deltaX:i,deltaY:s}}canSolveCaptchas(){return!!Pl}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(n){this.logger.debug({err:n,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,n,r,...o){let a=this.context.pages().indexOf(e);a=a===-1?0:a,hu(e,this.debugData,a,{type:n,text:`[MOMENTIC] ${r}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:n}){if(!Il(e)){let l=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(l),this.logToUserConsole(this.page,"error",l);return}let r=n?.trim()||gM(e),o=lM(e),a=hM(e),i=id[a];this.page.once("filechooser",async l=>{this.logger.info({filePath:e,fileName:r},"File chooser triggered");try{if(!Il(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await l.setFiles({name:r,buffer:o,mimeType:uM.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(c){this.logger.error({err:c},"Error handling file chooser"),this.logToUserConsole(this.page,"error",c.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:l,base64Data:c,mimeType:d})=>{let u=window;u.momenticFileName=l,u.momenticFileBase64=c;let m=atob(c),p=new Array(m.length);for(let h=0;h<m.length;h++)p[h]=m.charCodeAt(h);let g=new Uint8Array(p);u.MomenticFile=class extends Blob{kind="file";name=u.momenticFileName;constructor(){super([g],{type:d})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],u.momenticFileName,{type:d})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},u.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new u.MomenticFile])},{fileName:r,base64Data:s,mimeType:i},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let n={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},n}async copy(e){try{await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard")}catch(n){if(n instanceof Error&&n.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(r=>navigator.clipboard.writeText(r),e,"copying text to clipboard");return}throw n}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(n=>{let r=n.request();return e.matches({url:r.url(),method:r.method()})})}registerRequestRecorder(e,n,r){this.requestRecorders[e]={onRequestStart:(o,a)=>{n.matches({url:a.request.url,method:a.request.method})&&r.onRequestStart(o,a)},onRequestComplete:(o,a)=>{n.matches({url:a.request.url,method:a.request.method})&&r.onRequestComplete(o,a)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,n,r){this.customHeaders.push({key:e.toLowerCase(),value:n,matcher:r})}registerMock(e,n,r,o){let a=e??Lu();return this.mocks[a]={matcher:n,generateResponse:r,fetchOriginalResponse:o},a}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return yi(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import FM from"fetch-cookie";import{cloneDeep as ib}from"lodash-es";import{CookieJar as UM}from"tough-cookie";async function Er(t,e={}){let n=await t.getBrowserState(e);return{serializedTree:n.serialize(),tree:n}}var ma=3.1783027;function EM(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);!(r>=48&&r<=57)&&!(r>=65&&r<=90)&&!(r>=97&&r<=122)&&e++}return e}function bi(t){return Math.ceil(_u(t)/ma)}function _u(t){let e=0;if(typeof t=="string"){let n=t;n=n.replaceAll(`
3904
- `,""),n=n.replaceAll(" ","");let r=EM(n);return n.length-r+ma*r}if(typeof t>"u")return 0;if(typeof t=="number")return String(t).length;if(Array.isArray(t))return t.forEach(n=>{e+=_u(n)}),e;if(typeof t=="object"){let n=t;return Object.keys(n).forEach(r=>{e+=String(r).length,r==="image_url"?(n[r]??{}).detail==="high"?e+=1105*ma:e+=85*ma:e+=_u(n[r])}),e}if(typeof t=="boolean")return t?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof t}': ${t}`)}var Yy={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Xy={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},Ky=/<(\S+) id="(\d+)".*?>/g,RM=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Jy=["h1","h2","section","footer","nav","aside","form","label","dialog"],CM=[...Jy,"span","div","h3"],vM=["table","select","form","ul","ol","menu","pre","code","dialog"],AM=["table","form","dialog","nav","section","ul","select"];function Du(t){return t.serializedTree.length>t.maxCharacterLength&&(t.logger.warn({serializedTreeLength:t.serializedTree.length},"Serialized condensed tree is too long to chunk, truncating before chunking"),t.serializedTree=t.serializedTree.slice(0,t.maxCharacterLength)),xM(t)}function xM({serializedTree:t,options:e,logger:n}){let{minChunkTokenCount:r,acceptableChunkTokenCount:o,maxChunkTokenCount:a,maxLineLength:i}=e,s=[],l=t.split(`
3905
- `),c=0,d=[],u=0,m=[],p=[],g=!1;for(;c<l.length;){g&&(s.push({ids:m,content:d.join(`
3906
- `),tokenLength:u}),d=[],u=0,m=p.length?[p[p.length-1].id]:[],g=!1);let h=l[c],f=bi(h);u+=f,h.length>i&&(h=h.slice(0,i));let w=Array.from(h.matchAll(Ky)).map(k=>k&&k.length>=3?{tagName:k[1],id:k[2]}:void 0).filter(k=>!!k),v=Array.from(h.matchAll(RM)).map(k=>k&&(k[2]||k[4])).filter(k=>!!k);v.reverse();let R=h.replace(/ id="[0-9]+"/g,"");d.push(R);for(let k of w)m.push(k.id),p.push(k);for(let k of v){let G=p[p.length-1];G&&G.tagName===k&&p.pop()}let x=p.some(k=>vM.includes(k.tagName)),M=l[c+1]??"",D=bi(M),K=Array.from(M.matchAll(Ky)).map(k=>k&&k.length>2?k[1]:void 0).filter(k=>!!k),P=K.some(k=>Jy.includes(k)),W=K.some(k=>CM.includes(k));u+D>=a&&(g=!0),u>=r&&(P&&!x||v.some(k=>AM.includes(k)))&&(g=!0),u>=o&&W&&!x&&(g=!0),c++}return d.length&&s.push({ids:m,content:d.join(`
3907
- `),tokenLength:u}),s.forEach((h,f)=>{n.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var Fu=4e4,Uu=8e4;async function po(t){let{serializedTree:e,logger:n,aiPageFiltering:r,softTokenLimit:o=Fu}=t;if(bi(e)<o)return e;let i;r?i=Du({serializedTree:e,options:Xy,logger:n,maxCharacterLength:1e6}):i=Du({serializedTree:e,options:Yy,logger:n,maxCharacterLength:3e6});try{return r?await H(IM({...t,chunks:i.chunks}),{milliseconds:2e4}):await H(MM({...t,chunkResult:i}),{milliseconds:15e3})}catch(s){n.warn({err:s},"Error executing page filtering, attempting AI keyword fallback");try{return await PM({...t,chunks:i.chunks})}catch(l){return n.warn({err:l},"Error executing page filtering using keyword matching, using naive truncation"),e.slice(0,Uu*ma)}}}async function IM({chunks:t,generator:e,description:n,type:r,logger:o,signal:a,tree:i,softTokenLimit:s=Fu,hardTokenLimit:l=Uu}){let c=await e.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:s,hardTokenLimit:l},{abortSignal:a,logger:o,loggerTags:Oe(o)}),d=[];t.forEach((m,p)=>{c.indices.includes(p)&&(d=d.concat(m.ids))});let u=i.pruneUsingRelevantIds(new Set(d)).serialize();return o.debug({description:n,type:r,selectedChunks:c,tree:u},"Pruned a11y tree with AI page filtering"),u}async function PM(t){let{type:e,description:n,generator:r,tree:o,logger:a,hardTokenLimit:i=Uu}=t;if(!n.trim())throw new Error("Empty description passed to page filtering");let s=await r.getExtractedKeywords({goal:n},{logger:t.logger,loggerTags:Oe(t.logger)});for(let l of s.keywords){let c=t.chunks.filter(p=>p.content.toLowerCase().includes(l.toLowerCase()));if(!c.length||c.reduce((p,g)=>p+g.tokenLength,0)>i&&c.length>1)continue;let u=c.flatMap(p=>p.ids),m=o.pruneUsingRelevantIds(new Set(u)).serialize();return a.debug({description:n,type:e,selectedChunks:c,tree:m},"Pruned a11y tree with keyword page filtering"),m}throw new Error("No keywords were unique enough for page filtering")}async function MM(t){let{description:e,generator:n,tree:r,logger:o,signal:a,chunkResult:i,softTokenLimit:s=Fu}=t,l=await n.rankChunksWithRag({description:e,chunks:i.chunks,tokenLimit:s},{abortSignal:a,logger:o,loggerTags:Oe(o)});if(l.ids.length===0)throw new Error("RAG returned no important ids");{let c=r.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`))).serialize();return o.debug({browserState:c},"Pruned a11y tree with RAG"),c}}async function zu(t,e){if(!t.description)throw new A("UserConfigurationError","Cannot locate element with empty description");return Mn({action:async()=>LM(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function LM(t,e){let{disableCache:n,testContext:r,filterByViewport:o,skipWait:a,source:i,memory:s,aiPageFiltering:l,logger:c,allowZeroOpacityOverride:d}=t,{ctx:u,orgId:m,browser:p,localCodeEvalTools:g,generator:h,abortSignal:f}=e,y=t.description,b=t.useMemory&&!n;r&&(y=await jt({orgId:m,s:y,context:r,localTools:g,signal:f,logger:c})),i&&(y=NM(y,i));let{serializedTree:w,tree:C}=await Er(p,{allowZeroOpacityOverride:d,filterByViewport:o,abortSignal:f,skipWait:a,logger:c}),v,R=Date.now(),x;for(;!v&&Date.now()-R<3e3;){f.throwIfAborted();try{v=await p.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Ce){x=Ce}}if(!v)throw new A("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${x?.message}`);let M=w,D=!1;M=await po({type:"locator",description:y,serializedTree:w,aiPageFiltering:l,tree:C,logger:c,generator:h}),M!==w&&(D=!0);let K=`data:image/jpeg;base64,${v.toString("base64")}`,P=await h.getElementLocation({browserState:M,goal:y,screenshot:K,source:i,memory:b?s:void 0},{disableCache:n,abortSignal:f,loggerTags:Oe(c),useMemory:b});c.debug({usedRag:D,result:P},"Got locator result");let W=P.id>0;if(u?.details?.push({type:"AI_LOCATION",matched:W,pageState:M,ragUsed:D,thoughts:P.thoughts}),!W)throw new Go(`Could not find any relevant element: ${P.thoughts}`,P.updatedMemory?{type:"GCS_TRACES",traces:P.updatedMemory}:void 0);let{resolution:k,target:G,frameConfig:we}=await p.createTargetFromA11yId({id:P.id,description:y,targetSource:"AI",logger:c});if(k.a11yNode?.properties?.hidden&&k.a11yNode?.properties?.hidden!=="false")throw new A("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${k.displayString}`);return b&&(P.updatedMemory?G.memory={type:"GCS_TRACES",traces:P.updatedMemory}:s&&(G.memory=s)),{thoughts:P.thoughts,target:G,resolution:k,frameConfig:we,screenshot:K}}var OM=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],Qy="<select> element:",Zy="text input or contenteditable element:",eb="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",tb="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",Bu=[Qy,Zy,eb,tb,...OM];function nb(t,e){if(t===e)return!0;for(let n of Bu){if(!t.startsWith(n))continue;let r=t.slice(n.length).trim();if(Bu.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===r)||r===e.trim())return!0}return!!Bu.some(n=>e.startsWith(n)&&e.slice(n.length).trim()===t.trim())}function NM(t,e){if(!t||!e)return t;switch(e){case"SELECT_OPTION":return`${Qy} ${t}`;case"TYPE":return`${Zy} ${t}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${eb}
3908
- ${t}`;case"ELEMENT_CHECK":return`${tb}
3909
- ${t}`;default:return t}}var kM=15;async function Ml({command:t,aiPageFiltering:e,logger:n,fixtures:r,source:o,useMemory:a,maxRetries:i=kM}){if(!t.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=r,l=t.timeout?t.timeout*1e3:s.smartWaitingTimeout,c=Af(l),d=0,u=Date.now(),m,p,g;try{await Mn({action:()=>s.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:s,logger:n})}catch(f){n.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;d<i&&(!h||h-u<l);){r.abortSignal.throwIfAborted(),d!==0&&await J(c,r.abortSignal),h=Date.now();try{if(m=await Mn({action:async()=>{let y=await rb(s,n,r.abortSignal);return p&&p.serializedTree===y.serializedTree&&p.screenshotBuff.equals(y.screenshotBuff)?m:(p=y,ob({command:t,state:y,fixtures:r,useMemory:a,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:d,aiPageFiltering:e,logger:n,source:o}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s}),m?.updatedMemory&&(Bs(t,m.updatedMemory),n.info({updatedMemory:m.updatedMemory,command:t},"Wrote new memory to assertion command")),m?.success)break;throw m?.thoughts?new A("AssertionFailureError",m.thoughts):new A("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){r.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),n.info({err:f},`AI check assert attempt ${d} failed, retrying...`)}finally{d++}}if(!m?.success)try{m=await Mn({action:async()=>ob({command:t,state:await rb(s,n,r.abortSignal),fixtures:r,useMemory:a,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:d,aiPageFiltering:e,logger:n}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s})}catch(f){r.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{d++}if(!m?.success){let f=`AI check still failing after ${d} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new A("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function rb(t,e,n){let[r,o]=await Promise.all([Er(t,{abortSignal:n,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function ob({command:t,state:e,fixtures:n,useConsensus:r,useMemory:o,highlightElementsOnFailure:a,aiPageFiltering:i,attemptNumber:s,source:l,logger:c}){let{browser:d,generator:u,abortSignal:m}=n,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,y=d.url(),b=t.contextChoice??"MULTIMODAL",w=g;b!=="VISION_ONLY"&&(w=await po({type:"assertion",serializedTree:g,description:t.assertion,aiPageFiltering:i,tree:h,generator:u,logger:c,signal:m}),w!==g&&(p.ragUsed=!0),p.pageState=w);let C={goal:t.assertion,url:y,memory:o?t.cache?.memory:void 0,browserState:w,screenshot:f.toString("base64"),contextChoice:b,source:l},R=await(b==="VISION_ONLY"?(x,M)=>u.getVisualAssertionResult(x,M):(x,M)=>u.getAssertionResult(x,M))(C,{useConsensus:r,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:m,logger:c,loggerTags:Oe(c)});return(R.result||a)&&R.relevantElements&&(p.relevantElementsSerialized=R.relevantElements.map(x=>d.getSerializedFormFromA11yId(x)).filter(x=>!!x),await _M(R.relevantElements,d,c)),{success:R.result,thoughts:R.thoughts,afterScreenshotOverride:f,updatedMemory:o?R.updatedMemory:void 0}}async function _M(t,e,n){let r=Date.now();for(let o of t){if(Date.now()-r>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let a=new AbortController;await H(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw a.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(a){n.debug({err:a},"Failed to highlight relevant element after assertion, continuing...");return}}}var DM=3e4;async function ab({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??DM/1e3,a=new AbortController,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([u,m])=>u&&m));i["Content-Type"]="application/json";let s;if(Zo(t.url)&&(s=t.url),n&&ea(t.url,n)&&(s=new URL(t.url,n).toString()),!s)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);let c=await H((async()=>{try{return await r(s,{headers:i,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables}),signal:a.signal})}catch(u){e.error({err:u},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!c)throw new A("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!c.ok){let u,m=await c.text();try{u=JSON.parse(m)}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}throw u?.errors?.length&&u?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}let d={};return c.headers.forEach((u,m)=>{d[m]=u}),{status:c.status,headers:d,json:await c.json()}}var pa=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:n,logger:r,flagStore:o,storage:a,orgId:i,localCodeEvalTools:s,uploadedFileStorage:l,visualDiffScreenshotStorage:c,options:d}){this.orgId=i,this.options=d,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=a,this.uploadedFileStorage=l,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=s,this.generator=n,this.logger=r,this.flagStore=o}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:n,history:r,disableCache:o,langfuseSessionId:a,lastError:i,logger:s=this.logger}){let[l,c]=await Promise.all([Er(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=await po({type:"ai-action",description:e,serializedTree:l.serializedTree,tree:l.tree,logger:s,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),u=`data:image/jpeg;base64,${c.toString("base64")}`,m={url:this.browser.url(),browserState:d,startingScreenshot:n,history:r,goal:e,screenshot:u,lastError:i};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Oe(s)},langfuseSessionId:a})}async promptToCommand({goal:e,startingScreenshot:n,history:r,actionHint:o,disableCache:a,logger:i=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,d]=await Promise.all([Er(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:i}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,m=await po({type:"ai-action",description:e,serializedTree:c.serializedTree,tree:c.tree,logger:i,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),p={url:l,browserState:m,startingScreenshot:n,history:r,goal:e,actionHint:o,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:a,abortSignal:this.executeAbortController.signal,loggerTags:{...Oe(i)},langfuseSessionId:s})}catch(g){throw new A("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Er(this.browser,e)}async locateElement(e){return await zu({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,n){return Mn({action:async()=>{let r=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:r}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:a,caches:i,action:s,options:l,retriesWithAI:c=1}){let d=[];for(let u=0;u<a.length;u++){let m=a[u],p=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:m,cache:i[u],action:async g=>g,options:{...l,targetName:o[u]}});d.push(p)}try{let u=await s(...d.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=d.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:d.map(g=>g.elementInteractedDisplayString),thoughts:p}}catch(u){if(this.throwIfClosed(),c>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:a,caches:a.map(()=>{}),action:s,options:l,retriesWithAI:c-1});throw new A("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapElementTargetingCommand(e){let n=this.logger.child({commandId:e.command.id}),r;for(let o=0;o<2;o++)try{return await Mn({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:n})}catch(a){if(r=a,this.browser.userBrowserSettings.visualActions&&od(a)){n.warn({err:a},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&Ga(a)){n.warn({err:a},"Invalid momentic id error, retrying element targeting command");continue}if(ad(a)&&n.warn({err:a},"Invalid backend node id error, retrying element targeting command"),a instanceof Rn&&a.retryableWithAI){n.warn({err:a},"Element cache disqualification error, retrying element targeting command");continue}throw a}throw r instanceof A?r:new A("ActionFailureError",r?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:n,action:r,options:o,command:a}){let i=this.logger.child({commandId:a.id}),{targetName:s}=o;if(n.type!=="description")throw new A("ActionFailureError","Cannot use selector with non-description target");let l,c=Date.now(),d=Date.now();for(;Date.now()-d<this.browser.smartWaitingTimeout;){c=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:n.elementDescriptor,targetName:s,logger:i});return{result:await r({locator:u.locator}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;l=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-c<500&&await J(500)}}throw l}async wrapElementTargetingCommandHelper(e){let{ctx:n,tracer:r,target:o,originalCache:a,action:i,options:s,command:l}=e,{disableCache:c,useSelector:d,targetName:u,targetHealingInProgress:m,source:p}=s,g=this.logger.child({commandId:l.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,y=!1,b=ib(e.cache);if((!b||c)&&!lc(o))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);c&&(g.info("Cache explicitly disabled for this step"),y=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(y=!0,b=void 0),b?.inputDescription&&!nb(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),y=!0,b=void 0);let w=v=>!!v&&Em(v),C=!0;if(!w(b)){C=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:y,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),y&&await J(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let v;try{v=await zu({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowZeroOpacityOverride:s.allowZeroOpacityOverride,logger:g},this.getControllerFixtures(n))}catch(M){if(M instanceof Go&&M.updatedLocatorMemory){let D={id:-1,...a,memory:M.updatedLocatorMemory};Us({cmd:l,key:u,newTarget:D,logger:g})}throw new A("ActionFailureError",M.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let R=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),x=await i(R);return Us({cmd:l,key:u,newTarget:v.target,logger:g}),m&&(r.heal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=Oe(g)),{result:x,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(n,b,{allowZeroOpacityOverride:s.allowZeroOpacityOverride,targetName:u,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let R=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),x=await i(R);if(Us({cmd:l,key:u,newTarget:b,logger:g}),C){let M=v.decisions.filter(D=>D.matched);if(M.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let D=M[0].type;r.heal({healType:D})}}return{result:x,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let R=!1;if((v instanceof Rn||od(v)||Ga(v)||ad(v)||tg(v)||ng(v))&&(R=!0),v instanceof A&&!R)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let x;return b.memory&&ki(b.memory)&&(x=b.memory),this.wrapElementTargetingCommand({ctx:n,tracer:r,command:l,target:o,cache:void 0,originalCache:a,action:i,options:{...s,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new A("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,n){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,n):{locator:e}}async screenshotWithDimensions(e){return hi(this.browser,e)}async executePresetCommand(e,n,r,o,a){this.options?.slowMoMs&&await J(this.options.slowMoMs);let i=await this.browser.getOpenPages(),s=this.browser.url(),l;try{l=await this.resolveCommandTemplateStrings(r,o)}catch(c){throw this.throwIfClosed(),new A("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await this.executePresetCommandHelper(e,n,r,o,a);return this.browser.userBrowserSettings.visualActions&&Mm(r)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(r.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await CS({beforeUrl:s,command:r,beforePages:i.map(d=>d.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{pS(r,l)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>pu(e)}}async resolveCommandTemplateStrings(e,n){return ll({obj:e,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,n,r,o,a){a=a||"disableCache"in r&&!!r.disableCache;let i=this.logger.child({commandId:r.id});switch(r.type){case"SUCCESS":let s=r.condition;return s?.assertion.trim()?Ml({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!r.assertion.trim())throw new A("ActionFailureError","Missing assertion");if(r.timeout&&r.timeout>1800)throw new A("AssertionFailureError",`AI check timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);return Ml({command:r,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i})}case"AI_EXTRACT":{if(!r.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let f=uh(r.schema);if(f)throw new A("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:r.goal,browserState:g,returnSchema:r.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:a,abortSignal:this.executeAbortController.signal,loggerTags:Oe(i)});if(f.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let y=f.message;throw y.includes("MaxGenerationLengthExceededError")?new A("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):y.includes("AIProviderError")&&y.includes("time")?new A("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Zo(r.url)&&!ea(r.url,this.browser.baseUrl))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${r.url}`);await this.browser.navigate({url:r.url,loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(r.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let l=await this.browser.solveCaptcha();l&&(await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...r,targetName:"target",disableCache:a}}),await this.browser.type(l,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(r.target&&bn(r.target))await this.browser.hoverUsingVisualCoordinates(r.target.pixels);else if(r.target&&r.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:C=>this.browser.hover(C),options:{...r,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:a}});g=b,h=w}let f=this.browser.getViewport()?.height??Nt.height,y=this.browser.getViewport()?.width??Nt.width;switch(r.type){case"SCROLL_UP":await this.browser.scrollVertical(-(r.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(r.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(r.deltaX??y));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(r.deltaX??y);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(r.timeout&&r.timeout>1800)throw new A("UserConfigurationError",`Wait for URL timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=r.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:r.timeout?r.timeout*1e3:void 0,negated:r.negated,caseInsensitive:r.caseInsensitive});break}case"WAIT":if(r.delay>1800)throw new A("UserConfigurationError",`Wait timeout of ${r.delay} seconds exceeds the maximum allowed value of 30 minutes`);let c=r.delay*1e3;await J(c,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"CLICK":{if(bn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:w=>this.browser.click(w,this.createCallbacksForBrowser(this.orgId),r),options:{disableCache:a,targetName:"target",...r}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:y,data:f};return Qs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(r.value),{succeedImmediately:!1,data:r.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(bn(r.fromTarget)&&bn(r.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(r.fromTarget.pixels,r.toTarget.pixels,{hoverSeconds:r.hoverSeconds});break}if(bn(r.fromTarget)||bn(r.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:["fromTarget","toTarget"],descriptions:[r.fromTarget,r.toTarget],caches:[r.cache?.fromTarget,r.cache?.toTarget],action:(f,y)=>this.browser.dragAndDrop(f.locator,y.locator,{hoverSeconds:r.hoverSeconds,steps:r.steps}),options:{useSelector:!!r.useSelector,disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(r.deltaX),h=parseInt(r.deltaY),f=r.steps??5;if(isNaN(g)||isNaN(h))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${r.deltaX}, ${r.deltaY})`);if(r.target&&bn(r.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,r.target.pixels,{force:r.force});break}let y,b,w;if(r.target?.elementDescriptor){let{elementInteractedDisplayString:C,result:v,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:async x=>x.locator,options:{disableCache:a,targetName:"target",...r}});y=v,b=C,w=R}return await this.browser.mouseDrag(g,h,f,y,{force:r.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:b,thoughts:w}}case"SELECT_OPTION":{if(!rr(r.target))throw new Error("Select with x/y is not supported yet");let g=r.target.elementDescriptor,h=r.choice,{elementInteractedDisplayString:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:g},cache:r.cache?.target,action:b=>this.browser.selectOption(b,h,r.force),options:{...r,targetName:"target",disableCache:a,source:Hr(r)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:y}}case"TAB":{let g={loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(r.action,g);break}case"NEW_TAB":await this.browser.createNewTab(r.url,{loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"COOKIE":if(!r.value)break;let d=await this.browser.setCookie(r.value);i.debug({results:d},"Set cookies");break;case"LOCAL_STORAGE":if(!r.value||!r.key)break;await this.browser.setLocalStorage(r.key,r.value);break;case"JAVASCRIPT":{let g;try{r.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:r.code,fragment:r.fragment??!1,context:o.toObjectCopy(),timeoutMs:r.timeout?r.timeout*1e3:void 0}),i.info({result:g},"Executed JavaScript in browser")):g=await yr({orgId:this.orgId,code:r.code,fragment:!!r.fragment,context:o,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){i.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:i})}}})}catch(h){throw this.throwIfClosed(),new A("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new A("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(r.target&&bn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r),await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);break}let g=this.browser.url(),h,f,y=ib(r.target);if(y){let{elementInteractedDisplayString:w,thoughts:C}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:y,cache:r.cache?.target,action:v=>this.browser.typeIntoTarget(r.value,v,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter}),options:{...r,targetName:"target",disableCache:a,disableGlobalLocatorRedirect:!0,source:Hr(r)}});h=w,f=C}else await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Qs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(bn(r.target)){await this.browser.hoverUsingVisualCoordinates(r.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.hover(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!rr(r.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.focus(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(r.target&&!rr(r.target))throw new Error("Blur with x/y is not supported yet");if(!r.target||!r.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:f=>this.browser.blur(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let u=this.browser.url();await this.browser.press(r.value,{repeat:r.repeat,convertMeta:r.convertMeta??!0,delayMs:r.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Qs(u,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new UM,h=FM(fetch,g),f;try{f=new URL(r.url).hostname}catch{}return{data:{...await yS({command:r,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:h}),cookies:Lp(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await ab({command:r,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return SS({ctx:e,tracer:n,command:r,disableCache:a,browser:this.browser,logger:i,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(r.fileSource.type==="URL"?(h=r.fileSource.url,g=await WS({uri:r.fileSource.url,logger:i,orgId:this.orgId})):r.fileSource.type==="USER_FILE"&&(h=r.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(r.fileSource.name,this.orgId)),!g)throw new A("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:r.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!r.storageState.trim())g=void 0;else if(g=await yr({orgId:this.orgId,code:r.storageState,fragment:!1,context:o,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=us.optional().parse(g)}catch(f){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(r.timeout??Tn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(hS(r.assertion)&&!r.useSelector&&r.target.type==="description"&&h&&h!=="v1"){let y={id:r.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${r.target.elementDescriptor}`,iframeUrl:r.iframeUrl,timeout:r.timeout,cache:r.cache&&"memory"in r.cache?{memory:r.cache?.memory}:void 0};try{let b=await Ml({command:y,logger:i,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{y.cache?.memory&&Bs(r,y.cache?.memory.traces)}}let f=await gS({command:r,tracer:n,timeoutMs:g,targetingWrapper:y=>this.wrapElementTargetingCommand(y),fixtures:this.getControllerFixtures(e),disableCache:a});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await Mn({action:async()=>dl({assertion:r.assertion,browser:this.browser,logger:i,timeout:r.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:this.browser,logger:i});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${r.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new wr(r.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[r.key]=h.then(async f=>await Iu(f)).catch(f=>{i.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[r.key];if(!g)throw new A("ActionFailureError",`No listener registered with key: ${r.key}`);let h=r.timeout??10;return{data:await H(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new wr(r.requestMatcher);return this.recordedRequests[r.key]={},this.browser.registerRequestRecorder(r.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[r.key][h]=Cl(f)},onRequestComplete:(h,f)=>{this.recordedRequests[r.key][h]=Cl(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[r.key];if(!g)throw new A("ActionFailureError",`No recorder registered with key: ${r.key}`);return delete this.recordedRequests[r.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return r.requestMatcher&&(g=new wr(r.requestMatcher)),this.browser.setHeader(r.name,r.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(r.key,new wr(r.requestMatcher),async(h,f)=>{let y=await yr({orgId:this.orgId,code:r.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:i,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),b=Gp.parse(y);return new Response(b.body,{status:b.status,headers:b.headers})},r.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(r.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(r.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:n,disableCache:r,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:n,screenshot:o},{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:n,isClickToRecord:r}){this.recordAbortController=n;let o=new vl({signal:n.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,r),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})}};import{z as an}from"zod";var bse=an.object({useSelector:an.boolean().optional(),disableCache:an.boolean().optional(),iframeUrl:an.string().optional(),retriesWithAI:an.number().optional(),targetName:an.union([an.literal("target"),an.literal("fromTarget"),an.literal("toTarget")]),source:Wi.optional(),disableGlobalLocatorRedirect:an.boolean().optional(),allowZeroOpacityOverride:an.boolean().optional(),targetHealingInProgress:an.boolean().optional(),memory:Eo.optional()});import{cloneDeep as BM}from"lodash-es";var zM={showOverlay:!1},Ll=class{sessions=new Map;sessionCountByIp=new Map;latestSessionId;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:n,cleanup:r,clientIp:o,sessionId:a,socket:i}){return this.sessions.set(a,{controller:e,context:n,cleanup:r,clientIp:o,browserBehavior:BM(zM),socket:i}),this.latestSessionId=a,a}removeSession(e,n){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:a}=o;try{a.setClosed(),await a.browser.cleanup()}catch(i){n.error({err:i},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(i){n.error({err:i},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}getLatestSession(){if(this.latestSessionId)return this.getSession(this.latestSessionId)}};function sb(t,e,n,r){let o=Date.now(),a=Date.now(),i,s,l,c,d=!1,u=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let y=l;l=void 0;let b=h.url(),w=f.toEditorDisplayCopy();JSON.stringify(w)===JSON.stringify(i)&&b===c&&o>a||(t.emit("browserState",{logsPerPage:y?.logsPerPage,harPages:y?.harPages,harEntries:y?.harEntries,viewport:h.getViewport(),url:b,iframeSrcUrls:s??[],context:w,isInPageLoad:h.isInPageLoad}),o=Date.now()),c=b,i=w}catch(y){if(!t.connected)return;let b=y instanceof Error?y.message:`${y}`;if(b.includes("Frame was detached")||b.includes("Not attached to an active page")||b.includes("browser has been closed")||b.includes("UserInfrastructureError"))return;n.error({err:y,sessionId:e},"Error grabbing browser state")}},m=setInterval(()=>{let h=r.getSession(e),f=h?.controller?.browser;if(!f||f.closed){n.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(m);return}u(f,h.context)},1e3),p=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(s)||f.logsPerPage.some(y=>y.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),g=setInterval(async()=>{let f=r.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(g);return}else if(d)return;d=!0;try{let y=await f.getAllFrameUrls(),b=f.retrieveAndClearDebugData();p(y,b)&&(s=y,l=b,a=Date.now())}catch(y){n.warn({err:y},"Failed to fetch extended details")}finally{d=!1}},2500);return{timers:[m,g]}}var HM=4;async function lb({socket:t,logger:e,storageFactory:n,uploadedFileStorage:r,visualDiffScreenshotStorage:o,devicePixelRatio:a,generatorFactory:i,enricherFactory:s,authorization:l,flagStoreFactory:c,settingsFactory:d,getOrgId:u,branchGetter:m,globalE2eStateManager:p}){let g=t.id,h=t.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let f=await u({type:"e2e",testId:h}),y=await m?.();e=e.child({testId:h,orgId:f,sessionId:g,branch:y});let b=await i(f,e),w=await s(f,e),C=await c(f),v=await d(f,e),R=await n(f),{testMetadata:x,baseUrl:M,envName:D,browserConfig:_,aiSettings:K,environmentVariables:P,localCodeEvalTools:W}=await go({testId:h,orgId:f,logger:e,storage:R,authorization:l,flagStore:C,settings:v}),k=p.getSession(g);if(k)return e.info("Associating connection with existing session (likely reconnect)"),await k.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:g,orgId:f,testId:h};let G=t.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:G,event:"connect",args:t.handshake.query},"Websocket event (connect)"),G&&p.getCurrentConnectionsByIp(G)>=HM)throw e.error({clientIp:G,sessions:p.getCurrentSessionsByIp(),...t.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(G);try{await $M({socket:t,baseUrl:M,envName:D,testMetadata:x,orgId:f,sessionId:g,logger:e,environmentVariables:P,clientIp:G,devicePixelRatio:a,storage:R,uploadedFileStorage:r,visualDiffScreenshotStorage:o,localCodeEvalTools:W,generator:b,enricher:w,browserConfig:_,aiSettings:K,flagStore:C,globalE2eStateManager:p})}catch(we){throw e.warn({err:we},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(G),we}return{type:"e2e",sessionId:g,testId:h,orgId:f}}async function $M({socket:t,baseUrl:e,envName:n,devicePixelRatio:r,testMetadata:o,orgId:a,sessionId:i,logger:s,storage:l,uploadedFileStorage:c,visualDiffScreenshotStorage:d,localCodeEvalTools:u,generator:m,environmentVariables:p,browserConfig:g,aiSettings:h,clientIp:f,enricher:y,flagStore:b,globalE2eStateManager:w}){let C={viewport:o.advanced?.viewport??Nt,locale:o.advanced?.locale??_o,timezoneId:o.advanced?.timezone??Do,geolocation:o.advanced?.geolocation??Fo,colorScheme:o.advanced?.colorScheme};r&&(C.deviceScaleFactor=r);let v=o.id,R=await hl({settings:g,orgId:a,baseUrl:e,envName:n,testName:o.name,localTools:u,envVariables:p,logger:s,customHeaders:void 0});s=s.child({orgId:a,sessionId:i,testId:v});let x=!1,M=b.isBooleanFlagEnabled("icon_knowledge_base")?await l.fetchIconKnowledgeBase(s):null,D=await kn.init({baseUrl:e,userBrowserSettings:R,enricher:y,storage:l,flagStore:b,logger:s,contextArgs:C,iconKnowledgeBase:M,callbacks:{onTabsChange:(k,G)=>{t.emit("tabs",{tabs:k,activeTab:G})},onScreencastFrame:(k,G)=>{let we=t;x&&(we=t.compress(!0)),we.emit("screenshot",{buffer:k},()=>{G()})},onSvgsCollected:k=>{t.emit("newIconDetected",{numIcons:k.newSvgs.length}),l.saveNewIcons(k,s)}}});await D.navigate({url:e,initialNavigation:!0});let _=new pa({browser:D,generator:m,logger:s,flagStore:b,orgId:a,options:{scratchPadId:void 0,slowMoMs:R.slowMoMs,autoFollowNewTabs:R.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??b.isBooleanFlagEnabled("rag_v2")},storage:l,localCodeEvalTools:u,uploadedFileStorage:c,visualDiffScreenshotStorage:d}),K=sb(t,i,s,w),P=async()=>{K.timers.forEach(k=>clearInterval(k))},W=new Xt({baseUrl:e,testName:o.name,currentUrl:_.browser.url(),variablesFromEnvironment:p,envName:n});if(!t.connected)throw await D.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");t.emit("session",{url:e,userAgent:kn.USER_AGENT,viewport:_.browser.getViewport(),sessionId:i}),w.registerSession({controller:_,context:W,sessionId:i,cleanup:P,clientIp:f,socket:t})}async function go({testId:t,orgId:e,logger:n,storage:r,authorization:o,flagStore:a,settings:i}){let s=await r.fetchTestMetadata(t,n);if(!s)throw new Error(`Test metadata could not found for test ${t}`);let l;o?.type==="API_KEY"&&(l=new gr({httpClient:new xt({...o,logger:n}),fakerSeed:void 0}));let c=s.envs?.find(f=>f.default),d;c&&(d=await r.fetchEnvironment(c.name,n));let u=d&&"browser"in d?d.browser:void 0,m={...i.browser,...u,...s.advanced},p=s.baseUrl||d?.variables?.[at];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let g={...d?.variables};await Promise.all((s.parameters??[]).map(async f=>{let y=await jt({orgId:e,s:f.defaultValue,context:Xt.dummyContext(s.name,d?.name,g),logger:n,localTools:l});g[f.name]=y}));let h={...i.ai,...s.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:d?.name,testName:s.name,browserConfig:m,environmentVariables:g,testMetadata:s,aiSettings:h}}var Hu=class{parentTracer=null;socket;step;constructor({step:e,socket:n,parentTracer:r}){this.socket=n,this.parentTracer=r,this.step=e}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new Rr({parentStep:this.step,socket:this.socket,parentTracer:this})}},Rr=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:n,parentTracer:r}){this.parentTracer=r,this.parentStep=e,this.socket=n}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Hu({step:e.step,parentTracer:this,socket:this.socket})}},Ol=class{constructor(e,n,r,o,a){this.socket=e;this.storage=n;this.orgId=r;this.testId=o;this.stepsBeforeRun=a}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Rr({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Rr({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Rr({parentStep:null,parentTracer:null,socket:this.socket})}};var $u={currentlyExecutingRequests:{}},GM=t=>async(e,n)=>{let{testId:r,orgId:o}=t.metadata,a=await t.flagStoreFactory(o),i=await t.settingsFactory(o,t.logger),s=await t.storageFactory(o),l,c=await go({testId:r,orgId:o,logger:t.logger,storage:s,authorization:t.authorization,flagStore:a,settings:i}),d=`${r}|${c.baseUrl}`;try{let u=$u.currentlyExecutingRequests[d]??0;$u.currentlyExecutingRequests[d]=u+1,l=await WM({...t,...e,...c,done:n})}finally{t.logger.info({result:l,sessionId:t.metadata.sessionId},"Test execution complete"),$u.currentlyExecutingRequests[d]--}},WM=async({socket:t,steps:e,baseUrl:n,testMetadata:r,reInitialize:o,toStep:a,fromStep:i,storageFactory:s,aiSettings:l,browserConfig:c,metadata:d,logger:u,envName:m,testName:p,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:y,globalE2eStateManager:b})=>{let{testId:w,sessionId:C,orgId:v}=d,R=C,x=b.getSession(C);if(!x)throw new Error("No active session found");let{controller:M,context:D}=x;M.setOpen(),u=u.child({testId:w,orgId:v,sessionId:C,runId:R}),u.info({steps:e.map(oe=>`${oe.type}${"command"in oe?` - ${oe.command.type}`:""}`),toStep:a,fromStep:i,reInitialize:o,envName:m,testName:p,baseUrl:n,context:D,flags:M.flagStore.getAllFlags()},"Socket execution parameters");let _=g??{},K=async()=>{o&&(await M.browser.reset({newUrl:n}),D.reset({baseUrl:n,currentUrl:M.browser.url(),variablesFromEnvironment:_,envName:m,testName:p}))},P=await s(v),W=await y(v),k=async()=>{try{await W.resolveStepCacheEntries({schemaVersion:r.schemaVersion,testId:w,stepLists:{steps:e},logger:u})}catch(oe){u.error({err:oe},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await ai({promiseGenerator:async()=>Promise.all([K(),k()]),signal:M.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),M.setOpen()}catch(oe){if(t.emit("finished"),oe.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${oe}`)}let G=jM(e),we={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},Ce={orgId:v,runId:R,testMetadata:r,steps:e,fromStep:i,toStep:a,orgSettings:{ai:l,browser:c}},be={controller:M,context:D,storage:P,codeEvalTools:h,billingReporter:new zo,logger:u},wt={test:{},step:{onDynamicAIActionStatusUpdateEvent:oe=>{t.emit("dynamicCommandStatusUpdate",oe)},onDynamicAIActionEvaluatingEvent:oe=>{t.emit("dynamicCommandEvaluating",oe)},onDynamicCommandGenerated:oe=>{t.emit("dynamicCommandGenerated",oe)},onDynamicCommandExecuted:oe=>{t.emit("dynamicCommandExecuted",oe)}}},Sn=new Ol(t,P,v,w,G),de=await gl({fixtures:be,options:we,callbacks:wt,inputs:Ce,testParams:{tracer:Sn}});return de?.status==="PASSED"?await zs({logger:u,cacheStorage:W,orgId:v,testId:w,originalSteps:{steps:G},updatedSteps:{steps:e}}):de?.status==="FAILED"&&await Hs({logger:u,cacheStorage:W,orgId:v,testId:w,originalSteps:{steps:G},updatedSteps:{steps:e}}),await Sn.finish(),f?.(de),de.status};var cb={event:"execute",createHandler:GM};import{cloneDeep as VM}from"lodash-es";var qM=t=>async({command:e},n)=>{let{logger:r,generatorFactory:o,metadata:a}=t,i=VM(e),s=qh(i);if(s.category!=="NO_DESCRIPTION_PROVIDED"){if(s.category!=="NONE"){n?.({result:s});return}"cache"in i&&(i.cache=void 0);try{let c=await(await o(a.orgId,r)).getLintStepResult({command:i},{logger:r});n?.({result:c})}catch(l){r.error({event:"lint",err:l},"Failed to lint step"),n?.({result:void 0})}}},db={event:"lintStep",createHandler:qM};var KM=({metadata:t,logger:e,storageFactory:n,globalE2eStateManager:r})=>{let{sessionId:o,orgId:a}=t;return async(i,s)=>{let{description:l,command:c,testMetadata:d,returnScreenshot:u}=i;e.info({params:i},`Locate handler called - ${l}`);let m=r.getSession(o);if(!m)throw new Error("No active session found");let{controller:p,context:g}=m;p.setOpen();let h=await n(a),f=Vr.parse(d.advanced??{}),y={},b;if(l){if("useSelector"in c&&c.useSelector)try{let w=await p.locateElementWithSelector(l,"iframeUrl"in c?c.iframeUrl:void 0);b=w.resolution.locator,y={target:w.target,thoughts:w.thoughts}}catch(w){e.warn({err:w},"Failed resolving target with selector"),s({err:`Failed locating element: ${w.message}`,decisions:w instanceof En?w.decisions:void 0});return}else try{let w=await p.locateElement({description:l,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Hr(c),iframeUrl:"iframeUrl"in c?c.iframeUrl:void 0,memory:"cache"in c&&c.cache&&"target"in c.cache&&ki(c.cache.target.memory)?c.cache.target.memory:void 0,logger:e});y={target:w.target,thoughts:w.thoughts},b=w.resolution.locator}catch(w){(async()=>{try{let C=await p.browser.getCondensedHtml({skipWait:!0});e.warn({err:w,html:C.slice(0,1e5)},"Failed locating element with AI")}catch(C){e.warn({err:C},"Failed grabbing HTML after trying to locate element with AI")}})(),s({err:`${w.message}`});return}if(c.type==="SELECT_OPTION"&&b)try{y.options=await p.browser.getSelectOptions(b)}catch(w){e.warn({err:w},"Failed getting select options"),s({err:`Failed getting select options: ${w.message}`});return}e.info({result:y},"Locate handler result")}if(u)try{let{buffer:w,width:C,height:v}=await p.screenshotWithDimensions({clearHighlights:!0,locator:b}),R=await h.uploadScreenshot(w);y.screenshot={data:R,width:C,height:v},e.info({width:C,height:v},"Captured screenshot during locate")}catch(w){e.error({err:w},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${w.message}`});return}if(s({result:y}),b)try{await Promise.all([p.browser.scrollIntoViewIfNeeded(b),p.browser.highlight(b)])}catch(w){e.warn({err:w},"Error highlighting element, continuing...")}}},ub={event:"locate",createHandler:KM};var YM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({event:o,percentX:a,percentY:i})=>{let s=n.getSession(r);if(!s)throw new Error("No active session found");let l=s.controller.browser;if(l.closed||l.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await l.clickMouseFromPositionPercentages(o,a,i)}catch(c){e.error({err:c},"Error performing click during cloud recording in control mode")}}},mb={event:"mouseClickEvent",createHandler:YM};var XM=({metadata:t,generatorFactory:e,logger:n,socket:r,globalE2eStateManager:o})=>{let{sessionId:a,orgId:i,testId:s}=t;return async({stepId:l,parentStepIdChain:c,attribute:d})=>{let u=o.getSession(a);if(!u)throw new Error("No active session found");let{controller:m}=u,p=await e(i,n);m.setOpen(),u.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{u.browserBehavior.showOverlay=!1,await m.stopRecordMode()}catch(y){n.warn({err:y},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(y,b)=>{b.type!=="PRESET_ACTION"||b.command.type!=="CLICK"||(r.emit("targetRecordingUpdate",{type:y,stepId:l,parentStepIdChain:c,command:b.command,attribute:d}),g.abort(),h=!0)};setTimeout(()=>{h||(g.abort(),r.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:l,parentStepIdChain:c,attribute:d}))},1e4),await m.startRecordMode({params:{generator:p,logger:n,testId:s,orgId:i,callbacks:{onActionReceived:y=>f("clickReceived",y),onStepRecorded:y=>f("descriptionGenerated",y)}},abortController:g,isClickToRecord:!0}),r.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:l,parentStepIdChain:c,attribute:d})}},pb={event:"recordTargetClick",createHandler:XM};var JM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");if(o==="Dead")return;let{controller:i}=a;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),await i.browser.keyDown(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key down socket event error");return}throw s}}},gb={event:"keyDownEvent",createHandler:JM};var QM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");if(o==="Dead")return;let{controller:i}=a;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),await i.browser.keyUp(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key up socket event error");return}throw s}}},hb={event:"keyUpEvent",createHandler:QM};var ZM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t,o,a=0,i=(c,d)=>{let u=async()=>{o=void 0};clearTimeout(o),o=setTimeout(u,Math.min(1e3,250*(a+1)))},s,l=0;return async c=>{let d=n.getSession(r);if(!d)throw new Error("No active session found");let{controller:u,browserBehavior:m}=d,p=u.browser;if(p.closed||p.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(c.event==="scroll"){let g=await p.scrollFromPositionPercentages(c.percentX,c.percentY,s?.x??0,s?.y??0),h=d.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}m.showOverlay&&i(p,c);try{let g=await p.moveMouseFromPositionPercentages(c.percentX,c.percentY);l=0,s=g}catch(g){l++,l%5===0&&e.warn({err:g,mouseErrors:l},"Error in socket mouse move handler")}}},fb={event:"mouseMoveEvent",createHandler:ZM};var eL=({metadata:t,generatorFactory:e,socket:n,logger:r,globalE2eStateManager:o})=>{let{sessionId:a,orgId:i,testId:s}=t;return async({stepId:l})=>{let c=o.getSession(a);if(!c)throw new Error("No active session found");let{controller:d,browserBehavior:u}=c,m=await e(i,r);r.info("Starting cloud recording");let p=new AbortController,g=await d.startRecordMode({params:{generator:m,logger:r,testId:s,orgId:i,callbacks:{onActionReceived:(h,f)=>{n.emit("stepRecorded",{stepId:l,step:h,offset:f})},onStepRecorded:(h,f)=>{n.emit("stepRecorded",{stepId:l,step:h,offset:f})}}},abortController:p,isClickToRecord:!1});u.recordingState={transformer:g}}},Sb={event:"recordingStart",createHandler:eL};var tL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{let o=n.getSession(r);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},yb={event:"recordingStop",createHandler:tL};var nL=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:a,settingsFactory:i,globalE2eStateManager:s})=>async(l,c)=>{let{testId:d,sessionId:u,orgId:m}=e;n.info({testId:d,sessionId:u},"Refresh event received");let p=await a(m),g=await i(m,n),h=await r(m),{baseUrl:f}=await go({testId:d,orgId:m,logger:n,storage:h,authorization:o,flagStore:p,settings:g}),y=s.getSession(u);if(!y){t.emit("error",{message:"No session to refresh"});return}let{controller:b}=y;b.setOpen(),await b.browser.refresh();let w=b.browser.getViewport();n.info({baseUrl:f,viewport:w},`Session refreshed for test ${d} at ${f}`),c()},bb={event:"refresh",createHandler:nL};var rL=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:a,settingsFactory:i,globalE2eStateManager:s})=>async()=>{let{testId:l,sessionId:c,orgId:d}=e;n.info({testId:l,sessionId:c},"Reset event received");let u=await a(d),m=await i(d,n),p=await r(d),{baseUrl:g,envName:h,testName:f,environmentVariables:y}=await go({testId:l,orgId:d,logger:n,storage:p,authorization:o,flagStore:u,settings:m}),b=s.getSession(c);if(!b){t.emit("error",{message:"No session to reset"});return}let{controller:w,context:C}=b;await w.browser.reset({newUrl:g});let v=w.browser.baseUrl;C.reset({baseUrl:v,currentUrl:w.browser.url(),variablesFromEnvironment:y,envName:h,testName:f});let R=w.browser.getViewport(),x=kn.USER_AGENT;n.info({baseUrl:g,viewport:R},`Session reset for test ${l} at ${v}`),t.emit("session",{url:v,userAgent:x,viewport:R,sessionId:c})},Tb={event:"reset",createHandler:rL};var oL=({metadata:t,globalE2eStateManager:e})=>{let{sessionId:n}=t;return async({url:r})=>{let o=e.getSession(n);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:r})}},wb={event:"switchTab",createHandler:oL};async function Eb(t){return lb(t)}var Rb=[rS,cb,ub,Tb,bb,eS,wb,db,pb,Sb,yb,fb,mb,gb,hb,nS,tS];var Cb=t=>{let{logger:e}=t,n=new aL(t.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return n.on("connection",async r=>{let o;try{e.info({event:"connection",transport:r.conn.transport.name},"Websocket connection established"),o=await Eb({...t,socket:r,logger:e}),e=e.child(o)}catch(a){e.error({event:"connection",type:"websocket",err:a},"Failed to setup connection"),r.emit("error",{message:a instanceof Error?a.message:`${a}`}),r.disconnect(!0);return}Rb.forEach(a=>iL(a,{...t,socket:r,metadata:o,logger:e}))}),n},iL=(t,e)=>{let n=t.createHandler(e),r=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(t.event)||e.logger.debug({...e.metadata,event:t.event},`Websocket event (${t.event})`);let a=i=>{e.logger.error({event:t.event,type:"websocket",err:i instanceof Error?i:new Error(`${i}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:i instanceof Error?i.message:`${i}`})};try{let i=n.apply(void 0,o);i&&typeof i.catch=="function"&&i.catch(a)}catch(i){a(i)}};e.socket.on(t.event,r)};import{Router as mL}from"express";import{Router as cL}from"express";import wi from"fs";import Ti from"path";import{v4 as dL}from"uuid";import uL from"yaml";import{hostname as sL}from"os";var lL="2.16.0",ut=Is({app:"desktop-server",hostname:sL(),disableConsoleLogs:!0}).child({cliVersion:lL});var ga=cL();async function ju(t){return(await rl(t,ut)).map(r=>{let o=t.modules[r.moduleId];if(!o){S.warn(`Found a dangling module with ID ${r.moduleId} that could not be found on disk.`);return}return{...o,content:r}}).filter(r=>r!==void 0)}ga.get("/",ce(async(t,e)=>{let n=ae(),r=te(n,S),o=await ju(r);e.status(200).json(o)}));ga.post("/",ce(async(t,e)=>{let n;try{n=ug.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{Yr(n.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let r=ae(),o=te(r,S).modules;if(Object.values(o).find(s=>s.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let a=Ti.join(r.rootDir,n.folderPath??"");if(!wi.existsSync(a)||!wi.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let i=await kf({...n,folder:a,project:r});e.status(201).json(i)}));ga.get("/:moduleId",ce(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n=te(ae(),S),r=n.modules[t.params.moduleId];if(!r){e.status(404).json({error:"Module not found."});return}try{let o=await nl(r,n,S);e.json(o)}catch(o){e.status(400).json({err:o})}}));ga.post("/:moduleId/duplicate",ce(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=dg.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Yr(n.name)}catch(h){e.status(400).json({error:h.message});return}let r=ae(),o=te(r,S),a=o.modules[t.params.moduleId];if(!a){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let i=await nl(a,o,S),s=Ti.join(r.rootDir,Ti.dirname(a.relativePath));if(!wi.existsSync(s)||!wi.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let l=ve(n.name),c=Ti.join(s,`${l}.module.yaml`),d=dL(),{stepsToSave:u}=await He({stepLists:{steps:i.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:rn()}}),m={fileType:pe.MODULE,schemaVersion:se,moduleId:d,name:n.name,description:"",enabled:!0,steps:u.steps,parameters:i.parameters,defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums,defaultCacheKey:i.defaultCacheKey,defaultCacheTtl:i.defaultCacheTtl,defaultCacheAllInvocations:i.defaultCacheAllInvocations,autoAuth:i.autoAuth,advanced:i.advanced},p=uL.stringify(m);wi.writeFileSync(c,p,"utf-8");let g={relativeFilePath:Ti.relative(r.rootDir,c)};e.status(201).json(g)}));ga.patch("/:moduleId/metadata",ce(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=mg.parse(t.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}let r=ae(),o=te(r,S);Nf({moduleId:t.params.moduleId,content:n,momenticFiles:o,logger:S,project:r}),e.status(201).json({message:"ok"})}));var vb=ga;var Ab=mL();Ab.get("/",ce(async(t,e)=>{let n=ae(),r=te(n,S),o=new Set;r?.tests&&Object.values(r.tests).forEach(c=>{c.labels?.forEach(d=>o.add(d))});let a=Array.from(o).sort(),i=Object.values(r.tests),s=await ju(r),l={labels:a,tests:i,modules:s};e.status(200).json(l)}));var xb=Ab;import{Router as pL}from"express";var Gu=pL();Gu.get("/",ce((t,e)=>{let n=Uf(ae(),ut);e.status(200).json(n)}));Gu.get("/names",ce((t,e)=>{let r=ae().config.environments?.map(o=>o.name)??[];e.status(200).json(r)}));var Ib=Gu;import{Router as gL}from"express";var Pb=gL();Pb.get("/",ce((t,e)=>{e.status(200).json({userId:el(),orgId:rn()})}));var Mb=Pb;import{Router as hL}from"express";var Nl=hL();Nl.get("/",ce((t,e)=>{let n=Jd().map(r=>({name:r.config.name,configFilePath:r.configFilePath}));e.status(200).json(n)}));Nl.get("/current",ce((t,e)=>{let n=ae();if(!n){e.status(404).json({error:"No project found."});return}let r={name:n.config.name,configFilePath:n.configFilePath};e.status(200).json(r)}));Nl.post("/set",ce((t,e)=>{let n;try{n=gg.parse(t.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}try{let r=ct({configFilePath:n.configFilePath});tl(r,o=>ct({configFilePath:o}))}catch(r){e.status(400).json({error:`Error setting project: ${r}`});return}e.sendStatus(204)}));var Lb=Nl;import{Router as fL}from"express";var Ob=fL();Ob.get("/",ce((t,e)=>{let r={ai:ae().config.ai};e.status(200).json(r)}));var Nb=Ob;import{convertToModelMessages as zL,stepCountIs as HL,streamText as $L}from"ai";import jL from"dedent";import{Router as GL}from"express";import zb from"fs";import So from"path";import{v4 as Hb}from"uuid";import WL from"yaml";import SL from"path";var kl=class{_result=[];_includeSnapshot=!1;_includeTestContext=!1;_includeTest=!1;_isError;_browser;_testContext;_project;_logger;_testPath;constructor(e,n,r,o,a){this._browser=e,this._testContext=n,this._project=r,this._logger=o,this._testPath=a}addResult(e){this._result.push(e)}result(){return this._result.join(`
3886
+ `};var Vn={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"]};var BS="BoundingBoxMovedError",zS="ZeroOpacityError",fl="visual_actions",qn="data-momentic-id";function HS(t,e,n){if(t.length<n)return t;let r=t.indexOf(e);if(r===-1)return t;let o=Math.max(0,r-n/3),a=Math.min(r+n/3,t.length),i=t.indexOf(`
3887
+ `,o);i>0&&i<r&&(o=i);let s=a,c=0;for(;c<1e3&&s>r&&t[s]!==`
3888
+ `;)c++,s--;return s>r&&t[s]===`
3889
+ `&&(a=s),t.slice(o,a)}function hn(t){let e=typeof t=="string"?t:t.toString();return`[${qn}="${e}"]`}import{execSync as uM}from"child_process";import{randomUUID as Mu}from"crypto";import{diff as Lu}from"deep-object-diff";import{existsSync as Al,mkdirSync as mM,readFileSync as pM,writeFileSync as gM}from"fs";import{Jimp as Vy}from"jimp";import hM from"js-beautify";import{cloneDeep as bi}from"lodash-es";import fM from"mime";import{homedir as Nu,hostname as SM,platform as yM}from"os";import{basename as bM,extname as TM,join as ua,resolve as wM}from"path";import{chromium as Ky,devices as EM}from"playwright";import{addExtra as RM}from"playwright-extra";import CM from"puppeteer-extra-plugin-recaptcha";import{v4 as vM}from"uuid";import{rmSync as cy}from"fs";import{basename as lP,join as cP}from"path";import{errors as dP}from"playwright-core";var $S=new Set(["about:blank","chrome-error://chromewebdata/"]);var ou=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],au=1e4,Si=500;import{mkdirSync as UI,rmSync as jS,statSync as BI}from"fs";import*as cu from"node:fs";import zI from"nodejs-file-downloader";import{tmpdir as HI}from"os";import yr,{basename as $I,dirname as jI}from"path";var du="file://",lu=yr.join(HI(),"momentic","downloads"),su=1e4,GI=50*1024*1024;async function GS(t){let{uri:e}=t;return e.startsWith(du)?VI(t):e.startsWith("http")?KI(t):qI(t)}function WI(t,e){let n=yr.join(lu,t,e.slice(du.length)),r=yr.join(lu,t),o=n.startsWith(r);if(!cu.existsSync(n)||!o)throw new A("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return n}async function VI({uri:t,orgId:e}){let n=WI(e,t);return{filePath:n,cleanup:()=>{jS(jI(n),{recursive:!0,force:!0})}}}async function qI({uri:t}){let e=yr.resolve(t);if(!cu.existsSync(e))throw new A("UserConfigurationError",`The referenced file (${t}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function KI({uri:t,logger:e,orgId:n}){let r=new URL(t);r.search&&(r.search="");let o=$I(r.href),a=mu(o),i=yr.extname(a);if(rg.includes(i))throw new Error(`Downloading files with extension ${i} is not allowed.`);let s=uu(n),c=new zI({url:t,fileName:a,directory:s,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:su}),{downloadStatus:l,filePath:d}=await j(c.download(),{milliseconds:su,message:`Download timed out after ${su}ms`});if(l!=="COMPLETE")throw new Error(`Download ended in non-success status: ${l}`);if(!d)throw new Error("File path of successfully downloaded file was empty");let m=BI(d).size;if(m>GI)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:d,fileName:a},"Downloaded file to disk");let p;return{filePath:d,cleanup:()=>{clearTimeout(p),p=setTimeout(()=>jS(s,{recursive:!0,force:!0}),10*60*1e3)}}}function WS(t,e){return`${du}${t}/${e}`}function uu(t){let e=Math.random().toString(36).substring(4),n=yr.join(lu,t,e);return UI(n,{recursive:!0}),n}function mu(t){let e=yr.extname(t),n=yr.basename(t,e);return t=(n.length>100?n.slice(n.length-100):n)+e,t=t.trim().replaceAll(" ","_"),t}async function Kn(t,e){try{return await t.evaluate(r=>window.serializeElementOnlyWithText?.(r,{truncateToLength:500}),void 0,{timeout:1e3})}catch(n){e.debug({err:n},"Failed to get HTML from locator for Playwright error translation");return}}async function VS(t,e){let n=t.evaluate(async()=>{let a=window,i={};try{let s=await indexedDB.databases();for(let c of s){if(!c.name)continue;let l=await a.exportIdbToObject?.(c.name,c.version);l&&(i[c.name]=l)}return[i,void 0]}catch(s){return[void 0,s.message]}}),[r,o]=await j(n,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),r}async function qS(t,e,n){if(e){n.debug("Importing indexedDB data");try{let r=t.evaluate(async o=>{let a=window;for(let[i,s]of Object.entries(o))await a.importObjectToIdb?.(i,s)},e);await j(r,{milliseconds:3e3})}catch(r){n.warn({err:r},"Failed to import indexedDB data")}}}async function KS(t,e){try{let n=t.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(r=>{r.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await j(n,{milliseconds:3e3})}catch(n){e.debug({err:n},"Failed clearing index db data, continuing...")}}async function YS(t,e,n,r,o){try{await YI(t,e,n,r)}catch(a){o.error({err:a,tabIndex:e},"Error handling new console log")}}async function YI(t,e,n,r){let o=r.text();o.length>Si&&(o=o.slice(0,Si)+"...(TRUNCATED)");let a=[];for(let i of r.args())try{let s=await i.jsonValue(),c=JSON.stringify(s);c.length>Si?a.push(c.slice(0,Si)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&a.push(s)}catch{}pu(t,n,e,{url:t.url(),location:r.location(),type:r.type(),text:r.text(),args:a})}function pu(t,e,n,r){let o=Date.now(),a=e.logsPerPage;if(a.length<=n||a[n]===void 0){a[n]=[];for(let i=0;i<n;i++)a[i]===void 0&&(a[i]=[])}a[n].length>au&&(a[n]=a[n].slice(Math.floor(au/2)),a[n]?.push({url:t.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:n})),a[n].push({...r,tabIndex:n,timestamp:o})}async function an({fn:t,codePath:e,logObject:n,signal:r,logger:o}){r?.throwIfAborted();let a=Date.now(),i=await ii({promiseGenerator:t,signal:r,codePath:e,logger:o}),s=Date.now();return n[e]=s-a,i}import XI from"truncate-json";var JI="[redacted due to size]",XS=5e3,QI=5e3;async function QS(t,e,n){let r=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[t]={id:t,startedDateTime:r,title:void 0,pageTimings:{}}}async function gu(t,e){let n=e.timing(),r=new URL(e.url()),o=[...r.searchParams.entries()].map(([s,c])=>({name:s,value:c})),a={...await ey(e),url:r.toString(),method:e.method(),queryString:o,postData:await eP(e)};return{pageref:t,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:a,timings:ty(n).timings}}async function ZS(t,e,n){await n.finished();let r={};try{r=await tP(n)}catch{}let o={...await ey(n),status:n.status(),statusText:n.statusText(),content:r,redirectURL:n.headers().location,_mocked:!1};t.response=o;let a;try{a=await e.sizes(),t.request.bodySize=a.requestBodySize,t.request.headersSize=a.requestHeadersSize}catch{}t.response&&a&&(t.response.bodySize=a.responseBodySize,t.response.headersSize=a.responseHeadersSize,t.response.content.size=a.responseBodySize);let i=e.timing();t.startedDateTime=new Date(i.startTime).toISOString();let{timings:s,total:c}=ty(i);t.time=c,t.timings=s}function yi(t,e,n){t.harEntries||(t.harEntries={}),t.harEntries[n]=e}function JS(t){try{return new Date(t).toISOString()}catch{return}}function ZI(t){let e={name:"",value:""},n=!0;for(let r of t.split(/; */)){let o=r.indexOf("="),a=o!==-1?r.substring(0,o).trim():r.trim(),i=o!==-1?r.substring(o+1,r.length).trim():"";if(n){n=!1,e.name=Ln(a),e.value=Ln(i);continue}a==="Domain"&&(e.domain=Ln(i)),a==="Expires"&&(e.expires=JS(i)),a==="HttpOnly"&&(e.httpOnly=!0),a==="Max-Age"&&(e.expires=JS(Date.now()+ +i*1e3)),a==="Path"&&(e.path=Ln(i)),a==="Secure"&&(e.secure=!0)}return e}async function ey(t){let e=await t.allHeaders(),n=e.cookie?.split(";").map(ZI)??[];return{headers:Object.entries(e).map(([r,o])=>({name:Ln(r),value:Ln(o)})),cookies:n}}async function eP(t){let e=t.postData();if(!e)return;let n=await t.headerValue("content-type"),r={mimeType:n??"application/octet-stream",text:Ln(e),params:[]};if(n==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[a,i]of o.entries())r.params.push({name:Ln(a),value:i?Ln(i):void 0})}return r}async function tP(t){return{mimeType:await t.headerValue("content-type")??void 0,text:Ln(await t.text()),encoding:await t.headerValue("content-encoding")??void 0}}function Ln(t){try{let e=JSON.parse(t),{jsonString:n}=XI(t,QI);return n}catch{return t.length>XS?t.slice(0,XS)+JI:t}}function co(t){return t<0?0:t}function ty(t){return{timings:{blocked:co(t.domainLookupStart),dns:co(t.domainLookupEnd-t.domainLookupStart),connect:co(t.connectEnd-t.connectStart),send:co(t.responseStart-t.requestStart),wait:0,receive:co(t.responseEnd-t.responseStart),ssl:co(t.connectEnd-t.secureConnectionStart)},total:co(t.responseEnd)}}function ny(){return async t=>{let{fragment:e,code:n,context:r}=t,{env:o}=r||{},a=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new a("env",e?`return ${n}`:n)(o))}}}async function et({root:t,fn:e,arg:n,timeout:r,waitForPageLoad:o,codePath:a}){return await o(),await j(t.evaluate(e,n),{milliseconds:r,message:`Timed out ${a} after ${r}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function hu(){return window.lastCursorPos}import{errors as nP}from"playwright-core";async function uo({func:t,action:e,logger:n,callbacks:r,retryTimeoutMs:o,targetingResult:a}){let i=Date.now(),s;for(;Date.now()-i<o;)try{return await t(a)}catch(c){let l=c;if(Wa(l)){n.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[d]=await Promise.all([t(a),r.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return d}else if(l instanceof nP.TimeoutError)n.warn({err:l,rootUrl:(await r.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await rP(l,a.locator,r,n);else throw l}throw s instanceof A?s:new A("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function rP(t,e,n,r){return t.message.includes("attempt #")?oP(t,e,n,r):aP(t)}async function oP(t,e,n,r){let o=t.message.split(/- retrying \w+ action, attempt #\d+/).filter(c=>c.length>0);if(!o.length)return r.warn({err:t},"Failed to parse Playwright error message for translation, returning raw message"),t;let a=o.length>2?o[o.length-2]:o[0];a=a.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3890
+ `,";").replace(/\s+/g," ");let i="",s=await Kn(e,r);if(s&&(i=`Target element HTML: ${$e(s,100,!0)}`),a.includes("element is not enabled"))return new A("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${i}`,{errOptions:{cause:t}});if(a.includes("intercepts pointer events")){let c="",l=a.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(l){let d=(await n.state.getRoot()).locator(hn(l)),u=await Kn(d,r);u&&(c=`Covering element HTML: ${$e(u,100,!0)}`)}return new A("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${i}
3891
+ ${c}`,{errOptions:{cause:t}})}if(a.includes("element is not visible")){let c="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let l=await e.boundingBox({timeout:3e3});l?l.height===0?c="The element you attempted to interact with has zero height.":l.width===0&&(c="The element you attempted to interact with has zero width."):c="The element you attempted to interact with has no bounding box."}catch{}return new A("ActionFailureError",`${c} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${i}`,{errOptions:{cause:t}})}return a.includes("element is outside of the viewport")?new A("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${i}`):t}function aP(t){let e=t.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new A("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:t}});return t}async function ry(t){try{return await iP(t)}catch(e){t.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function iP({locator:t,logger:e}){let[n,r]=await t.evaluate(c=>[c.id,c.tagName.toLowerCase()],{timeout:1e3}),o=await Kn(t,e),a=await t.boundingBox({timeout:1e3});if(a===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(a.width>5||a.height>5||r!=="input")return;if(n)try{let c=t.page().locator(`label[for=${JSON.stringify(n)}]`);return await c.waitFor({state:"visible",timeout:1e3}),{locator:c,relativePoint:void 0}}catch{}let i=await t.evaluate(c=>{let l=window,d=c.parentElement;if(!d)return{type:"error",error:"Input click target has no parent for redirection"};let u=c.getBoundingClientRect(),m=d.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let p={x:Math.min(Math.max(1,u.left-m.left),m.width-1),y:Math.min(Math.max(1,u.top-m.top),m.height-1)},g=l._MOMENTIC_FEATURE_FLAGS?.[fl],h=c.getAttribute(qn),f=!g&&h?hn(h):l.getMPath?.(c)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,serializedForm:d.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(i.type==="error")throw new Error(i.error);let s=t.page().locator(i.selector);return await s.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:i,originalElementDisplayString:o},`Redirected click to parent element with selector: ${i.selector}`),{locator:s,relativePoint:i.relativePoint}}var ay=["date","datetime-local","month","time","week"],oy={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function iy(t){try{await j(sP(t),{milliseconds:3e3})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function sP({root:t,text:e,options:n,logger:r,callbacks:o}){let a=(await et({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!oy[a])return;oy[a].test(e)&&r.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),n.clearContent=!1,r.info("Transforming datetime input to use sequential key presses")}import{z as Ft}from"zod";var sy=Ft.object({doubleClick:Ft.boolean().optional(),rightClick:Ft.boolean().optional(),force:Ft.boolean().optional(),waitForDownload:Ft.boolean().optional(),delayMs:Ft.number().optional(),downloadTimeoutMs:Ft.number().optional(),relativePosition:Ft.object({x:Ft.number(),y:Ft.number()}).optional()}),Jee=Ft.object({repeat:Ft.number().optional(),convertMeta:Ft.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Ft.number().optional()});async function Sl({locator:t,callbacks:e,logger:n,timeoutMs:r=1e3}){try{await fu(e,r);let o=t.evaluate(a=>{let i=window;i.momenticIsEligible=u=>{let p=window.getComputedStyle(u,null).getPropertyValue("display");if(p==="none"||p==="contents")return!1;let g=u.getBoundingClientRect();return!(!g.height||!g.width)},i.removeHighlightTimers=i.removeHighlightTimers||[],i.removeHighlightFunctions=i.removeHighlightFunctions||{};let s=0;for(;!i.momenticIsEligible(a)&&s<3;){if(!a.parentElement)throw new Error("No eligible non-empty parent found for highlighting");a=a.parentElement,s++}let c=a.style.getPropertyValue("outline"),l=a.style.getPropertyPriority("outline");a.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let d=`momentic${Math.floor(Math.random()*1e7)}`;i[d]=()=>{a.style.removeProperty("outline"),a.style.setProperty("outline",c,l),a.getAttribute("style")||a.removeAttribute("style")},i.removeHighlightTimers.push(setTimeout(()=>{i[d](),i.removeHighlightFunctions?.[d]&&delete i.removeHighlightFunctions[d]},5e3)),i.removeHighlightFunctions[d]=i[d]},void 0,{timeout:r});return await j(o,{milliseconds:r}),!0}catch(o){return n.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function fu(t,e=1e3){let n=await t.state.getRoot();await et({root:n,fn:()=>{let o=window,a=o.removeHighlightTimers||[];for(;a.length;){let i=a.pop();clearTimeout(i)}Object.values(o.removeHighlightFunctions??{}).forEach(i=>{i()})},timeout:e,arg:void 0,waitForPageLoad:t.waitForPageLoad,codePath:"removing element highlights"})}async function Su(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return uo({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async n=>dy({...t,targetingResult:n,useVisualClick:e})})}async function uP(t,e){let{redirectionAttempts:n=0}=e;if(n>=2)throw t;try{return await mP(t,e)}catch(r){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t):r}}async function mP(t,e){let{logger:n,redirectionAttempts:r=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let a=await o.getAttribute("id",{timeout:1e3});if(!a)throw t;let i=o.page().locator(`[for=${JSON.stringify(a)}]`);return await i.waitFor({state:"visible",timeout:1e3}),n.warn({err:t},"Attempting locator redirection due to input being covered by label"),dy({...e,targetingResult:{locator:i},redirectionAttempts:r+1})}else throw n.error({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function pP(t){let{browserCallbacks:e,logger:n,targetingResult:r,position:o,options:a}=t,i=await e.state.getRoot(),s=i&&i!==r.locator.page()&&"frameElement"in i?await i.frameElement():null,c;try{c=s?await to({promiseGenerator:async()=>s.boundingBox(),timeoutMs:3e3,logger:n}):null}catch(g){throw new A("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await s?.dispose()}let l=Date.now(),{clickX:d,clickY:u,reason:m}=await fP({frameCoordinates:c,logger:n,targetingResult:r,position:o,options:a}),p=sy.safeParse(a);n.info({frameCoordinates:c,position:o,options:p.success?p.data:void 0,clickLocation:{clickX:d,clickY:u,reason:m},duration:Date.now()-l},"Visual click")}async function gP(t){let{actionSource:e,targetingResult:n,options:r,logger:o}=t,a=t.targetingResult.locator,i=r?.relativePosition??t.position;if(e==="click"&&!i){let c=await ry({locator:a,logger:o});c&&(a=c.locator,i=c.relativePoint??i)}let s=r?.force||n.hints?.force||!1;try{r?.doubleClick?await a.dblclick({button:r.rightClick?"right":"left",timeout:3e3,position:i,delay:r?.delayMs??25,force:s}):await a.click({button:r?.rightClick?"right":"left",timeout:3e3,position:i,delay:r?.delayMs??25,force:s})}catch(c){let l=c;if(yP(l))o.warn({err:l},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:l},"Error clicking on locator, attempting to recover..."),uP(l,{...t,targetingResult:{...a,locator:a}})}}async function dy(t){let{options:e,logger:n,browserCallbacks:r,controllerCallbacks:o,useVisualClick:a,targetingResult:i}=t,s;e?.waitForDownload&&(s=(async()=>{let c=e.downloadTimeoutMs??3e4;try{return await i.locator.page().waitForEvent("download",{timeout:c})}catch(l){return l instanceof dP.TimeoutError?new A("ActionFailureError",`Download did not complete in ${c}ms`):new A("ActionFailureError",`Download failed: ${l.message}`)}})());try{await Sl({locator:i.locator,callbacks:r,logger:n,timeoutMs:1e3})}catch(c){n.warn({err:c},"Error highlighting locator in click, continuing...")}if(a?await pP(t):await gP(t),e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new A("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");n.info("Waiting for download to start and complete");let c=await j(s,{milliseconds:e.downloadTimeoutMs??3e4});if(c instanceof Error)throw c;return{downloadedFile:await SP(c,o.createIsolatedFolder,n)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function hP(t,e){if(e.hints?.clickableXY){let a=(t?.x??0)+e.hints.clickableXY.x,i=(t?.y??0)+e.hints.clickableXY.y;return[{x:a,y:i},"targeting hint"]}let n=await e.locator.boundingBox({timeout:3e3});if(!n)throw new A("ActionFailureError","Element does not have a bounding box");let r=n.x+n.width/2,o=n.y+n.height/2;return[{x:r,y:o},"halfway point of the bounding box"]}async function fP({frameCoordinates:t,logger:e,options:n,targetingResult:r,position:o}){let a,i,s;if(o){let u=await r.locator.boundingBox({timeout:3e3});a=(t?.x??0)+(u?.x??0)+o.x,i=(t?.y??0)+(u?.y??0)+o.y,s="predefined position"}else{let[u,m]=await hP(t,r);a=u.x,i=u.y,s=m}let c=r.locator.page(),l=n?.rightClick?"right":"left",d=n?.delayMs??25;return n?.doubleClick?await c.mouse.dblclick(a,i,{button:l,delay:d}):await c.mouse.click(a,i,{button:l,delay:d}),{clickX:a,clickY:i,reason:s}}async function SP(t,e,n){n.info("Download detected, saving file to disk");let r=await t.path(),o=mu(t.suggestedFilename()),a=e();await t.saveAs(cP(a,o)),cy(r,{force:!0}),setTimeout(()=>{cy(a,{recursive:!0,force:!0})},5*60*1e3);let i=WS(lP(a),o);return n.info({uri:i,downloadFolder:a},"Saved download to isolated folder"),i}function yP(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as bP}from"os";var TP={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function wP(){let t=bP();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function uy(t){return JSON.stringify(t.split("+").sort())}function yl(t){let e=wP(),n=uy(t);for(let r of Object.values(TP))if(Object.values(r).some(o=>uy(o)===n))return r[e];return process.platform==="darwin"?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function yu({frame:t,page:e,deltaX:n,directionX:r,deltaY:o,directionY:a,signal:i,callbacks:s,logger:c}){if(!n&&!o)return;let l=r==="left"?-1:1,d=a==="up"?-1:1;if(t)await et({root:t,fn:([u,m,p,g])=>window.scrollTo(window.scrollX+(u??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[n,o,l,d],waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let u=e.viewportSize()||Nt,m=await et({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[p,g,h]=await et({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let b=f.getBoundingClientRect();return[f.scrollTop,b.x,b.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((n??u.width)*l,(o??u.height)*d);try{let f=Date.now();for(;Date.now()-f<2e3;){i?.throwIfAborted();let b=await j(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[y,E,v]=await j(e.evaluate(()=>{let R=document.activeElement;if(!R)return[void 0,void 0,void 0];let C=R.getBoundingClientRect();return[R.scrollTop,C.x,C.y]}),{milliseconds:1e3});if(b===m&&y===p&&E===g&&v===h)break;m=b,p=y,g=E,h=v,await J(500)}}catch(f){c.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function bu(t,e){let n,r;for(let o=0;o<4;o++)try{return n=t.pages(),await Promise.all(n.map(async a=>{let i="";try{i=e?.getTitles?await a.title():""}catch{i="Unknown page"}return{title:i,url:a.url()}}))}catch(a){r=a,await J(500)}throw new Error(`Failed to get tab titles after all retries: ${r?.message}`)}import{randomUUID as MP}from"crypto";import{cloneDeep as wu}from"lodash-es";function br(t,e){let n=t.findIndex(r=>r===e);if(!(n===-1||!t[n+1]))return t[n+1]}import{createHash as EP}from"crypto";var RP="v1";function bl(t,e){if(t.tagName.toLowerCase()==="svg"&&!vP(t))try{let n=my(t,e),r=CP(JSON.stringify(n));return{version:RP,json:n,hash:r}}catch{return}}function CP(t){return EP("md5").update(t).digest("hex")}function my(t,e){let n=t.tagName.toLowerCase(),r=AP(t);if(n==="image"&&r["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:n,props:r,children:[]};for(let a of t.childrenBackendIds){let i=e.backendIdToNode[a];if(i&&i.nodeType===1){let s=my(i,e);s&&o.children.push(s)}}return o}function vP(t){let e=t.computedStyles.display,n=t.computedStyles.visibility,r=t.computedStyles.opacity;return e==="none"||n==="hidden"||r==="0"}function AP(t){let e={},n=t.attributes;for(let r of Object.keys(n))Vn.visualAttributesForSvgSerialization.includes(r)&&(e[r]=n[r]);return n.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=n.id),e}var mo={r:147,g:196,b:125,a:.55},gy={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:mo,paddingColor:mo,borderColor:mo,marginColor:mo,eventTargetColor:mo,shapeColor:mo,shapeMarginColor:mo,showInfo:!0,showAccessibilityInfo:!0};function hy({snapshot:t,devicePixelRatio:e,computedStylesToFetch:n,logger:r}){let o=t.strings,a=t.documents,i={},s={},c={roots:[],backendIdToNode:i,frameIndexToIframeNode:s};return a.forEach((l,d)=>{let u=xP({allDocuments:a,stringConstants:o,computedStylesToFetch:n,devicePixelRatio:e,frameIndex:d,backendIdToNode:i,frameIndexToIframeNode:s,logger:r});c.roots.push(u)}),c}function xP({allDocuments:t,stringConstants:e,computedStylesToFetch:n,devicePixelRatio:r,frameIndex:o,frameIndexToIframeNode:a,backendIdToNode:i,logger:s}){let c=t[o],l=c.layout,d={};l.nodeIndex.forEach((x,I)=>{d[x]=I});let u=l.styles,m=l.bounds??[],p=c.nodes,g=p.contentDocumentIndex??{index:[],value:[]},h=p.backendNodeId??[],f=p.attributes??[],b=p.parentIndex??[],y=p.nodeName??[],E=p.nodeType??[],v=p.pseudoType??{index:[],value:[]},R=p.inputChecked??{index:[]},C=e[c.frameId];for(let x=0;x<h.length;x++){let I=h[x],D=E[x],k=f[x]??[],q=b[x]!==void 0&&b[x]>=0?b[x]:void 0,$=q!==void 0?h[q]:void 0,_=$!==void 0?i[$]:void 0,M=v.index.indexOf(x),z=M!==-1?e[v.value[M]]:void 0,ue=d[x],oe;ue?oe=m[ue]??[]:oe=[];let ke=y[x]!==void 0?e[y[x]]?.toLowerCase():void 0;if(!ke){s.warn({backendNodeId:I,frameId:C,frameIndex:o,nodeBounds:oe},"DOM node has no tag name");continue}let je={backendNodeId:I,psuedoType:z,nodeType:D,frameIndex:o,parentFrameId:C,ownedFrameId:void 0,bounds:{x:oe[0]??null,y:oe[1]??null,width:oe[2]??null,height:oe[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:$??null,tagName:ke,parent:_??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};_&&_.childrenBackendIds.push(I);let Vt=g.index.indexOf(x);if(Vt!==-1){let Z=g.value[Vt];a[Z]=je;let _e=t[Z]?.frameId;je.ownedFrameId=_e!==void 0?e[_e]:void 0}for(let Z of Object.keys(je.bounds)){let _e=Z;je.bounds[_e]!==null&&(je.bounds[_e]/=r)}let tt=ue!==void 0?u[ue]??[]:[];for(let Z=0;Z<tt.length&&!(Z>=n.length);Z++){let _e=tt[Z];if(_e===void 0||isNaN(_e))continue;let Re=e[_e];if(Re===void 0)continue;let ln=n[Z];je.computedStyles[ln]=Re}for(let Z=0;Z<k.length;Z+=2){let _e=k[Z],Re=k[Z+1];if(!_e||!Re)continue;let ln=e[_e],Ir=e[Re];!ln||!Ir||(je.attributes[ln]=Ir)}R.index.includes(x)&&(je.attributes.checked="true"),i[je.backendNodeId]=je}return i[h[0]]}function Tu(t,e){if(t.mPathSelector)return t.mPathSelector;let n=t.parent,r;if(!n)r=t.tagName;else if(t.tagName==="body")r="body";else{let a=n.childrenBackendIds.filter(c=>e.backendIdToNode[c]?.nodeType===1&&!e.backendIdToNode[c]?.psuedoType).indexOf(t.backendNodeId),i=` > ${t.tagName}:nth-child(${a+1})`;r=`${Tu(n,e)}${i}`}return t.mPathSelector=r,r}function py(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var IP=["html","#document","#document-fragment"];function fy({node:t,domGraph:e}){let n=[],r=t,o=py(t,e);if(!o)return[t.tagName];let a=()=>{if(r=o,o=py(o,e),!o&&r.frameIndex!==0)throw new Error("No parent node but not in main frame")},i=0;for(;o&&i<1e6;){if(i++,IP.includes(r.tagName)){a();continue}if(r.tagName==="body")n.push("body");else{let c=!1,l=1;for(let d=0;d<o.childrenBackendIds.length;d++){let u=o.childrenBackendIds[d],m=e.backendIdToNode[u];if(u===r.backendNodeId){n.push(`${r.tagName}:nth-child(${l})`),c=!0;break}else m?.nodeType===1&&!m.psuedoType&&l++}if(!c)throw new Error(`Could not find child (${r.tagName}) in parent's children list (${o.tagName})`)}a()}return n.reverse()}function Sy(t,e){let n=t.locator("html"),r=[];for(let o=0;o<e.length;o++){let a=e[o];if(r.push(a),a.startsWith("iframe")){let i=r.join(" > ");r=[],o<e.length-1?n=n.frameLocator(i):n=n.locator(i)}}if(r.length&&(n=n.locator(r.join(" > "))),"owner"in n)throw new Error("Final locator from mpath is a frame locator");return n}async function yy(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:n.nodeId},timeout:2e3})).attributes,a=br(o,qn);if(!a)throw new Error(`Could not find attribute ${qn} for object ${e}`);return a}function by(t){let e=[];for(let n=0;n<t.domGraph.roots.length;n++){let r=t.domGraph.roots[n],o=PP({root:r,domGraph:t.domGraph,existingHashes:t.existingHashes,flagStore:t.flagStore,logger:t.logger});e=e.concat(o)}return e}function PP(t){let{root:e,domGraph:n,existingHashes:r}=t,o=[],a=[e];for(;a.length;){let i=a.pop();if(i.nodeType===1&&i.tagName.toLowerCase()==="svg"){let s=bl(i,n);s&&!r[s.hash]&&o.push(s)}for(let s of i.childrenBackendIds){let c=n.backendIdToNode[s];c&&a.push(c)}}return o}var LP=["focusable","keyshortcuts","controls","live","relevant","orientation"],OP=["selected","readonly","modal","required","invalid"],NP=["id","name","role","content"],Ty=["absolute","fixed","sticky"],kP=["path"],_P=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],Ry=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Cy=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],DP=["menulistpopup","statictext","inlinetextbox"],FP=80,wy=100,vy=50,Cu=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],UP=["cite"],BP={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},zP={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Ey={indentLevel:0},Eu=class t{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;importantProperties;pathFromRoot;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,this.importantProperties=e.importantProperties,e.properties&&e.properties.forEach(n=>{n.name==="keyshortcuts"?this.dataMomenticId=parseInt(n.value.value):this.properties[n.name]=n.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let n=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(n&&n.length<vy?n:""),this.role=this.role||(e.domNode.attributes.role??""),GP(this.properties,e.domNode,e.importantProperties)}VP(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(e){if(this.domNode&&kP.includes(this.domNode.tagName)||this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(r=>Cy.includes(r)))return!1;if(e){if(Object.keys(this.domNode?.attributes??{}).some(o=>My(o,e)))return!0;let r=this.domNode?.attributes.class?.split(" ");if(r&&r.length>0&&r.some(o=>Ly(o,e))||e.styles?.some(o=>{let a=o.split(":");if(a.length!==2)return!1;let i=a[0]?.trim(),s=a[1]?.trim();if(i===void 0||s===void 0)return!1;let c=this.domNode?.computedStyles[i];return c!==void 0&&(c===s||s==="*")}))return!0}if(_P.includes(this.role.toLowerCase())||this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Vn.alwaysInterestingTruthyPropertyNames.some(r=>!!this.properties[r]))return!0;let n=this.properties.class;return typeof n=="string"&&n.split(" ").some(r=>Py(r))?!0:this.children.every(r=>r.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(r=>r.role==="StaticText")||this.children.length>1&&this.children.some(r=>r.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(r=>r.startsWith("data"))}serialize(e=Ey){let n=Object.assign({},Ey,e),{indentLevel:r,noChildren:o,noProperties:a,noId:i,noContent:s,condensedMode:c}=n,l=wu(this.properties),d=" ".repeat(r),u=this.role||"",m=this.tagName??"unknown",p=this.name;u==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(R=>!R.superseded&&R.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(R=>!R.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let R=h.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===p&&(p="")}let f=Cu.includes(this.role)||UP.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${d}${p}
3892
+ `;let b=`${d}<${m}`;!i&&!f&&(b+=` id="${this.id}"`);let y=s??!1;(l.multiline||l.contenteditable)&&this.children.length>0&&(y=!0),u&&u!=="generic"&&u!==m&&!(BP[u]??[]).includes(m)&&(b+=` role=${JSON.stringify(u)}`),p&&(b+=` name=${JSON.stringify(p)}`),this.content&&!y&&(b+=` content=${JSON.stringify(this.content)}`);let E=Date.now();if(Object.keys(l).length>0&&!a){if(Date.now()-E>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(l).forEach(([R,C])=>{if(!LP.includes(R)){{if(OP.includes(R)&&(!C||C==="false"))return;if(R==="value"&&y&&(l.type==="text"||this.role==="textbox"))return;if(R==="level"&&`${C}`=="1")return;if(R==="url"&&l.src&&m==="img")return;if(R==="url"&&l.href&&m==="a")return;if(R==="editable"&&C==="plaintext")return;if(R==="type"&&C===m)return;if(c&&!zP[R])return}typeof C=="string"?b+=` ${R}="${$e(C,wy,!0)}"`:typeof C=="boolean"?C?b+=` ${R}`:b+=` ${R}={false}`:typeof C<"u"&&(b+=` ${R}={${$e(JSON.stringify(C),wy,!0)}}`)}})}if(m==="::before"||m==="::after"){let R="";for(let C of this.children)R+=C.serialize({...e,indentLevel:r,neighbors:0});return R}let v=e.maxLevel!==void 0&&r/2>=e.maxLevel;if(this.children.length===0||o||v)b+=` />
3893
+ `;else{let R="";for(let x of this.children)R+=x.serialize({...e,indentLevel:r+2,neighbors:0});let C=R.trim();C.length<=FP&&!C.includes(`
3894
+ `)?b+=`>${C}</${m}>
3895
+ `:b+=`>
3896
+ ${R}${d}</${m}>
3897
+ `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let R=this.parent.children.findIndex(I=>I.id===this.id),C=R>0?this.parent.children[R-1]?.serialize({...e,neighbors:0}):"",x=R<this.parent.children.length-1?this.parent.children[R+1]?.serialize({...e,neighbors:0}):"";return`${C||""}
3898
+ ${b}
3899
+ ${x||""}`}return b}shallowClone(){let e=new t({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:wu(this.internalProperties),importantProperties:this.importantProperties,parentFrame:this.parentFrame});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=wu(this.properties),e}},Ru=class t{constructor(e,n,r,o){this.root=e;this.a11yIdNodeMap=n;this.dataMomenticIdMap=r;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingRelevantIds(e){let n=this.root;if(!n)throw new Error("Cannot prune a11y tree with no root");function r(a,i=!1){let s=e.has(`${a.id}`)||a.id===n?.id,c=a.shallowClone(),l=a.children,d=!1,u=[];for(let m of l){let p=r(m,s||d);p&&(u.push(p),p.parent=c,d=!0)}if(c.children=u,s||d)return c;if(Cu.includes(a.role)&&i)return c}let o=r(n);return new t(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function HP(t){return t.name?.value?`"${t.name.value}"`:t.role?.value&&t.role.value!=="none"&&t.role.value!=="generic"?`"${t.role.value}"`:`"${t.nodeId}"`}function $P(t,e,n,r){return t.bounds.x===null||t.bounds.y===null||t.bounds.height===null||t.bounds.width===null||t.bounds.width===0||t.bounds.height===0?!0:t.bounds.x+t.bounds.width<e.leftBound||t.bounds.x>e.rightBound?(Cs({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport horizontally"),!1):t.bounds.y+t.bounds.height<e.upperBound||t.bounds.y>e.lowerBound?(Cs({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport vertically"),!1):t.computedStyles.display==="none"?(n.debug({domNode:t},"Filtering out node since it has display none"),!1):!0}async function Ay({node:t,parent:e,frameId:n,frameContext:r,axGraph:o,domGraph:a,inputNodeMap:i,showZeroOpacityElements:s,filterByViewport:c,viewportDetails:l,useMPaths:d,importantProperties:u,cdpClient:m,logger:p,callId:g}){if(!e&&t.parentId)throw new Error(`Got no parent for accessibility node ${t.nodeId}: ${JSON.stringify(t)}`);let h=(_,M={})=>{},f=t.backendDOMNodeId,b=DP.includes(t.role?.value?.toLowerCase()??"");if(!b&&f===void 0)return h("Filtering out node since it doesn't exist in the DOM"),[];let y=f?a.backendIdToNode[f]:void 0;if(!b&&!y)try{let _=await j(m.send({method:"DOM.describeNode",params:{backendNodeId:f}}),{milliseconds:750,fallback:()=>{p.debug("Timeout getting node from CDP while processing a11y tree")}});if(_&&_.node.nodeName.toLowerCase()==="slot"&&_.node.distributedNodes?.length)p.debug({redirectedDomNode:y,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:t,cdpResult:_},"Redirecting node to assigned slot");else return h("Filtering out node since it doesn't exist in the DOM",{cdpResult:_}),[]}catch(_){return h("Filtering out node since it doesn't exist in the DOM",{err:_}),[]}if(y&&e&&c&&l&&t.backendDOMNodeId&&!$P(y,l,p,g))return y.momenticIgnored=!0,[];if(y&&y.computedStyles.display==="none")return y.momenticIgnored=!0,[];if(y&&y.computedStyles.opacity==="0"&&s!==!0){if(s==="inputs-only"&&y.tagName.toLowerCase()!=="input")return y.momenticIgnored=!0,[];if(s===!1)return y.momenticIgnored=!0,[]}let E=t.name?.value?typeof t.name.value=="string"?t.name.value:`${t.name.value}`:"",v=t.value?.value?typeof t.value.value=="string"?t.value.value:`${t.value.value}`:"",R=new Eu({domNode:y,id:parseInt(t.nodeId),role:t.role?.value||"",name:E,nameSources:t.name?.sources,content:v,properties:t.properties,children:[],ignoredReasons:t.ignoredReasons?.filter(_=>Ry.includes(_.name)||Cy.includes(_.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+HP(t),backendNodeID:t.backendDOMNodeId,ignoredByCDP:t.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},importantProperties:u,parentFrame:r.type==="root"?void 0:r}),C=r,x=i[n],I=n;if(y?.tagName.toLowerCase()==="iframe"&&y.ownedFrameId){let _=r.childFrames.find(ue=>ue.frameId===y.ownedFrameId),M=o[_?.frameId??""]?.root,z=i[_?.frameId??""];if(_&&M&&z){t.childIds&&t.childIds.length>0&&p.debug("Replacing existing node's children with children from the iframe");let ue=M;t.childIds=ue.childIds,C=_,x=z,I=_.frameId}}let D=y?.childrenBackendIds?.length??0,k=(t.childIds??[]).filter(_=>!!x.get(parseInt(_))).length;if(D>k){let _=t.childIds?.map(z=>x.get(parseInt(z))).filter(Boolean).map(z=>z?.backendDOMNodeId).filter(z=>z!==void 0)??[],M=0;for(let z of y?.childrenBackendIds??[]){if(_.includes(z)){M=(t.childIds?.findIndex(Vt=>x.get(parseInt(Vt))?.backendDOMNodeId===z)??0)+1;continue}let ue=a.backendIdToNode[z];if(!ue||ue?.tagName.toLowerCase()!=="svg")continue;let oe=Math.floor(-1*Math.random()*1e7),ke={nodeId:oe.toString(),parentId:t.nodeId,ignored:!1,backendDOMNodeId:z,frameId:I,role:{type:"string",value:"graphics-symbol"}};x.set(oe,ke),t.childIds||(t.childIds=[]),t.childIds.splice(M,0,oe.toString()),M++}}if(t.childIds?.length===1&&y){let _=x.get(parseInt(t.childIds[0])),M=_?.role?.value,z=y.childrenBackendIds;if(_&&M==="StaticText"&&z.length===1){let ue=a.backendIdToNode[z[0]];if(ue?.tagName?.toLowerCase()==="span"){let oe=Math.floor(-1*Math.random()*1e7).toString(),ke={nodeId:oe,parentId:t.nodeId,ignored:!1,backendDOMNodeId:ue.backendNodeId,frameId:I,childIds:[_.nodeId]};_.parentId=oe,x.set(parseInt(oe),ke),t.childIds=[oe]}}}for(let _ of t.childIds??[]){if(!_)continue;let M=x.get(parseInt(_));if(!M)continue;let z=await Ay({node:M,parent:R,domGraph:a,axGraph:o,frameId:I,frameContext:C,inputNodeMap:i,cdpClient:m,logger:p,callId:g,filterByViewport:c,showZeroOpacityElements:s,importantProperties:u,viewportDetails:l,useMPaths:d});z.length&&(R.children=R.children.concat(z))}if(R.role==="StaticText"&&(R.children=[]),R.children.length===1&&R.children[0].role==="StaticText"){let _=R.name,M=R.children[0]?.name;(_===M||!M)&&(R.children=[])}let q=[];for(let _=R.children.length-1;_>=0;_--){let M=R.children[_];if(M.role!=="StaticText"){q.push(M);continue}if(_===0||R.children[_-1].role!=="StaticText"){q.push(M);continue}R.children[_-1].name+=M.name}if(R.children=q.reverse(),!R.isInteresting(u)&&t.parentId)return y&&(y.momenticIgnored=!0),R.children;for(let _ of R.children)_.parent=R;return WP(R),y&&d&&Tu(y,a),[R]}function xy({node:t,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,domGraph:a,useMPaths:i,selectorToNodeMap:s,iconKnowledgeBase:c,startId:l=1}){t.id=l,l+=1,e[t.id]=t,t.dataMomenticId?n[t.dataMomenticId]=t:Cu.includes(t.role);let d=t.backendNodeId,u=d!==void 0?a.backendIdToNode[d]:void 0;if(i&&u&&u.mPathSelector&&(s[u.mPathSelector]=t),c&&u&&u.tagName?.toLowerCase()==="svg"){let m=bl(u,a),p=m?c[m.hash]:void 0,g=p?p.description:void 0;p&&(t.properties["data-momentic-description"]=g)}for(let m of t.children)l=xy({node:m,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,startId:l,useMPaths:i,domGraph:a,selectorToNodeMap:s,iconKnowledgeBase:c});return l}async function Iy({rawA11yGraph:t,domGraph:e,startingFrameId:n,logger:r,cdpClient:o,filterByViewport:a,showZeroOpacityElements:i,importantProperties:s,viewportDetails:c,useMPaths:l,frameContext:d,iconKnowledgeBase:u}){let m=n??"root",p=t[m]?.root;if(!p)throw new Error("A11y tree has no root");let g=MP(),h=R=>{let C=R.allNodes.filter(I=>!I.ignoredReasons?.find(k=>Ry.includes(k.name))),x=new Map;return C.forEach(I=>{x.set(parseInt(I.nodeId),I)}),x},f={};Object.entries(t).forEach(([R,C])=>{f[R]=h(C)});let b=await Ay({node:p,domGraph:e,parent:null,inputNodeMap:f,axGraph:t,frameId:m,frameContext:d,cdpClient:o,logger:r,callId:g,showZeroOpacityElements:i,importantProperties:s,filterByViewport:a,viewportDetails:c,useMPaths:l});if(b.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(b)}`);if(b.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let y={},E={},v={};return xy({node:b[0],a11yIdNodeMap:y,dataMomenticIdMap:E,selectorToNodeMap:v,domGraph:e,logger:r,callId:g,useMPaths:l,iconKnowledgeBase:u}),new Ru(b[0],y,E,v)}function jP(t,e,n,r){if(t==="class"){if(n.tagName?.toLowerCase()==="svg")return e.split(" ").filter(i=>i.length<vy&&!Vn.bannedClassSubstrings.some(s=>i.includes(s))).slice(0,3).join(" ");let o=e.split(" "),a=[];for(let i of o)if(Py(i,r)){a.push(i);continue}return a.length?a.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let o=parseInt(e);if(!isNaN(o))return o}catch{}return t==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function GP(t,e,n){if(!e)return;Object.entries(e.attributes).forEach(([i,s])=>{let c=t[i]||i.startsWith("aria")||NP.includes(i);if((Vn.relevantElementAttributes.includes(i)||My(i,n))&&!c){let d=jP(i,s,e,n);d!==null&&(t[i]=d)}});let r,o=[];if(e.computedStyles.position&&Ty.includes(e.computedStyles.position))r=e.computedStyles.position;else if(e.attributes.style){for(let i of Ty)if(e.attributes.style.includes(`position: ${i}`)){r=i;break}}r&&o.push(`position: ${r}`);let a;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(a="opacity: 0"),a&&o.push(a);for(let i of n?.styles??[]){let s=i.split(":"),c=s[0]?.trim(),l=s[1]?.trim(),d=e.computedStyles[c??""];if(c!==void 0&&l!==void 0&&d!==void 0&&(l==="*"||d===l)){let u=e.computedStyles[c],m=`${c}: ${u}`;o.includes(m)||o.push(m)}}o.length>0&&(t.style=o.join("; "))}function WP(t){let e=t.properties.class;if(typeof e=="string"&&e.includes("cm-content")){t.children.forEach((a,i)=>{a.properties["cm-line-number"]=`${i+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){t.children.forEach((a,i)=>{a.properties["block-number"]=`${i+1}`}),t.children.length>0&&(t.children[t.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(t.tagName==="table"){let a=[],i=t.children.find(c=>c.tagName==="thead");if(i){let c=i.children.find(l=>l.tagName==="tr");if(c){let l=c.children.filter(d=>d.tagName==="th");l.forEach((d,u)=>{d.properties["col-index"]||(d.properties["col-index"]=u+1),a?.push($e(d.name,100,!1))}),a?.length!==l.length&&(a=void 0)}}let s=0;for(let c of t.children)if(c.tagName==="tbody")for(let l=0;l<c.children.length;l++){let d=c.children[l];if(d.tagName!=="tr")continue;if(l===0&&!a?.length){let p=d.children.filter(g=>g.tagName==="th");if(p.length){if(a=p.map(g=>$e(g.name,100,!1)),a.length===p.length)continue;a=void 0}}s+=1,d.properties["row-index"]||(d.properties["row-index"]=s);let u=d.children.filter(p=>p.tagName==="td"||p.tagName==="th"),m=u.length===a?.length;u.forEach((p,g)=>{p.tagName!=="th"&&(p.properties["col-index"]||(p.properties["col-index"]=g+1),m&&(p.properties.col||(p.properties.col=a[g])))})}}}function VP(t){let e=t.properties.class,n=typeof e=="string"&&e.includes("cm-content");t.internalProperties.inCodeMirrorEditor=t.internalProperties?.inCodeMirrorEditor||n}function Py(t,e){if(e&&Ly(t,e))return!0;if(Vn.bannedClassSubstrings.some(n=>t.includes(n)))return!1;if(Vn.alwaysInterestingClassNames.includes(t))return!0;for(let n of Vn.alwaysInterestingClassPrefixes)if(t.startsWith(n))return!0;return!1}function My(t,e){if(e?.attributes?.includes(t))return!0;for(let n of e?.attributes??[])if(n.endsWith("*")){let r=n.slice(0,-1);if(t.startsWith(r))return!0}return!1}function Ly(t,e){if(e?.classes?.includes(t))return!0;for(let n of e?.classes??[])if(n.endsWith("*")){let r=n.slice(0,-1);if(t.startsWith(r))return!0}return!1}var Tl=class t{constructor(e,n,r,o,a){this.session=e;this.logger=n;this.contextGetter=r;this.pageGetter=o;this.defaultTimeoutMs=a}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:n,pageGetter:r,defaultTimeoutMs:o}){let a=n(),i=r(),s,c;for(let d=0;d<2;d++)try{s=await j(a.newCDPSession(i),{milliseconds:o*d,fallback:()=>{throw new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${i.url()})`)}});break}catch(u){await J(500),c=u}if(!s)throw c;let l=new t(s,e,n,r,o);try{await j(l.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(d){throw l.cdpFullyDead=!0,new A("UserInfrastructureError",`Failed to initialize CDP client: ${d}`)}return l}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(n){this.logger.warn({err:n},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(n)}`)}),e.on("Page.navigatedWithinDocument",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(n)}`)}),e.on("Page.lifecycleEvent",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(n)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:n,timeout:r=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await j(this.cdpInitializingPromise,{milliseconds:r});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new A("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await j(this.session.send(e,n),{milliseconds:r,message:o??`Chrome command ${e} timed out after ${r}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(a){throw["Internal error","Target crashed"].some(i=>a.message.includes(i))&&!this.cdpInitializingPromise&&(this.logger.warn({err:a},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),a}}async createRawCDPSession(e=this.defaultTimeoutMs){let n=e,r=this.pageGetter(),o=await j(this.contextGetter().newCDPSession(r),{milliseconds:n,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${r.url()})`),new A("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${r.url()})`)}});return this.logger.debug(`Created new CDP session for ${r.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let n=this.session;this.session=await this.createRawCDPSession(e),await j(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await j(n.detach(),{milliseconds:1e3})}catch(r){this.logger.warn({err:r},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(n){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${n}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,n){return this.session.on(e,n),this.session}off(e,n){return this.session.off(e,n),this.session}addListener(e,n){return this.session.addListener(e,n),this.session}removeListener(e,n){return this.session.removeListener(e,n),this.session}};var ca="<empty>";function qP(t){return t.includes("doubleclick.net")||t.includes("googletagmanager.com")||t.includes("googlesyndication.com")||t.includes("s.amazon-adsystem.com")||t.includes("smartadserver.com")||t.includes("omnitagjs.com")||t.includes("x.adroll.com")}function Ny(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||qP(t.url)}async function KP(t,e){let n=await t.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await t.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[n.backendNodeId]}})).nodeIds[0],i=(await t.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:n.backendNodeId}})).node;return i.nodeId=o,i}async function da({cdpClient:t,page:e,logger:n}){let r={type:"root",childFrames:[],page:e},o=[],[a,i]=await Promise.all([t.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),t.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),l=(a.frameTree.childFrames??[]).map(async(u,m)=>{if(Ny(u.frame))return null;try{return await ky({cdpClient:t,rawFrameTree:u,indices:[m],parent:r,warnings:o,logger:n})}catch(p){return o.push(`Failed to get child frame: ${p}`),null}}),d=await Promise.all(l);return r.childFrames=d.filter(u=>u!==null),o.length&&n?.warn({warnings:o},"Got warnings when fetching frame tree"),r}async function ky({cdpClient:t,rawFrameTree:e,indices:n,parent:r,warnings:o,logger:a}){let i=e.frame.id,s=await KP(t,i),c=s.attributes??[],l=null,d=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=br(c,g);h&&(d.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(l=h))}let u={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:i,locationData:{indices:n,attributeSelectors:d},src:l,childFrames:[],parent:r,domNode:s},p=(e.childFrames??[]).map(async(g,h)=>{if(Ny(g.frame))return null;try{return await ky({cdpClient:t,rawFrameTree:g,indices:[...n,h],parent:u,warnings:o,logger:a})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return u.childFrames=(await Promise.all(p)).filter(g=>g!==null),u}async function YP(t){try{return await t.owner().count()===1}catch{return!1}}async function XP(t){try{return await t.count()===1}catch{return!1}}async function On(t,e){let n=[],r=t;for(;r.parent.type==="frame";)n.push(r.parent),r=r.parent;n.reverse();let o=e,a=[];for(let l of n){let d=!1;for(let u of[...l.locationData.attributeSelectors,ca]){let m=o.frameLocator(u===ca?"iframe":`iframe[${u}]`);if(await YP(m)){d=!0,o=m,a.push(u);break}}if(!d)throw new A("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${l.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let i;for(let l of[...t.locationData.attributeSelectors,ca]){let d=o.locator(l===ca?"iframe":`iframe[${l}]`);if(await XP(d)){i=d,a.push(l);break}}if(!i)throw new A("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${t.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await i.evaluateHandle(l=>l,{timeout:1e3}),c=await s.asElement().contentFrame();if(!c)throw new A("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${t.url}'`);return await s.dispose(),{frame:c,mPathSelectorTokens:a}}function Oy(t,e){let n=[...t],r=[];for(;n.length;){let o=n.shift();e(o)&&r.push(o),n.push(...o.childFrames)}return r}async function _y({page:t,frameTree:e,cache:n}){let r,o=e.childFrames,a=[];if(n.mPathSelectorTokens.length){let s=o;for(let d=0;d<n.mPathSelectorTokens.length-1;d++){let u=n.mPathSelectorTokens[d];u===ca?s=s.length===1?s[0].childFrames:[]:s=s.filter(m=>m.locationData.attributeSelectors.includes(u)).map(m=>m.childFrames).flat()}let c=[],l=n.mPathSelectorTokens[n.mPathSelectorTokens.length-1];if(l===ca?c=s:c=s.filter(d=>d.locationData.attributeSelectors.includes(l)),c.length===1)return r=c[0],a.push(`Found unique frame with mpath ${n.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${c.length} frames with mpath ${n.mPathSelectorTokens.join(" > ")}`)}if(n.frameSrcRegex){let s=new RegExp(n.frameSrcRegex),c=Oy(o,l=>!!l.src&&s.test(l.src));if(c.length===1)return r=c[0],a.push(`Found unique frame with src regex ${n.frameSrcRegex}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${c.length} frames with src regex ${n.frameSrcRegex}`),n.frameSrcRegex=void 0}if(n.frameUrlRegex){let s=new RegExp(n.frameUrlRegex),c=Oy(o,l=>!!l.url&&s.test(l.url));if(c.length===1)return r=c[0],a.push(`Found unique frame with url regex ${n.frameUrlRegex}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${c.length} frames with url regex ${n.frameUrlRegex}`),n.frameUrlRegex=void 0}let i=o;for(let s=0;s<n.indices.length-1;s++)i=i[n.indices[s]]?.childFrames??[];if(r=i[n.indices[n.indices.length-1]],r)return a.push(`Found unique frame with indices ${n.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};throw a.push(`Found ${i.length} frames with indices ${n.indices}`),new En("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:a}])}function wl(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function vu(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function Dy(t){let e=vu(t),n=t.src??"",r=t.url??"",o=[],a=[],i=[...e.childFrames];for(;i.length;){let s=i.shift();s.src&&o.push(s.src),s.url&&a.push(s.url),i.push(...s.childFrames)}return{srcs:o,urls:a,desiredSrc:n,desiredUrl:r}}function Fy(t){return t.type==="auto"?{type:"auto",frameId:t.handle.frameId,url:t.handle.url,src:t.handle.src??"",mPathSelectorTokens:t.mPathSelectorTokens.join(" > ")}:{type:"url",url:t.url}}async function Uy({frame:t,logger:e,signal:n}){let r;try{r=await t.frameElement(),await JP({frameElementHandle:r,logger:e,signal:n})}catch(o){e.warn({err:o},"Failed to scroll iframe into view, continuing...")}finally{await r?.dispose()}}async function JP({frameElementHandle:t,logger:e,signal:n}){let r=await t.boundingBox();if(!r){e.warn("Active frame element has null bounding box, skipping scroll");return}await to({promiseGenerator:async()=>t.evaluate(async(a,{x:i,y:s})=>{window.scrollTo(window.scrollX+i,window.scrollY+s);let c=Date.now(),l,d,u;for(;Date.now()-c<1500;){let m=document.activeElement,p,g,h;if(!m)p=void 0,g=void 0,h=void 0;else{let f=m.getBoundingClientRect();p=m.scrollTop,g=f.x,h=f.y}if(l!==void 0&&d!==void 0&&u!==void 0&&p===l&&g===d&&h===u)break;l=p,d=g,u=h,await new Promise(f=>setTimeout(f,250))}},r),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:n}),e.info({bb:r},"Successfully scrolled iframe into view")}function By(t,e){return async(n,r)=>{try{let o=await r.allHeaders();for(let{key:a,value:i,matcher:s}of t)(!s||s.matches({url:r.url(),method:r.method()}))&&(o[a]=i);await n.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as ZP}from"crypto";function zy(t,e){for(let n of Object.values(e))if(n.matcher.matches({url:t.url(),method:t.method()}))return n}async function Hy(t){let{route:e,mock:n,entry:r,debugData:o,requestId:a,requestRecorders:i,logger:s}=t,c={url:r.request.url,options:{method:r.request.method,headers:r.request.headers.map(p=>[p.name,p.value]),body:r.request.postData?.text}},l;if(n.fetchOriginalResponse){let p=await e.fetch();l={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let d=await QP(n,c,l),u={};d.headers.forEach((p,g)=>{u[g]=p});let m={body:await d.text(),contentType:d.headers.get("content-type")||"text/plain",headers:u,status:d.status};await e.fulfill(m);try{r.response={status:m.status,statusText:d.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body},_mocked:!0},yi(o,r,a);for(let p of Object.values(i))p.onRequestComplete(a,r)}catch(p){p.message.includes("has been closed")||s.warn({err:p},"Failed to add response to HAR")}}async function QP(t,e,n){try{return await t.generateResponse(e,n)}catch(r){let o=r instanceof Error?r.message:`${r}`;return new Response(o,{status:500,headers:{"Content-Type":"text/plain"}})}}async function Au(t){try{await eM(t)}catch(e){t.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function eM(t){let{pageId:e,route:n,request:r,debugData:o,logger:a,requestRecorders:i,mocks:s}=t,c=ZP(),l=await gu(e,r);try{yi(o,l,c);for(let u of Object.values(i))u.onRequestStart(c,l)}catch(u){a.warn({err:u},"Failed to add request to HAR")}let d=zy(r,s);d?await Hy({logger:a,route:n,mock:d,entry:l,debugData:o,requestId:c,requestRecorders:i}):await tM({route:n,request:r,debugData:o,logger:a,requestRecorders:i,entry:l,requestId:c})}async function tM({route:t,request:e,debugData:n,logger:r,requestRecorders:o,entry:a,requestId:i}){await t.continue();try{let s=await e.response();if(!s||!a)return;await ZS(a,e,s),yi(n,a,i);for(let c of Object.values(o))c.onRequestComplete(i,a)}catch(s){s.message.includes("has been closed")||r.warn({err:s},"Failed to add response to HAR")}}async function nM(t){let e=t.postData();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:t.postDataJSON()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function rM(t){let e=await t.text();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:await t.json()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function El(t){return{request:{url:t.request.url,method:t.request.method,headers:t.request.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.request.postData?t.request.postData.mimeType.includes("json")?{json:JSON.parse(t.request.postData.text)}:{text:t.request.postData.text}:{}},response:t.response?{status:t.response.status,headers:t.response.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.response.content?t.response.content.mimeType?.includes("json")&&t.response.content.text?{json:JSON.parse(t.response.content.text)}:{text:t.response.content.text}:{}}:void 0}}async function xu(t){let e=t.request(),n=t.status(),r=t.headers(),o=await rM(t);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await nM(e)},response:{status:n,headers:r,...o},status:n,headers:r,...o}}var Tr=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:n,method:r}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==r.toLowerCase()?!1:Js(n,this.requestMatcher.urlMatcher)}};async function $y({event:t,transformer:e,enricher:n,frame:r,lastScreenshotForRecording:o,logger:a}){let{warnings:i,error:s,properties:c}=t.target;if(s){a.error({error:s,warnings:i},"Error while capturing passive click");return}if(i.length&&a.warn({warnings:i},"Warnings while capturing passive click"),!c)return;let l=r.parentFrame()?r.url():void 0,u=r.page().frames().map(g=>g.url());a.debug({frameUrl:l,...t},"Passive click event captured on element");let m,p;if(l)try{let g=await r.frameElement();m=await j(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await n.constructIframeRegex({urls:u,srcs:[],desiredUrl:l});if(h.urlRegex)p={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){a.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),p={type:"url",url:l}}(async()=>{try{await e.recordElementAction({...t,screenshotBase64:o,frameConfig:p,frameBoundingBox:m})}catch(g){a.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as Nn}from"crypto";import oM from"js-beautify";var aM=["Dead"],Rl=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:n,generator:r,testId:o,orgId:a,logger:i}){this.signal=e,this.logger=i,this.testId=o,this.orgId=a,this.callbacks={onStepRecorded:(s,c)=>{this.recordedSteps.set(c,{step:s}),n.onStepRecorded(s,c)},onActionReceived:(s,c)=>{this.recordedSteps.set(c,{step:s}),n.onActionReceived?.(s,c)}},this.generator=r}reserveIndexForCommand(e){let n=this.nextStepOffset;return this.recordedSteps.set(n,{step:{id:Nn(),type:"PRESET_ACTION",command:Fn(e)}}),this.nextStepOffset++,n}async recordElementAction(e){let{type:n,target:r,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let a,i,s=r.properties.attributes.nodeOnlySerializedHtml.trim(),c=s,l;switch(e.frameConfig?e.frameBoundingBox?l={x:e.frameBoundingBox.x+r.properties.boundingBox.x,y:e.frameBoundingBox.y+r.properties.boundingBox.y,width:r.properties.boundingBox.width,height:r.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):l=r.properties.boundingBox,n){case"CLICK":{a="CLICK";let h=Fn(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}}}};break}case"SELECT":{a="SELECT_OPTION";let h=Fn(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:c},cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:l}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{a="MOUSE_DRAG";let h=Fn(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:Le(this.logger),boundingBox:l}}}};break}default:throw new Error(`Unknown action type: ${n}`)}let d;e.offset===void 0?(d=this.nextStepOffset,this.nextStepOffset++):d=e.offset,this.callbacks.onActionReceived?.(i,d);let u=e.target.browserState;try{u=oM.html(u,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),u=HS(u,"data-momentic-interacted",4e4)}catch{}let m;try{m=(await this.generator.getReverseMappedDescription({target:u,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:r.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...Le(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=s}let p=this.recordedSteps.get(d)?.step??i,g=p?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...p,command:g},d)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:n,combinable:r}=e;if(aM.includes(n)||this.signal.aborted)return;let o="normal";n.length>1&&(o="special");let a;if(o==="normal"){let u=Fn("TYPE");a={id:Nn(),type:"PRESET_ACTION",command:{...u,target:void 0,value:n,clearContent:!1}}}else{let u=Fn("PRESS");a={id:Nn(),type:"PRESET_ACTION",command:{...u,value:n}}}let i,s=this.nextStepOffset-1,c=this.recordedSteps.get(s),l=c?.step,d=l?.command;if(r){if(d?.type===a.command.type){let u=d.value,m=a.command.value;a={id:Nn(),type:"PRESET_ACTION",command:{...d,value:a.command.type==="PRESS"?`${u}+${m}`:`${u}${m}`}},i=s}else if(d?.type==="CLICK"&&a.command.type==="TYPE")l.command={...a.command,target:d.target,cache:d.cache},a=c.step,i=s;else if(d?.type==="TYPE"&&a.command.type==="PRESS"&&a.command.value==="Backspace"){let u=d.value;a={id:Nn(),type:"PRESET_ACTION",command:{...d,value:u.slice(0,u.length-1)}},i=s}}i===void 0&&(i=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(a,i)}recordScroll(e){if(this.signal.aborted)return;let n=()=>{let{deltaY:a}=e;if(!a)return;let i=this.nextStepOffset-1,s=this.recordedSteps.get(i)?.step.command,c;s?.type==="SCROLL_DOWN"&&s.deltaY?(a+=s.deltaY,c=i):s?.type==="SCROLL_UP"&&s.deltaY?(a-=s.deltaY,c=i):(c=this.nextStepOffset,this.nextStepOffset++);let l=a>0?"SCROLL_DOWN":"SCROLL_UP",d=Fn(l);d.deltaY=Math.abs(a);let u={id:Nn(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,c)},r=()=>{let{deltaX:a}=e;if(!a)return;let i=this.nextStepOffset-1,s=this.recordedSteps.get(i)?.step.command,c;s?.type==="SCROLL_RIGHT"&&s.deltaX?(a+=s.deltaX,c=i):s?.type==="SCROLL_LEFT"&&s.deltaX?(a-=s.deltaX,c=i):(c=this.nextStepOffset,this.nextStepOffset++);let l=a>0?"SCROLL_RIGHT":"SCROLL_LEFT",d=Fn(l);d.deltaX=Math.abs(a);let u={id:Nn(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,c)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(r(),e.deltaY>=20&&n()):(n(),e.deltaX>=20&&r())}};import{z as Iu}from"zod";var pre=Iu.object({type:Iu.literal("url"),url:Iu.string()});var Cl=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;computedStylesToFetch=["display","opacity","visibility","height","position"];activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:n,allowPartialAccessibilityTree:r,logger:o,cdpClient:a,pageGetter:i,abortSignalGetter:s,enricher:c,iconKnowledgeBase:l,userBrowserSettings:d}){if(this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=n,this.allowPartialAccessibilityTree=r,this.logger=o,this.cdpClient=a,this.pageGetter=i,this.abortSignalGetter=s,this.enricher=c,this.iconKnowledgeBase=l,this.userBrowserSettings=d,this.userBrowserSettings.importantStyles)for(let u of this.userBrowserSettings.importantStyles){let m=u.split(":");if(m.length!==2){this.logger.warn({style:u},"Invalid style property passed to importantStyles");continue}let p=m[0]?.trim(),g=m[1]?.trim();if(p===void 0||g===void 0){this.logger.warn({style:u},"Invalid style property passed to importantStyles");continue}this.computedStylesToFetch.includes(p)||this.computedStylesToFetch.push(p)}}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let n={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,n),n}async getAutoFrameDetailsFromHandle(e){let n=this.pageGetter(),r=vu(e),{frame:o,mPathSelectorTokens:a}=await On(e,n),i={indices:e.locationData.indices,mPathSelectorTokens:a};return this.constructIframeRegexAsync(e,i),{cache:i,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:a,frameTree:r,cache:i}}}async resolveAutoFrameCache(e){let n=this.pageGetter(),r=await da({cdpClient:this.cdpClient,page:n,logger:this.logger}),{resolution:o,logs:a}=await _y({page:n,frameTree:r,cache:e});return this.logger.info({logs:a},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:n=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(wl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let r;return this.frameConfig.type==="url"?r=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:n}):r={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:wl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Uy({frame:r.frame,logger:e,signal:n}),this.activeFrameCache=r,r}async executeFunctionInAllFrames(e,n){let r=this.pageGetter(),o=await da({cdpClient:this.cdpClient,page:r,logger:this.logger}),a=[j(r.evaluate(e,n),{milliseconds:2e3})],i=Array.from(o.childFrames);for(;i.length>0;){let c=i.shift(),l=c.url;l==="about:blank"||l.startsWith("chrome-error://")||(i.push(...c.childFrames),a.push(On(c,r).then(({frame:d})=>j(d.evaluate(e,n),{milliseconds:2e3})).catch(d=>(this.logger.warn({err:d,frameUrl:c.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(a)).filter(c=>c!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),n=await da({cdpClient:this.cdpClient,page:e,logger:this.logger}),r=Array.from(n.childFrames),o=[];for(;r.length>0;){let a=r.shift();r.push(...a.childFrames),o.push(a.src??a.url)}return o}async getDomGraph({devicePixelRatio:e,signal:n,logger:r}){return this.getDOMTree({devicePixelRatio:e??1,signal:n,logger:r??this.logger})}async getA11yTree(e){let n={},r=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),a=this.pageGetter(),i,s,c=null;if(this.frameConfig?.type==="url"){if(i=await an({fn:()=>this.resolveActiveFrameConfig({logger:r,signal:o}),codePath:"getActiveFrameDetails",logObject:n,signal:o,logger:r})??void 0,!i)throw new A("ActionFailureError","Got null frame details despite active frame config");s=i.handle,c=s.frameId}else this.userBrowserSettings.autoExpandIframes?(s=await an({fn:()=>da({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),codePath:"getMomenticFrameTree",logObject:n,signal:o,logger:r}),c=null):(s={type:"root",page:a,childFrames:[]},c=null);await an({fn:async()=>this.addMomenticIds({rootPage:a,childFrames:s.childFrames,frameFilter:i?.frame,logger:r}),codePath:"addIdsToElement",logObject:n,signal:o,logger:r});let l=await an({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:r}),codePath:"domFetch",logObject:n,signal:o,logger:r}),d=await an({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:c,childFrames:s.childFrames,logTimings:n,logger:r,signal:o}),codePath:"totalA11yFetch",logObject:n,signal:o,logger:r}),{tree:u}=await an({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:d,domGraph:l,startingFrameId:c,frameContext:s,logger:r,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements}),codePath:"a11yProcess",logObject:n,signal:o,logger:r});return Object.values(n).some(m=>m>750)&&r.warn({logTimings:n},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=u.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=u.dataMomenticIdMap,this.lastA11yTreeRoot=u.root,this.lastDomGraph=l,this.lastSelectorToNodeMap=u.selectorToNodeMap,u}async fetchA11yTreeForRecording(e,n){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:n,logger:Xr,filterByViewport:!1}),Math.random()<.1){let r=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:r&&r.length>4e5?"REDACTED_DUE_TO_SIZE":r},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:n,node:r}){if(r.backendNodeId===void 0)throw new Error(`Node with a11y id ${r.id} has no backend node ID: ${r.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[r.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${r.backendNodeId}`);let a=fy({node:o,domGraph:this.domGraph});return Sy(e,a)}else return this.getLocatorFromBackendId(n,r.backendNodeId)}async getLocatorFromBackendId(e,n){let r=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:n},timeout:2e3});if(!r||!r.object.objectId)throw new Error(`Could not resolve backend node ${n}`);let o;try{o=await yy(this.cdpClient,r.object.objectId)}catch(a){throw this.logger.debug({err:a,object:JSON.stringify(r.object)},"Failed to get ID attribute"),a}return e.locator(hn(o))}getNodeUsingMPathSelector(e){let n=this.selectorToNodeMap[e];if(n)return n;let r=e.split(" > "),o="";for(let a=r.length-1;a>=0;a--){let i=r.slice(a).join(" > ");if(this.selectorToNodeMap[i]){o=i;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:n=this.abortSignalGetter(),logger:r=this.logger}){let o=Date.now(),a,i,s,c=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{a=await da({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),i=await this.getMatchingFrameByUrlWithCdp(a,e),r.info({frameId:i.handle.frameId,url:i.handle.url,src:i.handle.src,locationData:i.handle.locationData},`Found matching frame using ${i.matchType}`);break}catch(l){if(s=l,l instanceof A&&l.reason==="UserInfrastructureError")throw l;c%3===0&&this.logger.warn({attempt:c,err:l},"Failed to resolve active frame, retrying..."),await J(500,n)}finally{c++}if(i)return{source:"url",frame:i.frame,handle:i.handle,frameIdentifierStringified:wl(e),cacheTime:Date.now(),frameTree:a,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,n){let r=n.url,o=this.pageGetter(),a=Array.from(e.childFrames),i=[];for(;a.length>0;){let s=a.shift(),c=s.domNode;a.push(...s.childFrames);let l=br(c.attributes??[],"src"),d=c.contentDocument?.documentURL;if(!l&&!d){this.logger.debug("Skipping frame with no URL or src");continue}for(let u of[l,d])if(u){if(r.startsWith("/")&&r.endsWith("/")){if(new RegExp(r.slice(1,-1)).test(u)){i.push({handle:s,matchType:"regex",...await On(s,o)});break}}else if(r.trim()===u.trim()){i.push({handle:s,matchType:"url",...await On(s,o)});break}}}if(i.length===1){let s=i[0];return this.userBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw i.length>1?new Error(`Found multiple frames with src matching '${r}'. Please use a more specific selector.`):new A("ActionFailureError",`Failed to find frame with src matching: ${r}`)}async composeA11yDomGraph({opts:e,a11yGraph:n,domGraph:r,startingFrameId:o,frameContext:a,logger:i,iconKnowledgeBase:s,showZeroOpacityElements:c}){let l=await Iy({rawA11yGraph:n,startingFrameId:o,frameContext:a,domGraph:r,logger:i,cdpClient:this.cdpClient,showZeroOpacityElements:c,filterByViewport:e.filterByViewport,importantProperties:{attributes:this.userBrowserSettings.importantAttributes,classes:this.userBrowserSettings.importantClasses,styles:this.userBrowserSettings.importantStyles},viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userBrowserSettings.visualActions});if(!l||!l.root)throw new Error("Accessibility tree appears empty");return{tree:l}}async addMomenticIds({rootPage:e,childFrames:n,frameFilter:r,logger:o}){if(this.userBrowserSettings.visualActions)return;let a=await this.addMomenticIdsHelper(r??e,1);if(!this.userBrowserSettings.autoExpandIframes||r)return;let i=Array.from(n),s=[];for(;i.length>0;){let c=i.shift();i.push(...c.childFrames);let l=async()=>{try{let{frame:d}=await On(c,e);a=await this.addMomenticIdsHelper(d,a)}catch(d){c.url!=="about:blank"&&o.warn({err:d},"Error adding momentic IDs to child frame, continuing...")}};s.push(l())}await Promise.all(s)}async addMomenticIdsHelper(e,n){if(this.userBrowserSettings.visualActions)return n;let r=this.logger;return await et({root:e,fn:a=>window.addIdsToElement?.(document.body,a),arg:n,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(a){r.warn({err:a},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??n}getPageDomain(e){try{let n=new URL(e);if(!n.hostname)return null;let r=n.hostname.split("."),o=r.length>2?r.slice(-2).join("."):n.hostname;return`${n.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:n,handle:r}){try{let{shouldUnroll:o,reason:a}=await this.decideChildFrameUnrollEligibilityHelper({domNode:r.domNode});return{shouldUnroll:o,reason:a}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let a=`Got error when determining whether to filter frame ${r.frameId} with url ${r.url}, allowing it to be fetched: ${o}`;return n?.push(a),e?.warn({err:o},a),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let n=e.attributes??[];if(br(n,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let r=br(n,"style");if(r?.includes("display: none")||r?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,a]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let i of a.computedStyle){if(i.name==="display"&&i.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(i.name==="visibility"&&i.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(i.name==="opacity"&&i.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:n,childFrames:r,logTimings:o,logger:a=this.logger,signal:i=this.abortSignalGetter()}){let s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(p){a.warn({err:p},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let c,l;for(let p=0;p<3;p++)try{l=await an({fn:()=>this.getRawA11yTreeForFrame({frameId:n,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:i,logger:a});break}catch(g){c=g,a.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!l)throw new Error(`Failed to fetch accessibility tree for root page: ${c}`);let d={};if(d[n??"root"]=l,!this.userBrowserSettings.autoExpandIframes)return d;let u=Array.from(r),m=[];for(;u.length>0;){let p=u.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:p,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${p.frameId} with url ${p.url}, allowing it to be fetched: ${h}`)}u.push(...p.childFrames);let g=async()=>{try{let h=await an({fn:()=>this.getRawA11yTreeForFrame({frameId:p.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${p.frameId}`,logObject:o,signal:i,logger:a});d[p.frameId]=h}catch(h){a.warn({err:h,url:p.url,src:p.src},`Error getting raw a11y tree for child frame ${p.frameId}, continuing...`)}};m.push(g())}return await Promise.all(m),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),d}async getRawA11yTreeForFrame({frameId:e,timeoutMs:n,logTimings:r}){let o;if(this.allowPartialAccessibilityTree)o=(await an({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let i=(await an({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await an({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:i},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:n,logger:r}){let o,a=0,i;for(;!o&&a<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:this.computedStylesToFetch},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await J(500,n),a++,i=s}if(!o||!o.documents.length)throw r.error({err:i},"Fatal error fetching DOM tree"),new A("UserInfrastructureError",`Received an empty HTML snapshot from the browser. This usually indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code: ${i?.message}`);return hy({snapshot:o,devicePixelRatio:e,computedStylesToFetch:this.computedStylesToFetch,logger:r})}constructIframeRegexAsync(e,n){if(n.frameSrcRegex||n.frameUrlRegex)return;let r=Dy(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(r);o?.srcRegex&&(n.frameSrcRegex=o.srcRegex),o?.urlRegex&&(n.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:r},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function Pu(t){let e=[],n="";for(let r of t)r==="+"&&n?(e.push(n),n=""):n+=r;return e.push(n),e}var Ou=ua(Nu(),"momentic","chromium"),AM=ua(Nu(),"video"),xl=process.env.TWO_CAPTCHA_KEY,Yy=RM(Ky);Yy.use(CM({provider:{id:"2captcha",token:xl},visualFeedback:!0}));var kn=class t{static USER_AGENT=EM["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:n,enricher:r,browser:o,context:a,page:i,baseUrl:s,logger:c,userBrowserSettings:l,viewport:d,properties:u,clientCallbacks:m,iconKnowledgeBase:p}){if(uh(l),this.storage=e,this.flagStore=n,this.enricher=r,this.browser=o,this.context=a,this.page=i,this.baseUrl=s,this.logger=c,this.userControlledBrowserSettings=l,this.viewport=d,this.properties=u,this.clientCallbacks=m,u.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:n}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let r={[fl]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:US.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(r)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];n&&await this.page.reload();let a=s=>this.handleNewPageEvent(s);this.context.on("page",a),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",a)});let i=Promise.all(o);await Promise.all([i]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&yM()==="darwin"&&uM("system_profiler SPDisplaysDataType").toString().includes("Retina")?(S.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await Tl.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Cl({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let n=e.sessionId,r=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=r,this.clientCallbacks?.onScreencastFrame?.(r,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:n}})}catch{}})()})}))}static async init({baseUrl:e,logger:n,storage:r,flagStore:o,enricher:a,userBrowserSettings:i,contextArgs:s,recordVideo:c,iconKnowledgeBase:l,callbacks:d}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let u;switch(i.browserType){case"Google Chrome":u="chrome";break;case"Chrome for Testing":u=void 0;break;case"Chromium":u="chromium";break;default:u="chromium";break}let m={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:u},p={...s??{},geolocation:s?.geolocation||Fo,locale:s?.locale||_o,timezoneId:s?.timezoneId||Do,colorScheme:s?.colorScheme,httpCredentials:i.basicAuthorization?{username:i.basicAuthorization.username??"",password:i.basicAuthorization.password??""}:void 0,javaScriptEnabled:i.disableJavaScript?!1:void 0,ignoreHTTPSErrors:i.ignoreHttpsErrors??!1,userAgent:i.userAgent??t.USER_AGENT,viewport:s?.viewport??Nt},g=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],h=null,f,b,y={systemDevicePixelRatio:s?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(u==="chrome"||u==="chromium")&&(y.isNewHeadless=!0,m.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),i.disableGpu&&g.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let E=i.localChromeExtensionPaths?.map(R=>R.startsWith("~")?ua(Nu(),R.slice(1)):R);if(E?.length){if(u===void 0)throw new A("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let I of E){let D=ua(I,"manifest.json");if(!Al(D))throw new A("UserConfigurationError",`Chrome extension path ${D} does not exist.`)}let R=ua(Ou,`momentic-session-${Date.now()}`);if(!Al(R))try{mM(R,{recursive:!0})}catch(I){throw new A("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Ou} folder: ${I}`)}let C=[...g],x=E.map(I=>wM(I)).join(",");C.push(`--disable-extensions-except=${x}`),p?.deviceScaleFactor&&C.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&C.push(`--window-size=${p.viewport.width},${p.viewport.height}`),f=await Ky.launchPersistentContext(ua(Ou,`momentic-session-${Date.now()}`),{...m,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:C,baseURL:e}),n.debug({sharedContextOptions:p,sharedBrowserOptions:m,userBrowserSettings:i,chromeArgs:C,flags:o.getAllFlags(),properties:y,baseUrl:e},"Browser initialization context args (persistent)"),b=f.pages()[0]}else{h=await Yy.launch({...m,args:g});let R={...p,baseURL:e,recordVideo:c?{dir:AM}:void 0};f=await h.newContext(R),n.debug({contextArgs:R,sharedBrowserOptions:m,chromeArgs:g,userBrowserSettings:i,flags:o.getAllFlags(),properties:y,baseUrl:e},"Browser initialization context args (standard)"),b=await f.newPage()}let v=new t({browser:h,context:f,page:b,baseUrl:e,logger:n,storage:r,flagStore:o,enricher:a,userBrowserSettings:i,viewport:p.viewport||Nt,properties:y,clientCallbacks:d,iconKnowledgeBase:l});return await v.initialize({grantPermissions:!0,runInitScripts:!1}),v}static async fromExistingContext({context:e,storage:n,flagStore:r,enricher:o,userBrowserSettings:a,logger:i}){let s=e.pages()[0];if(!s)throw new Error("No page found in existing context");let c=s.viewportSize(),l=s?.url(),d=new t({browser:e.browser(),context:e,page:s,baseUrl:l,logger:i,storage:n,flagStore:r,enricher:o,userBrowserSettings:a,viewport:c,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0}),d}async handleAvailableTabsChangeHelper(){try{let e=await bu(this.context,{getTitles:!0}),n=this.page.url();this.clientCallbacks?.onTabsChange?.(e,n)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,n){let r=Mu(),o=`${e}-${r}`,a=Date.now(),i=!1,s=async()=>{try{await j(n(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(c){c.name!=="AbortError"&&this.logger.error({err:c,promiseKey:o,codePath:e,duration:Date.now()-a},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],i=!0}};this.pageLoadPromises[o]=s().catch(()=>{}),i&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let n=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let r=this.context.pages();for(let o=r.length-1;o>=0;o--){let a=r[o];if(!(!a||a.isClosed()||!no(a.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${a.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>n())}handleNewPageEvent(e){let n=e.url();if(this.logger.info({url:n},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let r=e.video();r&&this.videos.push(r)}try{this.handleNewPageEventHelper(e)}catch(r){this.logger.warn({err:r},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let n=Mu(),r="new-page-load-handler";e.on("close",i=>this.handlePageClosedEvent(i)),e.on("framenavigated",i=>this.handleFrameNavigationEvent(i)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",i=>{YS(e,o,this.debugData,i,this.logger)});let a=async()=>{await QS(n,this.debugData,e),await e.route("**/*",async(i,s)=>{await Au({pageId:n,route:i,request:s,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",By(this.customHeaders,this.logger)),await this.loadFrameAndRecordUrl({root:e,codePath:r}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(r,async()=>a())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let n=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),r=by({domGraph:n,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(r.forEach(s=>{this.iconKnowledgeBase[s.hash]=s}),!r.length)return;let o=Le(this.logger),a={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:SM()};for(let s of["runId","testId"])o[s]&&(a[s]=o[s]);let i={metadata:a,newSvgs:r};this.clientCallbacks.onSvgsCollected(i)}handleFrameNavigationEvent(e){let n=e.url(),r=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${n.slice(0,50)}-${r}`;if(!n||n==="about:blank"||!no(n)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let a=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(i){i.name!=="AbortError"&&this.logger.warn({err:i},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>a())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let r={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(r[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let a=window;a._MOMENTIC_ICON_KNOWLEDGE_BASE=o},r)}catch(n){this.logger.warn({err:n},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await j(fu(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,n,r){let o=Date.now(),a=0,i=0;for(;Date.now()-o<8e3;){i++,r?.throwIfAborted();try{if(await et({fn:()=>{let c=window;return!!(c.generateCssSelectors&&c.evaluateCssSelectors&&c.evaluatePrimaryCaches&&c.generateHtmlCacheAttributes&&c.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(a++,a>=3){n.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await J(500),i%2===0&&n.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),et({root:e,fn:()=>{let n=window;if(!n?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return n.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,n=[],r=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{r.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),n.push(()=>{for(let[o,a]of r)o.style.setProperty("caret-color",a.value,a.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of n)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:n=1,stabilizeBeforeScreenshot:r=!1}=e,o=this.page.url();r&&await this.stabilizePageForScreenshot();let a=Date.now();try{await this.fixViewportForNewHeadless();let i=await this.screenshotHelper({...e,retries:n});if(i.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(i.length===0)throw new Error("Got empty screenshot");return i}catch(i){if(n<=0||i.message.includes("has been closed"))throw i;return this.logger.warn({err:i,pageUrl:o},"Failed taking screenshot, retrying..."),await J(250),this.screenshot({...e,retries:n-1})}finally{Date.now()-a>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-a},"Screenshot took longer than expected"),r&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:n,saveToDiskPath:r,timeout:o,respectActiveFrame:a,clearHighlights:i=!1}){i&&await this.clearHighlights(),a&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:n,optimizeForSpeed:!0},timeout:o??2e3}),c=Buffer.from(s.data,"base64"),l=await Vy.fromBuffer(c),{width:d,height:u}=this.getViewport()??{};if(d&&u&&(l.bitmap.width!==d||l.bitmap.height!==u)&&(c=await l.resize({w:d,h:u}).getBuffer("image/jpeg")),r&&gM(r,c),this.lastScreenshotForRecording=c,!e)return c;let m=await e.boundingBox({timeout:3e3});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:p,y:g,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");if(p<0||g<0)throw new Error("Attempted to screenshot an element with negative coordinates");p=Math.floor(p),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{c=await(await Vy.fromBuffer(c)).crop({x:p,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(b){throw new Error(`Failed taking element screenshot at coordinates (${p}, ${g}) with size (${h}, ${f}): ${b}`)}return"dispose"in e&&await e?.dispose(),c}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:n=!1,loadTimeoutMs:r=this.pageLoadTimeout}){Af(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();n||(await this.waitForPageLoad(),await this.waitForDOMStability());let a=!1,i;for(let c=0;c<3;c++)try{await this.page.goto(e,{timeout:r,waitUntil:"domcontentloaded"}),a=!0;break}catch(l){if(i=l,this.abortSignal?.throwIfAborted(),this.logger.warn({err:l},`Error occurred during navigation${c===0?", retrying...":" (fatal)"}`),await J(500),i.message.includes("Timeout")&&i.message.includes("exceeded")||i.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!a)throw new A("UserInfrastructureError",i?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if($S.has(s))throw new A("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(n)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,n={},r=!1){await this.directTypeHelper(e,n,r)}async getActiveElement(e){try{return await et({root:e,fn:()=>{let r=document.activeElement?.textContent??void 0;return r&&r.length>100&&(r=r.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:r}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(n){this.logger.warn({err:n},"Failed to get active element");return}}async directTypeHelper(e,n={},r=!1){let o=await this.getActivePageOrFrame();await iy({root:o,text:e,options:n,logger:this.logger,callbacks:this.getBrowserCallbacks()});let a=await this.getActiveElement(o);if(r){let i=Date.now();for(;Date.now()-i<this.smartWaitingTimeout&&(!a||a.tag==="body");)await J(250),this.abortSignal?.throwIfAborted(),a=await this.getActiveElement(o);a||this.logger.warn("No active element found to type into, attempting anyways")}n.clearContent&&(n.forceClearContent||a?.tag==="input"||a?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:a},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:n.delay??xm}),n.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async r=>{let o=r.scrollTop;r.scrollIntoView(),await new Promise(i=>setTimeout(i,250));let a=Date.now();for(;Date.now()-a<1e3;){let i=r.scrollTop;if(i===o)break;o=i,await new Promise(s=>setTimeout(s,250))}},void 0,{timeout:2e3})}catch(r){this.logger.warn({err:r},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:n}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(n.locator),!0}catch(n){return this.logger.debug({err:n,id:e},"Failed to highlight target"),!1}}async highlight(e){return Sl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let n=new URL(e).origin;if(n==="null")return;this.originsVisited.add(n)}catch(n){this.logger.warn({err:n},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises),o=-1,a=0;for(;n.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Still waiting on page load promises"),Date.now()-o<20&&(a++,a>2)){this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(n),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let n=this.context.pages().indexOf(this.page),r=[...this.context.pages()];for(let o=0;o<r.length;o++){let a=r[o];if(a.isClosed())continue;let i=a.url();try{this.originsVisited.delete(new URL(i).origin)}catch{}await KS(a,this.logger),o!==n&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${i}`),await a.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let n=[];for(let a of e.cookies??[]){let i=await this.setCookie(a);n=n.concat(i)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let r=0;for(let a of e.origins??[])for(let i of a.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(a.origin).origin,isLocalStorage:!0},key:i.name,value:i.value}}),r++}catch(s){this.logger.warn({err:s,origin:a},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${r} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await qS(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let n=0,r=null;for(;n<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await VS(this.page,this.logger),o}catch(o){if(r=o,n++,n<=2){this.logger.warn({err:o,retryCount:n,maxRetries:2},`Error saving auth state, retrying (${n}/2)...`);let a=Math.pow(2,n)*100;await new Promise(i=>setTimeout(i,a))}}throw this.logger.error({err:r},"Failed to save auth state after 2 retries"),new A("ActionFailureError",`Failed to save auth state: ${r?.message}`)}async getOpenPages(e){return bu(this.context,e)}saveA11yDetailsToCache(e,n){n.content=e.content,n.name=e.name,n.role=e.role,n.numChildren=e.children.length,delete n.serializedForm,delete n.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:n,locator:r,forceSaveNewCssSelectors:o,startingBoundingBox:a,allowZeroOpacityOverride:i,logger:s=this.logger}){if(e&&this.saveA11yDetailsToCache(e,n),n.frameCache=this.stateManager.saveAutoFrameCacheDetails(n.frameCache),r)try{let c=await this.fetchHtmlAttributes({locator:r,logger:s,startingBoundingBox:a,allowZeroOpacityOverride:i}),l=!1;for(let d of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let u=c?.[d];if(u&&!n[d]){l=!0;break}if(u&&JSON.stringify(u)!==JSON.stringify(n[d])){l=!0;break}}c&&(o||l)&&(n.generatedSelectors=c.generatedSelectors,n.serializedHtml=c.serializedHtml,n.nodeOnlySerializedHtml=c.nodeOnlySerializedHtml,n.hybridSelector=c.hybridSelector)}catch(c){if(c instanceof Rn)throw c;s.warn({err:c},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:n,locator:r,logger:s,boundingBox:a})}catch(c){s.debug({err:c},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:n,logger:r,boundingBox:o}){if(!n)return{scrollPerformed:!1};if(!ou.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(n),o||(o=await n.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return r.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:a=0,y:i=0,width:s=0,height:c=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-c)<1&&Math.abs((e.boundingBox.x??0)-a)<1&&Math.abs((e.boundingBox.y??0)-i)<1)return{scrollPerformed:!0};e.boundingBox=o;let l=await this.screenshot({locator:n,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(l),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async createTargetFromA11yId({id:e,description:n,targetSource:r,skipSaveToCache:o,logger:a=this.logger}){if(e<0)throw new A("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let i=this.stateManager.a11yIdToNodeMap[e];if(!i)throw new A("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,c,l,d,u;if(this.userBrowserSettings.autoExpandIframes&&!s&&i.parentFrame){let f=i.parentFrame,{cache:b,config:y}=await this.stateManager.getAutoFrameDetailsFromHandle(f);l=b,d=y,c=y.frame,u="auto iframe"}else i.parentFrame&&s?(d=s,c=await this.getActivePageOrFrame(),u="hardcoded url already on the state manager"):(c=await this.getActivePageOrFrame(),u="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:c,node:i}),p={id:e,inputDescription:n??void 0,targetSource:r,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Le(a),frameCache:l},g,h=!1;o||(d&&(a.info({frameConfigSource:u,frameConfig:Fy(d)},"A11y node was resolved to a target within an iframe"),g=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(d),h=!0),await this.updateCacheWithNewNodeDetails({node:i,target:p,locator:m,logger:a,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:!0}));try{return{resolution:{locator:m,a11yNode:i,displayString:i.getNodeOnlySerializedForm(),decisions:[]},target:p,frameConfig:d,frameConfigSource:u}}finally{h&&this.stateManager.setActiveFrameConfig(g)}}async resolveTarget(e,n,r={}){let{targetName:o,logger:a=this.logger,signal:i=this.abortSignal,allowZeroOpacityOverride:s}=r;if(n.frameCache&&this.userBrowserSettings.autoExpandIframes){let p,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(n.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){p=f,await J(500,i)}if(!g)throw p}let c=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(c,a,i);let l=Date.now(),d=0,u=0,m;for(;Date.now()-l<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),d++;let p=d===2||Date.now()-l>this.smartWaitingTimeout-2e3&&d%2===0;try{m=await this.resolveTargetHelper({root:c,target:n,primaryOnly:!0,logger:p?a:Xr,allowZeroOpacityOverride:s,signal:i});break}catch(g){if(g instanceof Ga)break;if(g instanceof Rn){if(u++,u>2)throw a.error({err:g},"Got multiple cache disqualification errors, giving up"),g;a.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await J(500,i)}i?.throwIfAborted(),p&&a.info({err:g},`Could not resolve target using primary cache only (x${d})`),await J(500,i)}}return m||(m=await this.resolveTargetHelper({root:c,target:n,primaryOnly:!1,logger:a,signal:i,allowZeroOpacityOverride:s}),n.targetSource="HEURISTIC_HEALED",n.targetUpdateTime=new Date().toISOString(),n.targetUpdateLoggerTags=Le(a),a.info({decisions:m.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:m?.decisions??[],pageState:void 0,targetSource:n.targetSource,targetUpdateTime:n.targetUpdateTime}),m}async resolveTargetHelper({root:e,target:n,primaryOnly:r,logger:o,signal:a,allowZeroOpacityOverride:i}){let s=[],c=(await this.getBrowserState({logger:o,abortSignal:a,skipWait:!0,allowZeroOpacityOverride:i})).serialize(),l;if(n.generatedSelectors||n.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:n,logger:o,allowZeroOpacityOverride:i})}catch(u){l=u,u instanceof En&&s.push(...u.decisions)}if(d)return{...d,pageState:void 0,decisions:[...s,...d.decisions]};r||(s.push({type:"CSS_SELECTOR",matched:!1,reason:l?.message,selectors:bi(n.generatedSelectors??[])}),n.generatedSelectors=void 0,n.hybridSelector=void 0)}if(r)throw l;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:c,target:n,decisions:s,logger:o,signal:a,allowZeroOpacityOverride:i});if(d)return d}throw new En(`Could not find any relevant node given target: ${JSON.stringify(n)}`,s)}async resolveTargetWithPrimaryMethods({root:e,target:n,logger:r,allowZeroOpacityOverride:o}){if(!n.nodeOnlySerializedHtml)throw new Ga("Insufficient data to resolve target using primary methods (missing node HTML)");let a=this.userControlledBrowserSettings.hybridSelectorMode,i={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?n.boundingBox:void 0},{css:s,hybrid:c}=await et({fn:y=>window.evaluatePrimaryCaches(y),arg:{cssParams:{selectors:n.generatedSelectors??[],cachedElementSerialized:n.nodeOnlySerializedHtml,opts:i},hybridParams:a&&n.hybridSelector?{nodes:n.hybridSelector,cachedElementSerialized:n.nodeOnlySerializedHtml,opts:i}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),l,d,u=[];if(a==="prefer"&&c?.result){l=c.result;let y={type:"HYBRID_SELECTOR",matched:!0,logs:c.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};u.push(y),d="HYBRID_SELECTOR"}else if(s?.result){l=s.result;let y=`${l.workingSelectors.length} CSS selectors matched the following element: ${l.serializedElement}`,E=l.workingSelectors.slice(0,5);u.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:y,selectors:E}),r.debug({reason:y,workingSelectors:E},"Resolved with CSS selectors"),d="CSS_SELECTOR"}else throw u.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.logs}),c&&u.push({type:"HYBRID_SELECTOR",matched:!1,reason:c.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:c.logs}),new En("Cache evaluation failed",u);let m,p,g,h=!1;if(this.userBrowserSettings.visualActions){let y=l.mPath;if(!y)throw new Error("Found element did not have an mPath despite using visual actions");let E=y.join(" > ");m=e.locator(E),p=this.stateManager.getNodeUsingMPathSelector(E)}else if(l.dataMomenticId!==void 0)g=parseInt(l.dataMomenticId),p=this.stateManager.dataMomenticIdToNodeMap[g],"workingSelectors"in l?(m=e.locator(l.workingSelectors[0]),h=l.workingSelectors.length<5):m=e.locator(hn(g));else throw new A("InternalWebAgentError","Received an element resolution result with no identifying attributes");a&&n.hybridSelector&&(c?.logs.length===1?r.warn({hybridResult:c,cssResult:s,hybridMode:a},"Hybrid selector resolution rejected, continuing..."):c?.result?s?.result&&c?.result&&c.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(c.result.mPath)?r.warn({originalCache:n,hybridResult:c,cssResult:s,hybridMode:a,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==c.result.dataMomenticId&&r.warn({originalCache:n,hybridResult:c,cssResult:s,hybridMode:a,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):r.warn({originalCache:n,hybridResult:c,cssResult:s,hybridMode:a},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let f=bi(n);await this.updateCacheWithNewNodeDetails({node:p,target:n,locator:m,logger:r,startingBoundingBox:l.boundingBox,forceSaveNewCssSelectors:h,allowZeroOpacityOverride:o});let b=Lu(f,n);return b&&Object.keys(b).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Le(r),n.cacheResolutionUpdateSource=d,r.debug({diffs:b},"Updated cache")),{a11yNode:p,displayString:l.serializedElement,locator:m,decisions:u}}async resolveHardcodedCssSelector(e){let{ctx:n,selector:r,logger:o=this.logger,signal:a=this.abortSignal,timeoutMs:i=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),c=Date.now(),l=0,d,u=[];for(;Date.now()-c<i;){a?.throwIfAborted(),l++;let m=s.locator(r),p;try{return await m.waitFor({state:"attached",timeout:1e3}),p=await Kn(m,o)??"",u.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${r} matched an element on the page.`}),n?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:u,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:m,displayString:p,decisions:u}}catch(g){let h=g.message;d=new A("ActionFailureError",`CSS selector '${r}' failed to resolve after ${l} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await J(500,a)}}throw d}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:n,y:r,width:o,height:a}=e.target.boundingBox,i=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!i)return;let s=await i.locator.boundingBox({timeout:3e3});if(!s){this.logger.debug({proposedNode:i.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:c,y:l,width:d,height:u}=s;if(Math.abs(d-o)>10||Math.abs(u-a)>10){this.logger.debug({newW:d,oldW:o,newH:u,oldH:a,proposedNode:i.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!n||!r||!c||!l){this.logger.debug({oldX:n,oldY:r,newX:c,newY:l,proposedNode:i.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(c-n)>100||Math.abs(l-r)>100){this.logger.debug({newX:c,newY:l,oldX:n,oldY:r,proposedNode:i.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return i}async resolveTargetWithSecondaryMethodsHelper({root:e,target:n,decisions:r,logger:o,signal:a,allowZeroOpacityOverride:i}){if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.trim().length<10){let l="Refusing to attempt HTML comparison since the saved element is too short.";r.push({type:"HTML_DISTANCE",matched:!1,reason:l})}else if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.length>50)try{let l=await et({fn:u=>window.findClosestElementByLDist?.(u),arg:{nodeOnlySerializedHtml:n.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),d=Math.floor(.05*n.nodeOnlySerializedHtml.length);if(l&&l.closestDistance&&l.closestDistance>=d){let u=`Closest HTML candidate still has too far distance (${l.closestDistance}) from threshold (${d})`;r.push({type:"HTML_DISTANCE",matched:!1,reason:u,distance:l.closestDistance,closestElement:l.closestNodeSerialized})}else{if(l?.error)throw new Error(l.error);if(l?.dataMomenticId||l?.mPathSelector){let u=l.dataMomenticId?parseInt(l.dataMomenticId):void 0,m,p;if(u)m=this.stateManager.dataMomenticIdToNodeMap[u],p=e.locator(hn(u));else if(l.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(l.mPathSelector),p=e.locator(l.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=l.closestNodeSerialized??await Kn(p,o)??"unknown element";o.warn({result:l,originalTarget:n,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=bi(n);await this.updateCacheWithNewNodeDetails({node:m,target:n,locator:p,logger:o,startingBoundingBox:l.boundingBox,allowZeroOpacityOverride:i,forceSaveNewCssSelectors:!0});let f=Lu(h,n);return f&&Object.keys(f).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Le(o),n.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:l},"Updated cache after l-dist resolution")),r.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${d} string comparison distance of the saved element.`,logs:l.logs,distance:l.closestDistance,closestElement:g,savedElement:n.nodeOnlySerializedHtml}),{locator:p,a11yNode:m,displayString:g,decisions:r,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(l)}`)}}catch(l){o.info({err:l},"Failed to find closest HTML node using levenshtein distance"),r.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${l}`})}let s=n.screenshotUrl,c=n.role??"";if(s&&ou.includes(c))try{let l=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:n,screenshotUrl:s,signal:a,allowZeroOpacityOverride:i});return{...l,decisions:[...r,...l.decisions],pageState:void 0}}catch(l){a?.throwIfAborted(),r.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${l}`,elementImageUrl:s}),o.warn({err:l},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:n,oldTarget:r,signal:o,allowZeroOpacityOverride:a}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let s=await this.screenshot({retries:0}),l=await(await fetch(n)).arrayBuffer(),d=vM(),u=await this.enricher.runTemplateMatching({id:d,searchImageBase64String:Buffer.from(l).toString("base64"),pageImageBase64String:s.toString("base64")},{signal:o}),{target:m,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowZeroOpacityOverride:a}),g=m.boundingBox?.width,h=m.boundingBox?.height;if(!g||!h)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let f=m.id,b=this.stateManager.a11yIdToNodeMap[f],y=bi(r);await this.updateCacheWithNewNodeDetails({target:r,node:b,locator:p,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:a});let E=Lu(y,r);return E&&Object.keys(E).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=Le(this.logger),r.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:d,diffs:E,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:b,displayString:m.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:n}]}}async typeIntoTarget(e,n,r={}){await this.highlight(n.locator);let o=await n.locator.getAttribute("type",{timeout:1e3})??"",a=ay.some(i=>i===o.toLowerCase());return await Su({targetingResult:n,options:{force:r.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:a?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,r)}async click(e,n,r={}){return Su({targetingResult:e,options:r,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:n,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:n},r){let o=r?.timeout??this.pageLoadTimeout,a=Date.now(),i=!1,s=e;for(;Date.now()-a<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Js(s,n,r)){i=!0;break}await J(500,this.abortSignal)}if(!i)throw new A("ActionFailureError",`The active page URL ${r?.negated?"still does":"does not"} ${js(n)} in ${o}ms.
3900
+ Current tab: ${s}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(c){this.logger.warn({err:c},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,n,r={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await n.boundingBox({timeout:3e3});if(!o)throw new A("ActionFailureError","Could not get bounding box of target element");let a=o.x+o.width/2,i=o.y+o.height/2,s=r.steps??5;await this.page.mouse.move(a,i,{steps:s}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,n,r,o){o&&await this.hover({locator:o});let a=await(await this.getActivePageOrFrame()).evaluate(hu);a||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),a={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+a.left,n+a.top,{steps:r}),await J(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await uo({func:async n=>{await this.scrollIntoViewIfNeeded(n.locator);let r=await n.locator.boundingBox({timeout:3e3});if(!r)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(r.x+r.width/2,r.y+r.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await uo({func:n=>n.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let n=await this.getActivePageOrFrame();await et({fn:()=>{let r=document.activeElement;r&&r.nodeType===1&&r.blur()},root:n,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await uo({func:n=>n.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,n,r=!1){await this.highlight(e.locator),await uo({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(n.type==="INDEX"){let a=Number(n.index);if(isNaN(a))throw new A("UserConfigurationError",`Page index ${n.index} is not a number`)}await o.locator.selectOption({value:n.type==="VALUE"?n.value:void 0,label:n.type==="LABEL"?n.label:void 0,index:n.type==="INDEX"?Number(n.index):void 0},{force:r,timeout:3e3})},targetingResult:e})}async press(e,n){let r=n.repeat??1;if(n.convertMeta){let o=yl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<r;o++)await this.page.keyboard.press(e,{delay:n.delayMs??0})}async keyDown(e,n){if(n.convertMeta){let r=yl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of Pu(e))await this.page.keyboard.down(r)}async keyUp(e,n){if(n.convertMeta){let r=yl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of Pu(e))await this.page.keyboard.up(r)}async refresh(e){let n=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let r=0,o=2;for(;r<o;){r++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:n});break}catch(a){this.logger.warn({err:a,attempt:r},`Failed to reload page${r<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:n=2,logger:r=this.logger,skipWaitForPageLoad:o,allowZeroOpacityOverride:a}=e,i=e.abortSignal??this.abortSignal,s=a?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:r,signal:i});let c=0,l;for(;c<n;){c++;try{return await j(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:i,logger:r,filterByViewport:e.filterByViewport,showZeroOpacityElements:s}),{milliseconds:this.pageLoadTimeout*c,signal:i,message:"Getting browser state took too long"})}catch(d){if(i?.throwIfAborted(),l=d instanceof Error?d.message:`${d}`,c>=n)throw d;r.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new A("ActionFailureError",`Getting page content failed after ${n} attempts. Error: ${l}`)}async getViewportOffsetDetails(e){let[n,r,o,a,i]=await et({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:n,lowerBound:n+a,leftBound:r,rightBound:r+o,width:o,height:a,devicePixelRatio:this.properties.systemDevicePixelRatio??i}}async waitForDOMStability(e){let{logger:n=this.logger,timeout:r=this.smartWaitingTimeout,signal:o}=e??{},a={value:Date.now()},i=m=>{a.value=Date.now()},s=()=>i("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let c=()=>i("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>c);let l=()=>i("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",l);let d=()=>i("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",d);let u=()=>i("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",u);try{await this.waitForDOMStabilityHelper(a,n,r,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",c),this.cdpClient.removeListener("Page.frameStartedLoading",l),this.cdpClient.removeListener("Page.navigatedWithinDocument",d),this.cdpClient.removeListener("Page.frameRequestedNavigation",u)}}async waitForDOMStabilityHelper(e,n,r,o){let a=!1,i=Date.now(),s,c={quality:25,retries:0,stabilizeBeforeScreenshot:!0},l=!1,d=0;for(;Date.now()-i<r;){if(o?.throwIfAborted(),await J(500,this.abortSignal),s)try{let m=await this.screenshot(c);if(!m.equals(s)){s=m,l=!1;continue}l=!0}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(c)}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){a=!0;break}}let u={duration:Date.now()-i,a11yStableReceived:a,lastTreeUpdateMillisecondsAgo:Date.now()-e.value,screenshotStable:l};a||n.warn(u,"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,n){let{x:r,y:o}=e;this.logger.debug({x:r,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(r,o,{button:n.rightClick?"right":"left",clickCount:n.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,n,r){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(n.x,n.y,{steps:3}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,n,r,o){await this.hoverUsingVisualCoordinates(o);let a=await(await this.getActivePageOrFrame()).evaluate(hu);a||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),a={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+a.left,n+a.top,{steps:r}),await J(250),await this.page.mouse.up()}async getElementLocation(e){let n=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),r=await j(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&r===1&&(r=2);let o=n.documents[0],a=o.layout,i=o.nodes,s=i.nodeName||[],c=i.backendNodeId||[],l=a.nodeIndex,d=a.bounds,u=-1;for(let y=0;y<s.length;y++)if(c[y]===e){u=l.indexOf(y);break}if(u===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,p=0,g=0,h=0]=d[u];m/=r,p/=r,g/=r,h/=r;let f=m+g/2,b=p+h/2;return{centerX:f,centerY:b}}async scrollVertical(e){return yu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return yu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async createRawCDPSession(e){let n=await j(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),n}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,n){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(n??this.pageLoadTimeout)}async createNewTab(e,n){let r=await this.context.newPage();await this.changeActivePage(r,n?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...n}),this.handleAvailableTabsChange()}async switchToPage(e,n){let r=!0,o,a=Date.now();for(;r||n?.retry&&Date.now()-a<this.smartWaitingTimeout;){r=!1;try{await this.switchToPageHelper(e,n);return}catch(i){this.logger.warn({err:i},"Error switching to page, retrying..."),o=i,await J(500)}}throw o}async switchToPageHelper(e,n){let r=this.context.pages().map((a,i)=>({page:a,url:a.url(),index:i})),o;if(e.type==="INDEX"){let a=Number(e.index);if(isNaN(a))throw new A("UserConfigurationError",`Page index ${e.index} is not a number`);if(a<0||a>=r.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(r.map(i=>i.url))}`);o=r[a]}else{let a=r.filter(i=>e.type==="SUBSTRING"?i.url.includes(e.substring):i.url.match(e.pattern));a.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(a.map(i=>i.url))}`),o=a[a.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
3901
+ Available pages:${JSON.stringify(r.map(a=>a.url))}`);if(!no(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,n?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let n;return typeof e=="string"?n=ds(e):n=[e],await this.context.addCookies(n),n}async setLocalStorage(e,n){let r;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([a,i])=>{a&&localStorage.setItem(a,i||"")},[e,n],`setting local storage key ${e}`);return}catch(a){r=a}if(r)throw r}async solveCaptcha(){await this.getBrowserState({allowZeroOpacityOverride:!0});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let n=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),r=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:xl,task:{type:"ImageToTextTask",body:n.toString("base64"),case:!0},languagePool:"en"})});if(!r.ok){let s=`Captcha solver API returned error response: ${r.statusText}`;throw this.logger.error({text:await r.text()},s),new Error(s)}let{taskId:o}=await r.json(),a=Date.now(),i="";for(;Date.now()-a<6e4;){await J(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:xl,taskId:o})});if(!s.ok){let l=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},l),new Error(l)}let c=await s.json();if(c.errorId){let l=`Captcha solution API returned error ID ${c.errorId}`;throw this.logger.error(l),new Error(l)}if(c.status==="ready"){i=c.solution.text;break}}if(!i)throw new Error("Captcha solution timed out");return i}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},n)=>{this.transformer&&$y({event:n,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,n)=>{this.transformer&&this.transformer.recordKeystroke(n)})}async startRecordingCrons(e){if(e.aborted)return;let n,r=(await this.getOpenPages()).map(s=>s.url),o=0,a=!1,i=async()=>{if(e.aborted||o>8){clearTimeout(n);return}a=!0;let s;try{s=(await this.getOpenPages()).map(l=>l.url),o=0}catch(l){this.logger.debug({err:l},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let c=this.url();for(let l=s.length-1;l>=r.length;l--){let d=s[l];no(d,this.logger)&&d!==c&&this.logger.info({lastActivePages:r,currentUrl:c,newOpenPages:s},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(l)});break}r=s};n=setInterval(async()=>{if(!a){a=!0;try{await i()}catch(s){this.logger.error({err:s},"Error while checking pages during recording")}finally{a=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(n)})}async startRecording(e,n,r){this.logger.debug({isClickToRecord:r},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=o},r),this.transformer=n,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(r=>Array.from(r.querySelectorAll("option")).map(a=>({value:a.value,label:a.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:n,codePath:r}){let o=this.pageLoadTimeout,a=e.url();if(!a.includes("chrome-error://")){try{await to({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlDomContentLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(i){let s=i;if(s.name==="AbortError")throw new A("UserInfrastructureError",`The page with URL ${$e(a,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await to({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlPageLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(i){this.logger.warn({err:i,codePath:r,url:a},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:n=!1}=e??{};return n||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return hM.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:n,error:r}=await et({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(r)throw new Error(`Failed to process page HTML: ${r}`);if(!n)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return n}registerDialogHandler(e){let n=async r=>{try{e==="ACCEPT"?await r.accept():await r.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",n)}async evaluateFunctionInAllFrames(e,n){return this.stateManager.executeFunctionInAllFrames(e,n)}async evaluateFunctionInPage(e,n,r,o=2e3){let a=await this.getActivePageOrFrame();return et({root:a,fn:e,arg:n,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:r})}async evaluateCodeInPage({code:e,fragment:n,context:r,timeoutMs:o=lr}){let a=ny(),i={code:e,fragment:n,context:r},{result:s}=await j(this.page.evaluate(a,i),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new A("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,n){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let r;try{r=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:n},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:n},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return r}async getDomNodeFromPositionPercentages(e,{percentX:n,percentY:r}){if(n<0||n>1||r<0||r>1)throw new A("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:a,upperBound:i,leftBound:s}=await this.getViewportOffsetDetails(e),c=Math.round(i),l=Math.round(s),d=Math.ceil(o*n),u=Math.ceil(a*r),m=d+l,p=u+c;return this.getDomNodeFromPixelPosition(m,p)}async highlightFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r;try{r=await this.getDomNodeFromPositionPercentages(n,e)}catch{}return r?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:gy,backendNodeId:r.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:r?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r=await this.getDomNodeFromPositionPercentages(n,e);return this.getTargetFromBackendNodeId({root:n,backendNodeId:r.backendNodeId,allowZeroOpacityOverride:e.allowZeroOpacityOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:n,allowZeroOpacityOverride:r}){let o=this.stateManager.domGraph?.backendIdToNode[n];if(!o)throw new Error("No DOM node was found with the given backend ID");let a=o?.attributes[qn],i=parseInt(a??"");if(!a||isNaN(i))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(hn(i)),c;o.bounds.x!==null&&o.bounds.y!==null&&(c={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let l=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:c,allowZeroOpacityOverride:r}),d={id:-1,dataMomenticId:i,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...l};return this.logger.debug({target:d},"Tied backend ID to HTML node"),{target:d,locator:s}}async performTargetRedirection(e,n,r){try{return await this.scrollIntoViewIfNeeded(e),await j(this.performTargetRedirectionHelper(e,n,r),{milliseconds:3e3})??{locator:e}}catch(o){return n.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,n,r){let o=Date.now(),a=await Kn(e,n);if(r===void 0&&(r=await e.boundingBox({timeout:3e3})??void 0),!r){n.error(`Attempted to click on element with no bounding box: ${a}`);return}let{x:i,y:s,width:c,height:l}=r,d=this.getViewport();if(i<0||s<0||!d||i+c>d.width||s+l>d.height){n.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:m,mPathSelector:p,error:g,serializedElement:h,point:f,force:b,logs:y}=await e.evaluate(v=>{let R=window;if(!R.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return R.performTargetRedirection(v)},void 0,{timeout:1e3}),E=Date.now()-o;if(g){n.warn({error:g,serializedElement:h,duration:E,force:b,logs:y},"Got error from target redirection with bounding box");return}else{if(m)return n.info({newDataMomenticId:m,serializedElement:h,duration:E,force:b,logs:y},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(hn(m)),hints:{clickableXY:f,force:b}};if(p)return n.info({newMPathSelector:p,serializedElement:h,duration:E,force:b,logs:y},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(p),hints:{clickableXY:f,force:b}};if(f)return n.info({point:f,serializedElement:h,duration:E,force:b,logs:y},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:b}};if(b)return n.info({serializedElement:h,duration:E,force:b,logs:y},"Forcing click on original element"),{locator:e,hints:{force:b}}}}async fetchHtmlAttributes({locator:e,logger:n=this.logger,startingBoundingBox:r,allowZeroOpacityOverride:o}){let{hybridSelectorMode:a,showZeroOpacityElements:i}=this.userControlledBrowserSettings,s=await e.evaluate((c,l)=>{let d=window;return d.generateHtmlCacheAttributes?d.generateHtmlCacheAttributes(c,l):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:a==="test"||a==="prefer",startingBoundingBox:r,showZeroOpacityElements:o?!0:i},{timeout:2e3});if("error"in s&&s.error)throw s.error.startsWith(BS)?new ys(s.error):s.error.startsWith(zS)?new bs(s.error):new Error(s.error);return s.warnings.length&&n.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,n){let r=this.getViewport();if(!r)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(r.width*e),a=Math.ceil(r.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:a,button:"left",clickCount:0}}),{x:o,y:a}}async clickMouseFromPositionPercentages(e,n,r){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let a=Math.ceil(o.width*n),i=Math.ceil(o.height*r);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:a,y:i,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,n,r,o){let a=this.getViewport();if(!a)throw new Error("Cannot scroll using percentages without viewport");let i=Math.ceil(a.width*e),s=Math.ceil(a.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:i,deltaY:s,x:r,y:o}}),{deltaX:i,deltaY:s}}canSolveCaptchas(){return!!xl}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(n){this.logger.debug({err:n,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,n,r,...o){let a=this.context.pages().indexOf(e);a=a===-1?0:a,pu(e,this.debugData,a,{type:n,text:`[MOMENTIC] ${r}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:n}){if(!Al(e)){let c=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(c),this.logToUserConsole(this.page,"error",c);return}let r=n?.trim()||bM(e),o=pM(e),a=TM(e),i=od[a];this.page.once("filechooser",async c=>{this.logger.info({filePath:e,fileName:r},"File chooser triggered");try{if(!Al(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await c.setFiles({name:r,buffer:o,mimeType:fM.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(l){this.logger.error({err:l},"Error handling file chooser"),this.logToUserConsole(this.page,"error",l.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:c,base64Data:l,mimeType:d})=>{let u=window;u.momenticFileName=c,u.momenticFileBase64=l;let m=atob(l),p=new Array(m.length);for(let h=0;h<m.length;h++)p[h]=m.charCodeAt(h);let g=new Uint8Array(p);u.MomenticFile=class extends Blob{kind="file";name=u.momenticFileName;constructor(){super([g],{type:d})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],u.momenticFileName,{type:d})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},u.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new u.MomenticFile])},{fileName:r,base64Data:s,mimeType:i},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let n={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},n}async copy(e){try{await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard")}catch(n){if(n instanceof Error&&n.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(r=>navigator.clipboard.writeText(r),e,"copying text to clipboard");return}throw n}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(n=>{let r=n.request();return e.matches({url:r.url(),method:r.method()})})}registerRequestRecorder(e,n,r){this.requestRecorders[e]={onRequestStart:(o,a)=>{n.matches({url:a.request.url,method:a.request.method})&&r.onRequestStart(o,a)},onRequestComplete:(o,a)=>{n.matches({url:a.request.url,method:a.request.method})&&r.onRequestComplete(o,a)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,n,r){this.customHeaders.push({key:e.toLowerCase(),value:n,matcher:r})}registerMock(e,n,r,o){let a=e??Mu();return this.mocks[a]={matcher:n,generateResponse:r,fetchOriginalResponse:o},a}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return bi(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import $M from"fetch-cookie";import{cloneDeep as lb}from"lodash-es";import{CookieJar as jM}from"tough-cookie";async function wr(t,e={}){let n=await t.getBrowserState(e);return{serializedTree:n.serialize(),tree:n}}var ma=3.1783027;function xM(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);!(r>=48&&r<=57)&&!(r>=65&&r<=90)&&!(r>=97&&r<=122)&&e++}return e}function Ti(t){return Math.ceil(ku(t)/ma)}function ku(t){let e=0;if(typeof t=="string"){let n=t;n=n.replaceAll(`
3902
+ `,""),n=n.replaceAll(" ","");let r=xM(n);return n.length-r+ma*r}if(typeof t>"u")return 0;if(typeof t=="number")return String(t).length;if(Array.isArray(t))return t.forEach(n=>{e+=ku(n)}),e;if(typeof t=="object"){let n=t;return Object.keys(n).forEach(r=>{e+=String(r).length,r==="image_url"?(n[r]??{}).detail==="high"?e+=1105*ma:e+=85*ma:e+=ku(n[r])}),e}if(typeof t=="boolean")return t?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof t}': ${t}`)}var Jy={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Qy={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},Xy=/<(\S+) id="(\d+)".*?>/g,IM=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Zy=["h1","h2","section","footer","nav","aside","form","label","dialog"],PM=[...Zy,"span","div","h3"],MM=["table","select","form","ul","ol","menu","pre","code","dialog"],LM=["table","form","dialog","nav","section","ul","select"];function _u(t){return t.serializedTree.length>t.maxCharacterLength&&(t.logger.warn({serializedTreeLength:t.serializedTree.length},"Serialized condensed tree is too long to chunk, truncating before chunking"),t.serializedTree=t.serializedTree.slice(0,t.maxCharacterLength)),OM(t)}function OM({serializedTree:t,options:e,logger:n}){let{minChunkTokenCount:r,acceptableChunkTokenCount:o,maxChunkTokenCount:a,maxLineLength:i}=e,s=[],c=t.split(`
3903
+ `),l=0,d=[],u=0,m=[],p=[],g=!1;for(;l<c.length;){g&&(s.push({ids:m,content:d.join(`
3904
+ `),tokenLength:u}),d=[],u=0,m=p.length?[p[p.length-1].id]:[],g=!1);let h=c[l],f=Ti(h);u+=f,h.length>i&&(h=h.slice(0,i));let E=Array.from(h.matchAll(Xy)).map(M=>M&&M.length>=3?{tagName:M[1],id:M[2]}:void 0).filter(M=>!!M),R=Array.from(h.matchAll(IM)).map(M=>M&&(M[2]||M[4])).filter(M=>!!M);R.reverse();let C=h.replace(/ id="[0-9]+"/g,"");d.push(C);for(let M of E)m.push(M.id),p.push(M);for(let M of R){let z=p[p.length-1];z&&z.tagName===M&&p.pop()}let x=p.some(M=>MM.includes(M.tagName)),I=c[l+1]??"",D=Ti(I),q=Array.from(I.matchAll(Xy)).map(M=>M&&M.length>2?M[1]:void 0).filter(M=>!!M),$=q.some(M=>Zy.includes(M)),_=q.some(M=>PM.includes(M));u+D>=a&&(g=!0),u>=r&&($&&!x||R.some(M=>LM.includes(M)))&&(g=!0),u>=o&&_&&!x&&(g=!0),l++}return d.length&&s.push({ids:m,content:d.join(`
3905
+ `),tokenLength:u}),s.forEach((h,f)=>{n.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var Du=4e4,Fu=8e4;async function po(t){let{serializedTree:e,logger:n,aiPageFiltering:r,softTokenLimit:o=Du}=t;if(Ti(e)<o)return e;let i;r?i=_u({serializedTree:e,options:Qy,logger:n,maxCharacterLength:1e6}):i=_u({serializedTree:e,options:Jy,logger:n,maxCharacterLength:3e6});try{return r?await j(NM({...t,chunks:i.chunks}),{milliseconds:2e4}):await j(_M({...t,chunkResult:i}),{milliseconds:15e3})}catch(s){n.warn({err:s},"Error executing page filtering, attempting AI keyword fallback");try{return await kM({...t,chunks:i.chunks})}catch(c){return n.warn({err:c},"Error executing page filtering using keyword matching, using naive truncation"),e.slice(0,Fu*ma)}}}async function NM({chunks:t,generator:e,description:n,type:r,logger:o,signal:a,tree:i,softTokenLimit:s=Du,hardTokenLimit:c=Fu}){let l=await e.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:s,hardTokenLimit:c},{abortSignal:a,logger:o,loggerTags:Le(o)}),d=[];t.forEach((m,p)=>{l.indices.includes(p)&&(d=d.concat(m.ids))});let u=i.pruneUsingRelevantIds(new Set(d)).serialize();return o.debug({description:n,type:r,selectedChunks:l,tree:u},"Pruned a11y tree with AI page filtering"),u}async function kM(t){let{type:e,description:n,generator:r,tree:o,logger:a,hardTokenLimit:i=Fu}=t;if(!n.trim())throw new Error("Empty description passed to page filtering");let s=await r.getExtractedKeywords({goal:n},{logger:t.logger,loggerTags:Le(t.logger)});for(let c of s.keywords){let l=t.chunks.filter(p=>p.content.toLowerCase().includes(c.toLowerCase()));if(!l.length||l.reduce((p,g)=>p+g.tokenLength,0)>i&&l.length>1)continue;let u=l.flatMap(p=>p.ids),m=o.pruneUsingRelevantIds(new Set(u)).serialize();return a.debug({description:n,type:e,selectedChunks:l,tree:m},"Pruned a11y tree with keyword page filtering"),m}throw new Error("No keywords were unique enough for page filtering")}async function _M(t){let{description:e,generator:n,tree:r,logger:o,signal:a,chunkResult:i,softTokenLimit:s=Du}=t,c=await n.rankChunksWithRag({description:e,chunks:i.chunks,tokenLimit:s},{abortSignal:a,logger:o,loggerTags:Le(o)});if(c.ids.length===0)throw new Error("RAG returned no important ids");{let l=r.pruneUsingRelevantIds(new Set(c.ids.map(d=>`${d}`))).serialize();return o.debug({browserState:l},"Pruned a11y tree with RAG"),l}}async function Bu(t,e){if(!t.description)throw new A("UserConfigurationError","Cannot locate element with empty description");return Mn({action:async()=>DM(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function DM(t,e){let{disableCache:n,testContext:r,filterByViewport:o,skipWait:a,source:i,memory:s,aiPageFiltering:c,logger:l,allowZeroOpacityOverride:d}=t,{ctx:u,orgId:m,browser:p,localCodeEvalTools:g,generator:h,abortSignal:f}=e,b=t.description,y=t.useMemory&&!n;r&&(b=await jt({orgId:m,s:b,context:r,localTools:g,signal:f,logger:l})),i&&(b=UM(b,i));let{serializedTree:E,tree:v}=await wr(p,{allowZeroOpacityOverride:d,filterByViewport:o,abortSignal:f,skipWait:a,logger:l}),R,C=Date.now(),x;for(;!R&&Date.now()-C<3e3;){f.throwIfAborted();try{R=await p.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(oe){x=oe}}if(!R)throw new A("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${x?.message}`);let I=E,D=!1;I=await po({type:"locator",description:b,serializedTree:E,aiPageFiltering:c,tree:v,logger:l,generator:h}),I!==E&&(D=!0);let q=`data:image/jpeg;base64,${R.toString("base64")}`,$=await h.getElementLocation({browserState:I,goal:b,screenshot:q,source:i,memory:y?s:void 0},{disableCache:n,abortSignal:f,loggerTags:Le(l),useMemory:y});l.debug({usedRag:D,result:$},"Got locator result");let _=$.id>0;if(u?.details?.push({type:"AI_LOCATION",matched:_,pageState:I,ragUsed:D,thoughts:$.thoughts}),!_)throw new Go(`Could not find any relevant element: ${$.thoughts}`,$.updatedMemory?{type:"GCS_TRACES",traces:$.updatedMemory}:void 0);let{resolution:M,target:z,frameConfig:ue}=await p.createTargetFromA11yId({id:$.id,description:b,targetSource:"AI",logger:l});if(M.a11yNode?.properties?.hidden&&M.a11yNode?.properties?.hidden!=="false")throw new A("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${M.displayString}`);return y&&($.updatedMemory?z.memory={type:"GCS_TRACES",traces:$.updatedMemory}:s&&(z.memory=s)),{thoughts:$.thoughts,target:z,resolution:M,frameConfig:ue,screenshot:q}}var FM=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],eb="<select> element:",tb="text input or contenteditable element:",nb="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",rb="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",Uu=[eb,tb,nb,rb,...FM];function ob(t,e){if(t===e)return!0;for(let n of Uu){if(!t.startsWith(n))continue;let r=t.slice(n.length).trim();if(Uu.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===r)||r===e.trim())return!0}return!!Uu.some(n=>e.startsWith(n)&&e.slice(n.length).trim()===t.trim())}function UM(t,e){if(!t||!e)return t;switch(e){case"SELECT_OPTION":return`${eb} ${t}`;case"TYPE":return`${tb} ${t}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${nb}
3906
+ ${t}`;case"ELEMENT_CHECK":return`${rb}
3907
+ ${t}`;default:return t}}var BM=15;async function Il({command:t,aiPageFiltering:e,logger:n,fixtures:r,source:o,useMemory:a,maxRetries:i=BM}){if(!t.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=r,c=t.timeout?t.timeout*1e3:s.smartWaitingTimeout,l=vf(c),d=0,u=Date.now(),m,p,g;try{await Mn({action:()=>s.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:s,logger:n})}catch(f){n.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;d<i&&(!h||h-u<c);){r.abortSignal.throwIfAborted(),d!==0&&await J(l,r.abortSignal),h=Date.now();try{if(m=await Mn({action:async()=>{let b=await ab(s,n,r.abortSignal);return p&&p.serializedTree===b.serializedTree&&p.screenshotBuff.equals(b.screenshotBuff)?m:(p=b,ib({command:t,state:b,fixtures:r,useMemory:a,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:d,aiPageFiltering:e,logger:n,source:o}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s}),m?.updatedMemory&&(Bs(t,m.updatedMemory),n.info({updatedMemory:m.updatedMemory,command:t},"Wrote new memory to assertion command")),m?.success)break;throw m?.thoughts?new A("AssertionFailureError",m.thoughts):new A("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){r.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),n.info({err:f},`AI check assert attempt ${d} failed, retrying...`)}finally{d++}}if(!m?.success)try{m=await Mn({action:async()=>ib({command:t,state:await ab(s,n,r.abortSignal),fixtures:r,useMemory:a,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:d,aiPageFiltering:e,logger:n}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s})}catch(f){r.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{d++}if(!m?.success){let f=`AI check still failing after ${d} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new A("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function ab(t,e,n){let[r,o]=await Promise.all([wr(t,{abortSignal:n,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function ib({command:t,state:e,fixtures:n,useConsensus:r,useMemory:o,highlightElementsOnFailure:a,aiPageFiltering:i,attemptNumber:s,source:c,logger:l}){let{browser:d,generator:u,abortSignal:m}=n,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,b=d.url(),y=t.contextChoice??"MULTIMODAL",E=g;y!=="VISION_ONLY"&&(E=await po({type:"assertion",serializedTree:g,description:t.assertion,aiPageFiltering:i,tree:h,generator:u,logger:l,signal:m}),E!==g&&(p.ragUsed=!0),p.pageState=E);let v={goal:t.assertion,url:b,memory:o?t.cache?.memory:void 0,browserState:E,screenshot:f.toString("base64"),contextChoice:y,source:c},C=await(y==="VISION_ONLY"?(x,I)=>u.getVisualAssertionResult(x,I):(x,I)=>u.getAssertionResult(x,I))(v,{useConsensus:r,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:m,logger:l,loggerTags:Le(l)});return(C.result||a)&&C.relevantElements&&(p.relevantElementsSerialized=C.relevantElements.map(x=>d.getSerializedFormFromA11yId(x)).filter(x=>!!x),await zM(C.relevantElements,d,l)),{success:C.result,thoughts:C.thoughts,afterScreenshotOverride:f,updatedMemory:o?C.updatedMemory:void 0}}async function zM(t,e,n){let r=Date.now();for(let o of t){if(Date.now()-r>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let a=new AbortController;await j(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw a.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(a){n.debug({err:a},"Failed to highlight relevant element after assertion, continuing...");return}}}var HM=3e4;async function sb({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??HM/1e3,a=new AbortController,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([u,m])=>u&&m));i["Content-Type"]="application/json";let s;if(Zo(t.url)&&(s=t.url),n&&ea(t.url,n)&&(s=new URL(t.url,n).toString()),!s)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);let l=await j((async()=>{try{return await r(s,{headers:i,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables?JSON.parse(t.variables):void 0}),signal:a.signal})}catch(u){e.error({err:u},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!l)throw new A("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!l.ok){let u,m=await l.text();try{u=JSON.parse(m)}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}throw u?.errors?.length&&u?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${l.status}: ${u.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${l.status}: ${m}`)}let d={};return l.headers.forEach((u,m)=>{d[m]=u}),{status:l.status,headers:d,json:await l.json()}}var pa=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:n,logger:r,flagStore:o,storage:a,orgId:i,localCodeEvalTools:s,uploadedFileStorage:c,visualDiffScreenshotStorage:l,options:d}){this.orgId=i,this.options=d,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=a,this.uploadedFileStorage=c,this.visualDiffScreenshotStorage=l,this.localCodeEvalTools=s,this.generator=n,this.logger=r,this.flagStore=o}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:n,history:r,disableCache:o,langfuseSessionId:a,lastError:i,logger:s=this.logger}){let[c,l]=await Promise.all([wr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=await po({type:"ai-action",description:e,serializedTree:c.serializedTree,tree:c.tree,logger:s,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),u=`data:image/jpeg;base64,${l.toString("base64")}`,m={url:this.browser.url(),browserState:d,startingScreenshot:n,history:r,goal:e,screenshot:u,lastError:i};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Le(s)},langfuseSessionId:a})}async promptToCommand({goal:e,startingScreenshot:n,history:r,actionHint:o,disableCache:a,logger:i=this.logger,langfuseSessionId:s}){let c=this.browser.url(),[l,d]=await Promise.all([wr(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:i}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,m=await po({type:"ai-action",description:e,serializedTree:l.serializedTree,tree:l.tree,logger:i,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),p={url:c,browserState:m,startingScreenshot:n,history:r,goal:e,actionHint:o,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:a,abortSignal:this.executeAbortController.signal,loggerTags:{...Le(i)},langfuseSessionId:s})}catch(g){throw new A("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return wr(this.browser,e)}async locateElement(e){return await Bu({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,n){return Mn({action:async()=>{let r=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:r}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:a,caches:i,action:s,options:c,retriesWithAI:l=1}){let d=[];for(let u=0;u<a.length;u++){let m=a[u],p=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:m,cache:i[u],action:async g=>g,options:{...c,targetName:o[u]}});d.push(p)}try{let u=await s(...d.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=d.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:d.map(g=>g.elementInteractedDisplayString),thoughts:p}}catch(u){if(this.throwIfClosed(),l>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:a,caches:a.map(()=>{}),action:s,options:c,retriesWithAI:l-1});throw new A("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapElementTargetingCommand(e){let n=this.logger.child({commandId:e.command.id}),r;for(let o=0;o<2;o++)try{return await Mn({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:n})}catch(a){if(r=a,this.browser.userBrowserSettings.visualActions&&nd(a)){n.warn({err:a},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&Wa(a)){n.warn({err:a},"Invalid momentic id error, retrying element targeting command");continue}if(rd(a)&&n.warn({err:a},"Invalid backend node id error, retrying element targeting command"),a instanceof Rn&&a.retryableWithAI){n.warn({err:a},"Element cache disqualification error, retrying element targeting command");continue}throw a}throw r instanceof A?r:new A("ActionFailureError",r?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:n,action:r,options:o,command:a}){let i=this.logger.child({commandId:a.id}),{targetName:s}=o;if(n.type!=="description")throw new A("ActionFailureError","Cannot use selector with non-description target");let c,l=Date.now(),d=Date.now();for(;Date.now()-d<this.browser.smartWaitingTimeout;){l=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:n.elementDescriptor,targetName:s,logger:i});return{result:await r({locator:u.locator}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;c=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-l<500&&await J(500)}}throw c}async wrapElementTargetingCommandHelper(e){let{ctx:n,tracer:r,target:o,originalCache:a,action:i,options:s,command:c}=e,{disableCache:l,useSelector:d,targetName:u,targetHealingInProgress:m,source:p}=s,g=this.logger.child({commandId:c.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,b=!1,y=lb(e.cache);if((!y||l)&&!ac(o))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);l&&(g.info("Cache explicitly disabled for this step"),b=!0,y=void 0),y&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&y.targetSource==="HEURISTIC_HEALED"&&(b=!0,y=void 0),y?.inputDescription&&!ob(o.elementDescriptor,y.inputDescription)&&(g.warn({old:y.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),b=!0,y=void 0);let E=R=>!!R&&wm(R),v=!0;if(!E(y)){v=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:b,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),b&&await J(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let R;try{R=await Bu({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowZeroOpacityOverride:s.allowZeroOpacityOverride,logger:g},this.getControllerFixtures(n))}catch(I){if(I instanceof Go&&I.updatedLocatorMemory){let D={id:-1,...a,memory:I.updatedLocatorMemory};Us({cmd:c,key:u,newTarget:D,logger:g})}throw new A("ActionFailureError",I.message)}R.frameConfig&&this.browser.setActiveFrameConfig(R.frameConfig);let C=s.disableGlobalLocatorRedirect?{locator:R.resolution.locator}:await this.attemptLocatorRedirect(R.resolution.locator,g),x=await i(C);return Us({cmd:c,key:u,newTarget:R.target,logger:g}),m&&(r.heal({healType:"AI"}),R.target.targetSource="AI_HEALED",R.target.targetUpdateTime=new Date().toUTCString(),R.target.targetUpdateLoggerTags=Le(g)),{result:x,elementInteractedDisplayString:R.resolution.displayString,thoughts:R.thoughts}}try{let R=await this.browser.resolveTarget(n,y,{allowZeroOpacityOverride:s.allowZeroOpacityOverride,targetName:u,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(R.locator);let C=s.disableGlobalLocatorRedirect?{locator:R.locator}:await this.attemptLocatorRedirect(R.locator,g),x=await i(C);if(Us({cmd:c,key:u,newTarget:y,logger:g}),v){let I=R.decisions.filter(D=>D.matched);if(I.length!==1)g.warn({decisions:R.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let D=I[0].type;r.heal({healType:D})}}return{result:x,elementInteractedDisplayString:R.displayString}}catch(R){this.throwIfClosed();let C=!1;if((R instanceof Rn||nd(R)||Wa(R)||rd(R)||eg(R)||tg(R))&&(C=!0),R instanceof A&&!C)throw g.error({err:R},"Failed to execute action with cached target (fatal)"),R;if(f>0&&o){g.info({err:R},"Failed to execute action with cached target, retrying with AI");let x;return y.memory&&ki(y.memory)&&(x=y.memory),this.wrapElementTargetingCommand({ctx:n,tracer:r,command:c,target:o,cache:void 0,originalCache:a,action:i,options:{...s,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new A("ActionFailureError",R.message,{errOptions:{cause:R}})}}async attemptLocatorRedirect(e,n){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,n):{locator:e}}async screenshotWithDimensions(e){return fi(this.browser,e)}async executePresetCommand(e,n,r,o,a){this.options?.slowMoMs&&await J(this.options.slowMoMs);let i=await this.browser.getOpenPages(),s=this.browser.url(),c;try{c=await this.resolveCommandTemplateStrings(r,o)}catch(l){throw this.throwIfClosed(),new A("ActionFailureError",`Failed to substitute template strings in command: ${l.message}`,{errOptions:{cause:l}})}try{let l=await this.executePresetCommandHelper(e,n,r,o,a);return this.browser.userBrowserSettings.visualActions&&Pm(r)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(r.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await RS({beforeUrl:s,command:r,beforePages:i.map(d=>d.url),browser:this.browser,logger:this.logger}),l}catch(l){throw l.name!=="AbortError"&&this.logger.error({err:l},"Error thrown in action controller"),l}finally{mS(r,c)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>uu(e)}}async resolveCommandTemplateStrings(e,n){return ll({obj:e,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,n,r,o,a){a=a||"disableCache"in r&&!!r.disableCache;let i=this.logger.child({commandId:r.id});switch(r.type){case"SUCCESS":let s=r.condition;return s?.assertion.trim()?Il({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!r.assertion.trim())throw new A("ActionFailureError","Missing assertion");if(r.timeout&&r.timeout>1800)throw new A("AssertionFailureError",`AI check timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);return Il({command:r,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i})}case"AI_EXTRACT":{if(!r.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let f=dh(r.schema);if(f)throw new A("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:r.goal,browserState:g,returnSchema:r.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:a,abortSignal:this.executeAbortController.signal,loggerTags:Le(i)});if(f.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let b=f.message;throw b.includes("MaxGenerationLengthExceededError")?new A("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):b.includes("AIProviderError")&&b.includes("time")?new A("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Zo(r.url)&&!ea(r.url,this.browser.baseUrl))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${r.url}`);await this.browser.navigate({url:r.url,loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(r.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let c=await this.browser.solveCaptcha();c&&(await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...r,targetName:"target",disableCache:a}}),await this.browser.type(c,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(r.target&&bn(r.target))await this.browser.hoverUsingVisualCoordinates(r.target.pixels);else if(r.target&&r.target.elementDescriptor.trim()){let{elementInteractedDisplayString:y,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:v=>this.browser.hover(v),options:{...r,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:a}});g=y,h=E}let f=this.browser.getViewport()?.height??Nt.height,b=this.browser.getViewport()?.width??Nt.width;switch(r.type){case"SCROLL_UP":await this.browser.scrollVertical(-(r.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(r.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(r.deltaX??b));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(r.deltaX??b);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(r.timeout&&r.timeout>1800)throw new A("UserConfigurationError",`Wait for URL timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=r.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:r.timeout?r.timeout*1e3:void 0,negated:r.negated,caseInsensitive:r.caseInsensitive});break}case"WAIT":if(r.delay>1800)throw new A("UserConfigurationError",`Wait timeout of ${r.delay} seconds exceeds the maximum allowed value of 30 minutes`);let l=r.delay*1e3;await J(l,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"CLICK":{if(bn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:b}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:E=>this.browser.click(E,this.createCallbacksForBrowser(this.orgId),r),options:{disableCache:a,targetName:"target",...r}}),y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:b,data:f};return Qs(g,y.urlAfterCommand)&&(y.succeedImmediately=!0,y.succeedImmediatelyReason="URL changed"),y}case"COPY":return await this.browser.copy(r.value),{succeedImmediately:!1,data:r.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(bn(r.fromTarget)&&bn(r.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(r.fromTarget.pixels,r.toTarget.pixels,{hoverSeconds:r.hoverSeconds});break}if(bn(r.fromTarget)||bn(r.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:["fromTarget","toTarget"],descriptions:[r.fromTarget,r.toTarget],caches:[r.cache?.fromTarget,r.cache?.toTarget],action:(f,b)=>this.browser.dragAndDrop(f.locator,b.locator,{hoverSeconds:r.hoverSeconds,steps:r.steps}),options:{useSelector:!!r.useSelector,disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(r.deltaX),h=parseInt(r.deltaY),f=r.steps??5;if(isNaN(g)||isNaN(h))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${r.deltaX}, ${r.deltaY})`);if(r.target&&bn(r.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,r.target.pixels,{force:r.force});break}let b,y,E;if(r.target?.elementDescriptor){let{elementInteractedDisplayString:v,result:R,thoughts:C}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:async x=>x.locator,options:{disableCache:a,targetName:"target",...r}});b=R,y=v,E=C}return await this.browser.mouseDrag(g,h,f,b,{force:r.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:y,thoughts:E}}case"SELECT_OPTION":{if(!nr(r.target))throw new Error("Select with x/y is not supported yet");let g=r.target.elementDescriptor,h=r.choice,{elementInteractedDisplayString:f,thoughts:b}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:g},cache:r.cache?.target,action:y=>this.browser.selectOption(y,h,r.force),options:{...r,targetName:"target",disableCache:a,source:Hr(r)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:b}}case"TAB":{let g={loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(r.action,g);break}case"NEW_TAB":await this.browser.createNewTab(r.url,{loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"COOKIE":if(!r.value)break;let d=await this.browser.setCookie(r.value);i.debug({results:d},"Set cookies");break;case"LOCAL_STORAGE":if(!r.value||!r.key)break;await this.browser.setLocalStorage(r.key,r.value);break;case"JAVASCRIPT":{let g;try{r.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:r.code,fragment:r.fragment??!1,context:o.toObjectCopy(),timeoutMs:r.timeout?r.timeout*1e3:void 0}),i.info({result:g},"Executed JavaScript in browser")):g=await Sr({orgId:this.orgId,code:r.code,fragment:!!r.fragment,context:o,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){i.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:i})}}})}catch(h){throw this.throwIfClosed(),new A("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new A("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(r.target&&bn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r),await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);break}let g=this.browser.url(),h,f,b=lb(r.target);if(b){let{elementInteractedDisplayString:E,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:b,cache:r.cache?.target,action:R=>this.browser.typeIntoTarget(r.value,R,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter}),options:{...r,targetName:"target",disableCache:a,disableGlobalLocatorRedirect:!0,source:Hr(r)}});h=E,f=v}else await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);let y={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Qs(g,y.urlAfterCommand)&&(y.succeedImmediately=!0,y.succeedImmediatelyReason="URL changed"),y}case"HOVER":{if(bn(r.target)){await this.browser.hoverUsingVisualCoordinates(r.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.hover(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!nr(r.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.focus(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(r.target&&!nr(r.target))throw new Error("Blur with x/y is not supported yet");if(!r.target||!r.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:f=>this.browser.blur(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let u=this.browser.url();await this.browser.press(r.value,{repeat:r.repeat,convertMeta:r.convertMeta??!0,delayMs:r.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Qs(u,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new jM,h=$M(fetch,g),f;try{f=new URL(r.url).hostname}catch{}return{data:{...await SS({command:r,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:h}),cookies:Mp(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await sb({command:r,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return fS({ctx:e,tracer:n,command:r,disableCache:a,browser:this.browser,logger:i,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(r.fileSource.type==="URL"?(h=r.fileSource.url,g=await GS({uri:r.fileSource.url,logger:i,orgId:this.orgId})):r.fileSource.type==="USER_FILE"&&(h=r.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(r.fileSource.name,this.orgId)),!g)throw new A("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:r.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!r.storageState.trim())g=void 0;else if(g=await Sr({orgId:this.orgId,code:r.storageState,fragment:!1,context:o,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=us.optional().parse(g)}catch(f){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(r.timeout??Tn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(gS(r.assertion)&&!r.useSelector&&r.target.type==="description"&&h&&h!=="v1"){let b={id:r.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${r.target.elementDescriptor}`,iframeUrl:r.iframeUrl,timeout:r.timeout,cache:r.cache&&"memory"in r.cache?{memory:r.cache?.memory}:void 0};try{let y=await Il({command:b,logger:i,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${y.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:y.afterScreenshotOverride}}finally{b.cache?.memory&&Bs(r,b.cache?.memory.traces)}}let f=await pS({command:r,tracer:n,timeoutMs:g,targetingWrapper:b=>this.wrapElementTargetingCommand(b),fixtures:this.getControllerFixtures(e),disableCache:a});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await Mn({action:async()=>dl({assertion:r.assertion,browser:this.browser,logger:i,timeout:r.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:this.browser,logger:i});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${r.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new Tr(r.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[r.key]=h.then(async f=>await xu(f)).catch(f=>{i.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[r.key];if(!g)throw new A("ActionFailureError",`No listener registered with key: ${r.key}`);let h=r.timeout??10;return{data:await j(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new Tr(r.requestMatcher);return this.recordedRequests[r.key]={},this.browser.registerRequestRecorder(r.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[r.key][h]=El(f)},onRequestComplete:(h,f)=>{this.recordedRequests[r.key][h]=El(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[r.key];if(!g)throw new A("ActionFailureError",`No recorder registered with key: ${r.key}`);return delete this.recordedRequests[r.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return r.requestMatcher&&(g=new Tr(r.requestMatcher)),this.browser.setHeader(r.name,r.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(r.key,new Tr(r.requestMatcher),async(h,f)=>{let b=await Sr({orgId:this.orgId,code:r.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:i,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),y=jp.parse(b);return new Response(y.body,{status:y.status,headers:y.headers})},r.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(r.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(r.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:n,disableCache:r,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:n,screenshot:o},{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:Le(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:n,isClickToRecord:r}){this.recordAbortController=n;let o=new Rl({signal:n.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,r),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Le(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Le(this.logger)})}};import{z as sn}from"zod";var Ise=sn.object({useSelector:sn.boolean().optional(),disableCache:sn.boolean().optional(),iframeUrl:sn.string().optional(),retriesWithAI:sn.number().optional(),targetName:sn.union([sn.literal("target"),sn.literal("fromTarget"),sn.literal("toTarget")]),source:Wi.optional(),disableGlobalLocatorRedirect:sn.boolean().optional(),allowZeroOpacityOverride:sn.boolean().optional(),targetHealingInProgress:sn.boolean().optional(),memory:Eo.optional()});import{cloneDeep as GM}from"lodash-es";var WM={showOverlay:!1},Pl=class{sessions=new Map;sessionCountByIp=new Map;latestSessionId;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:n,cleanup:r,clientIp:o,sessionId:a,socket:i}){return this.sessions.set(a,{controller:e,context:n,cleanup:r,clientIp:o,browserBehavior:GM(WM),socket:i}),this.latestSessionId=a,a}removeSession(e,n){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:a}=o;try{a.setClosed(),await a.browser.cleanup()}catch(i){n.error({err:i},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(i){n.error({err:i},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}getLatestSession(){if(this.latestSessionId)return this.getSession(this.latestSessionId)}};function cb(t,e,n,r){let o=Date.now(),a=Date.now(),i,s,c,l,d=!1,u=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let b=c;c=void 0;let y=h.url(),E=f.toEditorDisplayCopy();JSON.stringify(E)===JSON.stringify(i)&&y===l&&o>a||(t.emit("browserState",{logsPerPage:b?.logsPerPage,harPages:b?.harPages,harEntries:b?.harEntries,viewport:h.getViewport(),url:y,iframeSrcUrls:s??[],context:E,isInPageLoad:h.isInPageLoad}),o=Date.now()),l=y,i=E}catch(b){if(!t.connected)return;let y=b instanceof Error?b.message:`${b}`;if(y.includes("Frame was detached")||y.includes("Not attached to an active page")||y.includes("browser has been closed")||y.includes("UserInfrastructureError"))return;n.error({err:b,sessionId:e},"Error grabbing browser state")}},m=setInterval(()=>{let h=r.getSession(e),f=h?.controller?.browser;if(!f||f.closed){n.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(m);return}u(f,h.context)},1e3),p=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(s)||f.logsPerPage.some(b=>b.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),g=setInterval(async()=>{let f=r.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(g);return}else if(d)return;d=!0;try{let b=await f.getAllFrameUrls(),y=f.retrieveAndClearDebugData();p(b,y)&&(s=b,c=y,a=Date.now())}catch(b){n.warn({err:b},"Failed to fetch extended details")}finally{d=!1}},2500);return{timers:[m,g]}}var VM=4;async function db({socket:t,logger:e,storageFactory:n,uploadedFileStorage:r,visualDiffScreenshotStorage:o,devicePixelRatio:a,generatorFactory:i,enricherFactory:s,authorization:c,flagStoreFactory:l,settingsFactory:d,getOrgId:u,branchGetter:m,globalE2eStateManager:p}){let g=t.id,h=t.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let f=await u({type:"e2e",testId:h}),b=await m?.();e=e.child({testId:h,orgId:f,sessionId:g,branch:b});let y=await i(f,e),E=await s(f,e),v=await l(f),R=await d(f,e),C=await n(f),{testMetadata:x,baseUrl:I,envName:D,browserConfig:k,aiSettings:q,environmentVariables:$,localCodeEvalTools:_}=await go({testId:h,orgId:f,logger:e,storage:C,authorization:c,flagStore:v,settings:R}),M=p.getSession(g);if(M)return e.info("Associating connection with existing session (likely reconnect)"),await M.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:g,orgId:f,testId:h};let z=t.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:z,event:"connect",args:t.handshake.query},"Websocket event (connect)"),z&&p.getCurrentConnectionsByIp(z)>=VM)throw e.error({clientIp:z,sessions:p.getCurrentSessionsByIp(),...t.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(z);try{await qM({socket:t,baseUrl:I,envName:D,testMetadata:x,orgId:f,sessionId:g,logger:e,environmentVariables:$,clientIp:z,devicePixelRatio:a,storage:C,uploadedFileStorage:r,visualDiffScreenshotStorage:o,localCodeEvalTools:_,generator:y,enricher:E,browserConfig:k,aiSettings:q,flagStore:v,globalE2eStateManager:p})}catch(ue){throw e.warn({err:ue},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(z),ue}return{type:"e2e",sessionId:g,testId:h,orgId:f}}async function qM({socket:t,baseUrl:e,envName:n,devicePixelRatio:r,testMetadata:o,orgId:a,sessionId:i,logger:s,storage:c,uploadedFileStorage:l,visualDiffScreenshotStorage:d,localCodeEvalTools:u,generator:m,environmentVariables:p,browserConfig:g,aiSettings:h,clientIp:f,enricher:b,flagStore:y,globalE2eStateManager:E}){let v={viewport:o.advanced?.viewport??Nt,locale:o.advanced?.locale??_o,timezoneId:o.advanced?.timezone??Do,geolocation:o.advanced?.geolocation??Fo,colorScheme:o.advanced?.colorScheme};r&&(v.deviceScaleFactor=r);let R=o.id,C=await hl({settings:g,orgId:a,baseUrl:e,envName:n,testName:o.name,localTools:u,envVariables:p,logger:s,customHeaders:void 0});s=s.child({orgId:a,sessionId:i,testId:R});let x=!1,I=y.isBooleanFlagEnabled("icon_knowledge_base")?await c.fetchIconKnowledgeBase(s):null,D=await kn.init({baseUrl:e,userBrowserSettings:C,enricher:b,storage:c,flagStore:y,logger:s,contextArgs:v,iconKnowledgeBase:I,callbacks:{onTabsChange:(M,z)=>{t.emit("tabs",{tabs:M,activeTab:z})},onScreencastFrame:(M,z)=>{let ue=t;x&&(ue=t.compress(!0)),ue.emit("screenshot",{buffer:M},()=>{z()})},onSvgsCollected:M=>{t.emit("newIconDetected",{numIcons:M.newSvgs.length}),c.saveNewIcons(M,s)}}});await D.navigate({url:e,initialNavigation:!0});let k=new pa({browser:D,generator:m,logger:s,flagStore:y,orgId:a,options:{scratchPadId:void 0,slowMoMs:C.slowMoMs,autoFollowNewTabs:C.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??y.isBooleanFlagEnabled("rag_v2")},storage:c,localCodeEvalTools:u,uploadedFileStorage:l,visualDiffScreenshotStorage:d}),q=cb(t,i,s,E),$=async()=>{q.timers.forEach(M=>clearInterval(M))},_=new Jt({baseUrl:e,testName:o.name,currentUrl:k.browser.url(),variablesFromEnvironment:p,envName:n});if(!t.connected)throw await D.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");t.emit("session",{url:e,userAgent:kn.USER_AGENT,viewport:k.browser.getViewport(),sessionId:i}),E.registerSession({controller:k,context:_,sessionId:i,cleanup:$,clientIp:f,socket:t})}async function go({testId:t,orgId:e,logger:n,storage:r,authorization:o,flagStore:a,settings:i}){let s=await r.fetchTestMetadata(t,n);if(!s)throw new Error(`Test metadata could not found for test ${t}`);let c;o?.type==="API_KEY"&&(c=new pr({httpClient:new xt({...o,logger:n}),fakerSeed:void 0}));let l=s.envs?.find(f=>f.default),d;l&&(d=await r.fetchEnvironment(l.name,n));let u=d&&"browser"in d?d.browser:void 0,m={...i.browser,...u,...s.advanced},p=s.baseUrl||d?.variables?.[it];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let g={...d?.variables};await Promise.all((s.parameters??[]).map(async f=>{let b=await jt({orgId:e,s:f.defaultValue,context:Jt.dummyContext(s.name,d?.name,g),logger:n,localTools:c});g[f.name]=b}));let h={...i.ai,...s.advanced};return{localCodeEvalTools:c,baseUrl:p,envName:d?.name,testName:s.name,browserConfig:m,environmentVariables:g,testMetadata:s,aiSettings:h}}var zu=class{parentTracer=null;socket;step;constructor({step:e,socket:n,parentTracer:r}){this.socket=n,this.parentTracer=r,this.step=e}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new Er({parentStep:this.step,socket:this.socket,parentTracer:this})}},Er=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:n,parentTracer:r}){this.parentTracer=r,this.parentStep=e,this.socket=n}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new zu({step:e.step,parentTracer:this,socket:this.socket})}},Ml=class{constructor(e,n,r,o,a){this.socket=e;this.storage=n;this.orgId=r;this.testId=o;this.stepsBeforeRun=a}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Er({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Er({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Er({parentStep:null,parentTracer:null,socket:this.socket})}};var Hu={currentlyExecutingRequests:{}},YM=t=>async(e,n)=>{let{testId:r,orgId:o}=t.metadata,a=await t.flagStoreFactory(o),i=await t.settingsFactory(o,t.logger),s=await t.storageFactory(o),c,l=await go({testId:r,orgId:o,logger:t.logger,storage:s,authorization:t.authorization,flagStore:a,settings:i}),d=`${r}|${l.baseUrl}`;try{let u=Hu.currentlyExecutingRequests[d]??0;Hu.currentlyExecutingRequests[d]=u+1,c=await XM({...t,...e,...l,done:n})}finally{t.logger.info({result:c,sessionId:t.metadata.sessionId},"Test execution complete"),Hu.currentlyExecutingRequests[d]--}},XM=async({socket:t,steps:e,baseUrl:n,testMetadata:r,reInitialize:o,toStep:a,fromStep:i,storageFactory:s,aiSettings:c,browserConfig:l,metadata:d,logger:u,envName:m,testName:p,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:b,globalE2eStateManager:y})=>{let{testId:E,sessionId:v,orgId:R}=d,C=v,x=y.getSession(v);if(!x)throw new Error("No active session found");let{controller:I,context:D}=x;I.setOpen(),u=u.child({testId:E,orgId:R,sessionId:v,runId:C}),u.info({steps:e.map(Z=>`${Z.type}${"command"in Z?` - ${Z.command.type}`:""}`),toStep:a,fromStep:i,reInitialize:o,envName:m,testName:p,baseUrl:n,context:D,flags:I.flagStore.getAllFlags()},"Socket execution parameters");let k=g??{},q=async()=>{o&&(await I.browser.reset({newUrl:n}),D.reset({baseUrl:n,currentUrl:I.browser.url(),variablesFromEnvironment:k,envName:m,testName:p}))},$=await s(R),_=await b(R),M=async()=>{try{await _.resolveStepCacheEntries({schemaVersion:r.schemaVersion,testId:E,stepLists:{steps:e},logger:u})}catch(Z){u.error({err:Z},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await ii({promiseGenerator:async()=>Promise.all([q(),M()]),signal:I.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),I.setOpen()}catch(Z){if(t.emit("finished"),Z.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${Z}`)}let z=KM(e),ue={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},oe={orgId:R,runId:C,testMetadata:r,steps:e,fromStep:i,toStep:a,orgSettings:{ai:c,browser:l}},ke={controller:I,context:D,storage:$,codeEvalTools:h,billingReporter:new zo,logger:u},je={test:{},step:{onDynamicAIActionStatusUpdateEvent:Z=>{t.emit("dynamicCommandStatusUpdate",Z)},onDynamicAIActionEvaluatingEvent:Z=>{t.emit("dynamicCommandEvaluating",Z)},onDynamicCommandGenerated:Z=>{t.emit("dynamicCommandGenerated",Z)},onDynamicCommandExecuted:Z=>{t.emit("dynamicCommandExecuted",Z)}}},Vt=new Ml(t,$,R,E,z),tt=await gl({fixtures:ke,options:ue,callbacks:je,inputs:oe,testParams:{tracer:Vt}});return tt?.status==="PASSED"?await zs({logger:u,cacheStorage:_,orgId:R,testId:E,originalSteps:{steps:z},updatedSteps:{steps:e}}):tt?.status==="FAILED"&&await Hs({logger:u,cacheStorage:_,orgId:R,testId:E,originalSteps:{steps:z},updatedSteps:{steps:e}}),await Vt.finish(),f?.(tt),tt.status};var ub={event:"execute",createHandler:YM};import{cloneDeep as JM}from"lodash-es";var QM=t=>async({command:e},n)=>{let{logger:r,generatorFactory:o,metadata:a}=t,i=JM(e),s=Vh(i);if(s.category!=="NO_DESCRIPTION_PROVIDED"){if(s.category!=="NONE"){n?.({result:s});return}"cache"in i&&(i.cache=void 0);try{let l=await(await o(a.orgId,r)).getLintStepResult({command:i},{logger:r});n?.({result:l})}catch(c){r.error({event:"lint",err:c},"Failed to lint step"),n?.({result:void 0})}}},mb={event:"lintStep",createHandler:QM};var ZM=({metadata:t,logger:e,storageFactory:n,globalE2eStateManager:r})=>{let{sessionId:o,orgId:a}=t;return async(i,s)=>{let{description:c,command:l,testMetadata:d,returnScreenshot:u}=i;e.info({params:i},`Locate handler called - ${c}`);let m=r.getSession(o);if(!m)throw new Error("No active session found");let{controller:p,context:g}=m;p.setOpen();let h=await n(a),f=Vr.parse(d.advanced??{}),b={},y;if(c){if("useSelector"in l&&l.useSelector)try{let E=await p.locateElementWithSelector(c,"iframeUrl"in l?l.iframeUrl:void 0);y=E.resolution.locator,b={target:E.target,thoughts:E.thoughts}}catch(E){e.warn({err:E},"Failed resolving target with selector"),s({err:`Failed locating element: ${E.message}`,decisions:E instanceof En?E.decisions:void 0});return}else try{let E=await p.locateElement({description:c,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Hr(l),iframeUrl:"iframeUrl"in l?l.iframeUrl:void 0,memory:"cache"in l&&l.cache&&"target"in l.cache&&ki(l.cache.target.memory)?l.cache.target.memory:void 0,logger:e});b={target:E.target,thoughts:E.thoughts},y=E.resolution.locator}catch(E){(async()=>{try{let v=await p.browser.getCondensedHtml({skipWait:!0});e.warn({err:E,html:v.slice(0,1e5)},"Failed locating element with AI")}catch(v){e.warn({err:v},"Failed grabbing HTML after trying to locate element with AI")}})(),s({err:`${E.message}`});return}if(l.type==="SELECT_OPTION"&&y)try{b.options=await p.browser.getSelectOptions(y)}catch(E){e.warn({err:E},"Failed getting select options"),s({err:`Failed getting select options: ${E.message}`});return}e.info({result:b},"Locate handler result")}if(u)try{let{buffer:E,width:v,height:R}=await p.screenshotWithDimensions({clearHighlights:!0,locator:y}),C=await h.uploadScreenshot(E);b.screenshot={data:C,width:v,height:R},e.info({width:v,height:R},"Captured screenshot during locate")}catch(E){e.error({err:E},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${E.message}`});return}if(s({result:b}),y)try{await Promise.all([p.browser.scrollIntoViewIfNeeded(y),p.browser.highlight(y)])}catch(E){e.warn({err:E},"Error highlighting element, continuing...")}}},pb={event:"locate",createHandler:ZM};var eL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({event:o,percentX:a,percentY:i})=>{let s=n.getSession(r);if(!s)throw new Error("No active session found");let c=s.controller.browser;if(c.closed||c.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await c.clickMouseFromPositionPercentages(o,a,i)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode")}}},gb={event:"mouseClickEvent",createHandler:eL};var tL=({metadata:t,generatorFactory:e,logger:n,socket:r,globalE2eStateManager:o})=>{let{sessionId:a,orgId:i,testId:s}=t;return async({stepId:c,parentStepIdChain:l,attribute:d})=>{let u=o.getSession(a);if(!u)throw new Error("No active session found");let{controller:m}=u,p=await e(i,n);m.setOpen(),u.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{u.browserBehavior.showOverlay=!1,await m.stopRecordMode()}catch(b){n.warn({err:b},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(b,y)=>{y.type!=="PRESET_ACTION"||y.command.type!=="CLICK"||(r.emit("targetRecordingUpdate",{type:b,stepId:c,parentStepIdChain:l,command:y.command,attribute:d}),g.abort(),h=!0)};setTimeout(()=>{h||(g.abort(),r.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:c,parentStepIdChain:l,attribute:d}))},1e4),await m.startRecordMode({params:{generator:p,logger:n,testId:s,orgId:i,callbacks:{onActionReceived:b=>f("clickReceived",b),onStepRecorded:b=>f("descriptionGenerated",b)}},abortController:g,isClickToRecord:!0}),r.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:c,parentStepIdChain:l,attribute:d})}},hb={event:"recordTargetClick",createHandler:tL};var nL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");if(o==="Dead")return;let{controller:i}=a;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),await i.browser.keyDown(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key down socket event error");return}throw s}}},fb={event:"keyDownEvent",createHandler:nL};var rL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");if(o==="Dead")return;let{controller:i}=a;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),await i.browser.keyUp(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key up socket event error");return}throw s}}},Sb={event:"keyUpEvent",createHandler:rL};var oL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t,o,a=0,i=(l,d)=>{let u=async()=>{o=void 0};clearTimeout(o),o=setTimeout(u,Math.min(1e3,250*(a+1)))},s,c=0;return async l=>{let d=n.getSession(r);if(!d)throw new Error("No active session found");let{controller:u,browserBehavior:m}=d,p=u.browser;if(p.closed||p.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(l.event==="scroll"){let g=await p.scrollFromPositionPercentages(l.percentX,l.percentY,s?.x??0,s?.y??0),h=d.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}m.showOverlay&&i(p,l);try{let g=await p.moveMouseFromPositionPercentages(l.percentX,l.percentY);c=0,s=g}catch(g){c++,c%5===0&&e.warn({err:g,mouseErrors:c},"Error in socket mouse move handler")}}},yb={event:"mouseMoveEvent",createHandler:oL};var aL=({metadata:t,generatorFactory:e,socket:n,logger:r,globalE2eStateManager:o})=>{let{sessionId:a,orgId:i,testId:s}=t;return async({stepId:c})=>{let l=o.getSession(a);if(!l)throw new Error("No active session found");let{controller:d,browserBehavior:u}=l,m=await e(i,r);r.info("Starting cloud recording");let p=new AbortController,g=await d.startRecordMode({params:{generator:m,logger:r,testId:s,orgId:i,callbacks:{onActionReceived:(h,f)=>{n.emit("stepRecorded",{stepId:c,step:h,offset:f})},onStepRecorded:(h,f)=>{n.emit("stepRecorded",{stepId:c,step:h,offset:f})}}},abortController:p,isClickToRecord:!1});u.recordingState={transformer:g}}},bb={event:"recordingStart",createHandler:aL};var iL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{let o=n.getSession(r);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},Tb={event:"recordingStop",createHandler:iL};var sL=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:a,settingsFactory:i,globalE2eStateManager:s})=>async(c,l)=>{let{testId:d,sessionId:u,orgId:m}=e;n.info({testId:d,sessionId:u},"Refresh event received");let p=await a(m),g=await i(m,n),h=await r(m),{baseUrl:f}=await go({testId:d,orgId:m,logger:n,storage:h,authorization:o,flagStore:p,settings:g}),b=s.getSession(u);if(!b){t.emit("error",{message:"No session to refresh"});return}let{controller:y}=b;y.setOpen(),await y.browser.refresh();let E=y.browser.getViewport();n.info({baseUrl:f,viewport:E},`Session refreshed for test ${d} at ${f}`),l()},wb={event:"refresh",createHandler:sL};var lL=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:a,settingsFactory:i,globalE2eStateManager:s})=>async()=>{let{testId:c,sessionId:l,orgId:d}=e;n.info({testId:c,sessionId:l},"Reset event received");let u=await a(d),m=await i(d,n),p=await r(d),{baseUrl:g,envName:h,testName:f,environmentVariables:b}=await go({testId:c,orgId:d,logger:n,storage:p,authorization:o,flagStore:u,settings:m}),y=s.getSession(l);if(!y){t.emit("error",{message:"No session to reset"});return}let{controller:E,context:v}=y;await E.browser.reset({newUrl:g});let R=E.browser.baseUrl;v.reset({baseUrl:R,currentUrl:E.browser.url(),variablesFromEnvironment:b,envName:h,testName:f});let C=E.browser.getViewport(),x=kn.USER_AGENT;n.info({baseUrl:g,viewport:C},`Session reset for test ${c} at ${R}`),t.emit("session",{url:R,userAgent:x,viewport:C,sessionId:l})},Eb={event:"reset",createHandler:lL};var cL=({metadata:t,globalE2eStateManager:e})=>{let{sessionId:n}=t;return async({url:r})=>{let o=e.getSession(n);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:r})}},Rb={event:"switchTab",createHandler:cL};async function Cb(t){return db(t)}var vb=[nS,ub,pb,Eb,wb,Zf,Rb,mb,hb,bb,Tb,yb,gb,fb,Sb,tS,eS];var Ab=t=>{let{logger:e}=t,n=new dL(t.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return n.on("connection",async r=>{let o;try{e.info({event:"connection",transport:r.conn.transport.name},"Websocket connection established"),o=await Cb({...t,socket:r,logger:e}),e=e.child(o)}catch(a){e.error({event:"connection",type:"websocket",err:a},"Failed to setup connection"),r.emit("error",{message:a instanceof Error?a.message:`${a}`}),r.disconnect(!0);return}vb.forEach(a=>uL(a,{...t,socket:r,metadata:o,logger:e}))}),n},uL=(t,e)=>{let n=t.createHandler(e),r=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(t.event)||e.logger.debug({...e.metadata,event:t.event},`Websocket event (${t.event})`);let a=i=>{e.logger.error({event:t.event,type:"websocket",err:i instanceof Error?i:new Error(`${i}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:i instanceof Error?i.message:`${i}`})};try{let i=n.apply(void 0,o);i&&typeof i.catch=="function"&&i.catch(a)}catch(i){a(i)}};e.socket.on(t.event,r)};import{Router as SL}from"express";import{Router as gL}from"express";import Ei from"fs";import wi from"path";import{v4 as hL}from"uuid";import fL from"yaml";import{hostname as mL}from"os";var pL="2.17.0",mt=Is({app:"desktop-server",hostname:mL(),disableConsoleLogs:!0}).child({cliVersion:pL});var ga=gL();async function $u(t){return(await rl(t,mt)).map(r=>{let o=t.modules[r.moduleId];if(!o){S.warn(`Found a dangling module with ID ${r.moduleId} that could not be found on disk.`);return}return{...o,content:r}}).filter(r=>r!==void 0)}ga.get("/",de(async(t,e)=>{let n=ie(),r=ne(n,S),o=await $u(r);e.status(200).json(o)}));ga.post("/",de(async(t,e)=>{let n;try{n=dg.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{Yr(n.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let r=ie(),o=ne(r,S).modules;if(Object.values(o).find(s=>s.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let a=wi.join(r.rootDir,n.folderPath??"");if(!Ei.existsSync(a)||!Ei.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let i=await Nf({...n,folder:a,project:r});e.status(201).json(i)}));ga.get("/:moduleId",de(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n=ne(ie(),S),r=n.modules[t.params.moduleId];if(!r){e.status(404).json({error:"Module not found."});return}try{let o=await nl(r,n,S);e.json(o)}catch(o){e.status(400).json({err:o})}}));ga.post("/:moduleId/duplicate",de(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=cg.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Yr(n.name)}catch(h){e.status(400).json({error:h.message});return}let r=ie(),o=ne(r,S),a=o.modules[t.params.moduleId];if(!a){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let i=await nl(a,o,S),s=wi.join(r.rootDir,wi.dirname(a.relativePath));if(!Ei.existsSync(s)||!Ei.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let c=Ce(n.name),l=wi.join(s,`${c}.module.yaml`),d=hL(),{stepsToSave:u}=await He({stepLists:{steps:i.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:on()}}),m={fileType:ge.MODULE,schemaVersion:le,moduleId:d,name:n.name,description:"",enabled:!0,steps:u.steps,parameters:i.parameters,defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums,defaultCacheKey:i.defaultCacheKey,defaultCacheTtl:i.defaultCacheTtl,defaultCacheAllInvocations:i.defaultCacheAllInvocations,autoAuth:i.autoAuth,advanced:i.advanced},p=fL.stringify(m);Ei.writeFileSync(l,p,"utf-8");let g={relativeFilePath:wi.relative(r.rootDir,l)};e.status(201).json(g)}));ga.patch("/:moduleId/metadata",de(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=ug.parse(t.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}let r=ie(),o=ne(r,S);Of({moduleId:t.params.moduleId,content:n,momenticFiles:o,logger:S,project:r}),e.status(201).json({message:"ok"})}));var xb=ga;var Ib=SL();Ib.get("/",de(async(t,e)=>{let n=ie(),r=ne(n,S),o=new Set;r?.tests&&Object.values(r.tests).forEach(l=>{l.labels?.forEach(d=>o.add(d))});let a=Array.from(o).sort(),i=Object.values(r.tests),s=await $u(r),c={labels:a,tests:i,modules:s};e.status(200).json(c)}));var Pb=Ib;import{Router as yL}from"express";var ju=yL();ju.get("/",de((t,e)=>{let n=Ff(ie(),mt);e.status(200).json(n)}));ju.get("/names",de((t,e)=>{let r=ie().config.environments?.map(o=>o.name)??[];e.status(200).json(r)}));var Mb=ju;import{Router as bL}from"express";var Lb=bL();Lb.get("/",de((t,e)=>{e.status(200).json({userId:el(),orgId:on()})}));var Ob=Lb;import{Router as TL}from"express";var Ll=TL();Ll.get("/",de((t,e)=>{let n=Yd().map(r=>({name:r.config.name,configFilePath:r.configFilePath}));e.status(200).json(n)}));Ll.get("/current",de((t,e)=>{let n=ie();if(!n){e.status(404).json({error:"No project found."});return}let r={name:n.config.name,configFilePath:n.configFilePath};e.status(200).json(r)}));Ll.post("/set",de((t,e)=>{let n;try{n=pg.parse(t.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}try{let r=dt({configFilePath:n.configFilePath});tl(r,o=>dt({configFilePath:o}))}catch(r){e.status(400).json({error:`Error setting project: ${r}`});return}e.sendStatus(204)}));var Nb=Ll;import{Router as wL}from"express";var kb=wL();kb.get("/",de((t,e)=>{let r={ai:ie().config.ai};e.status(200).json(r)}));var _b=kb;import{convertToModelMessages as VL,stepCountIs as qL,streamText as KL}from"ai";import YL from"dedent";import{Router as XL}from"express";import Gb from"fs";import So from"path";import{v4 as Wb}from"uuid";import JL from"yaml";import EL from"path";var Ol=class{_result=[];_includeSnapshot=!1;_includeTestContext=!1;_includeTest=!1;_isError;_browser;_testContext;_project;_logger;_testPath;constructor(e,n,r,o,a){this._browser=e,this._testContext=n,this._project=r,this._logger=o,this._testPath=a}addResult(e){this._result.push(e)}result(){return this._result.join(`
3910
3908
  `)}setIncludeSnapshot(){this._includeSnapshot=!0}async snapshot(){if(!this._includeSnapshot)return"";let e=this._browser.getActivePage(),n=await this._browser.getBrowserState({skipWait:!1}),r=[];return r.push("### Page state",`- Page URL: ${e.url()}`,`- Page Title: ${await e.title()}`,"- Page Snapshot:","```xml",n.serialize(),"```"),r.join(`
3911
3909
  `)}setIncludeTestContext(){this._includeTestContext=!0}testContext(){if(!this._includeTestContext)return"";let e=[],n=this._testContext.toObjectCopy();return e.push("### Environment variables","```json",JSON.stringify(n,null,2),"```"),e.join(`
3912
- `)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=te(this._project,this._logger),n=await Mt(SL.join(this._project.rootDir,this._testPath),this._logger,e),r=[];return r.push("### Test","```json",JSON.stringify(n,null,2),"```"),r.join(`
3910
+ `)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=ne(this._project,this._logger),n=await Mt(EL.join(this._project.rootDir,this._testPath),this._logger,e),r=[];return r.push("### Test","```json",JSON.stringify(n,null,2),"```"),r.join(`
3913
3911
  `)}addError(e){this._result.push(e),this._isError=!0}async serialize(){let e=[];this._result.length&&(e.push("### Result"),e.push(this._result.join(`
3914
3912
  `)),e.push(""));let n=await this.snapshot();n&&e.push(n,"");let r=this.testContext();r&&e.push(r,"");let o=await this.test();return o&&e.push(o,""),{content:[{type:"text",text:e.join(`
3915
- `)}],isError:this._isError}}};import{z as bL}from"zod";import{tool as yL}from"ai";var mt=t=>({builder:(n,r)=>yL({description:t.schema.description,inputSchema:t.schema.inputSchema,execute:async o=>{try{await t.handle(n,o,r)}catch(a){r.addError(String(a))}return r.serialize()}}),name:t.schema.name});var TL=mt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:bL.object({})},handle:async(t,e,n)=>{n.setIncludeSnapshot()}}),kb=[TL];import{randomUUID as _l}from"crypto";import{z as Ri}from"zod";import{z as wL}from"zod";var ho={id:!0,cache:!0},fo=wL.discriminatedUnion("type",[Or.omit(ho),Dr.omit(ho),kr.omit(ho),ir.omit(ho),ar.omit(ho),Nr.omit(ho),_r.omit(ho),gc.omit({id:!0}),wc.omit({id:!0}),xo.omit({id:!0}),Tc.omit({id:!0}),Ec.omit({id:!0}),hc.omit({id:!0})]);import{createAnthropic as EL}from"@ai-sdk/anthropic";import{randomUUID as RL}from"crypto";var _b=t=>e=>EL({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${t}`},apiKey:t})(e);var Ei=async({step:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s})=>{let{results:l}=await CL({steps:[t],controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s});return l[0]},CL=async({steps:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s})=>{let l={controller:e,storage:n,codeEvalTools:r,logger:o,context:i,billingReporter:new zo};return mn({listParams:{containerName:"copilot-steps",steps:t,tracer:new Rr({parentStep:null,parentTracer:null,socket:a})},fixtures:l,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:s,runId:RL(),steps:t,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};var vL=mt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:Ri.object({description:Ri.string().describe("Description of the element to preview.")})},handle:async({controller:t,logger:e,testContext:n},r,o)=>{o.setIncludeSnapshot();try{let a=await t.locateElement({description:r.description,disableCache:!0,skipWait:!0,logger:e,testContext:n});a.resolution.locator&&await Promise.all([t.browser.scrollIntoViewIfNeeded(a.resolution.locator),t.browser.highlight(a.resolution.locator)]),o.addResult(`Found element matching description: ${a.target.id}`),a.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${a.target.nodeOnlySerializedHtml}`);return}catch(a){o.addError(`Failed to find any element matching description: ${a}`)}}}),AL=mt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:Ri.object({assertion:Ri.string().describe("Assertion to confirm page state.")})},handle:async(t,e,n)=>{n.setIncludeSnapshot();let{logger:r,storage:o,controller:a,codeEvalTools:i,socket:s,orgId:l,testContext:c}=t,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:_l()},id:_l()},u=await Ei({step:d,controller:a,storage:o,codeEvalTools:i,logger:r,socket:s,orgId:l,testContext:c});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),xL=mt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:Ri.object({command:fo})},handle:async(t,e,n)=>{n.setIncludeSnapshot(),n.setIncludeTestContext();let{logger:r,storage:o,controller:a,codeEvalTools:i,socket:s,orgId:l,testContext:c}=t;n.setIncludeSnapshot();let d={type:"PRESET_ACTION",command:{...e.command,id:_l()},id:_l()},u=await Ei({step:d,controller:a,storage:o,codeEvalTools:i,logger:r,socket:s,orgId:l,testContext:c});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),Db=[vL,AL,xL];import IL from"path";import{z as Dl}from"zod";var PL=mt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:Dl.object({})},handle:async(t,e,n)=>{n.setIncludeTestContext()}}),ML=mt({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:Dl.object({})},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot(),await t.controller.browser.reset({})}}),LL=mt({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:Dl.object({index:Dl.number()})},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot();let{project:r,logger:o,testPath:a,storage:i,controller:s,codeEvalTools:l,socket:c,orgId:d,testContext:u}=t,m=te(r,o),g=(await Mt(IL.join(r.rootDir,a),o,m)).steps[e.index];if(!g){n.addError(`Step at index ${e.index} does not exist.`);return}let h=await Ei({step:g,controller:s,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:d,testContext:u});if(!h){n.addError(`Step at index ${e.index} executed with unknown result.`);return}if(h.status==="SUCCESS"){n.addResult(`Step at index ${e.index} executed successfully: ${h.message}`),h.data&&n.addResult(`Data: ${JSON.stringify(h.data,null,2)}`);return}n.addError(`Step at index ${e.index} failed: ${h.message}`)}}),Fb=[PL,ML,LL];import{randomUUID as Cr}from"crypto";import Ci from"path";import{z as gn}from"zod";var OL=mt({schema:{name:"test_get",description:"Get test contents.",inputSchema:gn.object({})},handle:async(t,e,n)=>{n.setIncludeTest()}}),NL=mt({schema:{name:"test_insert_step",description:"Insert a step into the test.",inputSchema:gn.object({index:gn.number(),command:fo})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Cr()},id:Cr()};l.steps.splice(e.index,0,c);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),kL=mt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:gn.object({index:gn.number(),command:fo})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Cr()},id:Cr()};l.steps.splice(e.index,1,c);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),_L=mt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:gn.object({index:gn.number()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s);l.steps.splice(e.index,1);let{stepsToSave:c,moduleUpdates:d}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});d.forEach(u=>{$t({content:u,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:c,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),DL=mt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:gn.object({startIndex:gn.number(),deleteCount:gn.number(),commands:fo.array()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Cr()},id:Cr()}));l.steps.splice(e.startIndex,e.deleteCount,...c);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),FL=mt({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:gn.object({commands:fo.array()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Cr()},id:Cr()}));l.steps=c;let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),Ub=[OL,NL,kL,_L,DL,FL];var Bb=[...kb,...Fb,...Db,...Ub];var Fl=new Ll;var ha=class extends qo{constructor(n,r){super(n,r);this.client=n;this.orgId=r}async fetchTestMetadata(n,r){let o=ae(),i=te(o,r).tests[n];if(i)return ol(i.relativePath,o)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(n,r){let o=ae();return ui(n,o,Xr)}async fetchIconKnowledgeBase(n){try{return await this.client.fetchIconKnowledgeBase(n)}catch(r){return n.error({err:r},"Failed to fetch icon knowledge base"),null}}};import{randomUUID as UL}from"node:crypto";import{PostHog as BL}from"posthog-node";var Ul=class t{bindings;client;options;constructor(e,n={}){this.bindings=e,this.options=n,this.client=new BL("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...n})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new t({...this.bindings,...e},this.options)}track(e,n){if(!vp(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:UL(),event:r,timestamp:n?.timestamp,properties:{...this.bindings,...o}}),this}};var vi=new Ul({platform:"local_app"},{flushAt:1,flushInterval:0});var vr=GL();vr.post("/",ce(async(t,e)=>{let n;try{n=lg.parse(t.body)}catch(u){e.status(400).json({error:`Invalid request body: ${u}`});return}try{Yr(n.name)}catch(u){e.status(400).json({error:u.message});return}let o={id:Hb(),name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:se,advanced:{browserType:n.browserType??"Chromium",viewport:n.viewport??Nt},retries:0,steps:[]};n.environment&&(o.envs=[{name:n.environment,default:!0}]);let a=ae(),i=te(a,S);if(Object.values(i.tests).find(u=>u.name===n.name)){e.status(400).send(`A test with the name "${n.name}" already exists. Please use a different name.`);return}let l=So.join(a.rootDir,...n.pathSegments||[]),c=await Df({test:o,name:n.name,folder:l}),d={...o,relativeFilePath:So.relative(a.rootDir,c)};vi.track({type:"test_editor:test_create"}),e.status(201).json(d)}));vr.get("/:testPath",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=ae(),o=te(r,S),a;try{a=await Mt(So.join(r.rootDir,n),ut,o),e.status(200).json(a)}catch(i){e.status(400).send({error:i.message});return}(async()=>{try{let{stepsToSave:i,moduleUpdates:s}=await He({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps}});s.forEach(l=>{$t({content:l,schemaVersion:se,momenticFiles:o,project:r})}),Pt({relativeTestPath:n,steps:i,schemaVersion:se,project:r})}catch(i){ut.error({err:i},"Failed to save migrated test to disk after initial fetch")}})()}));vr.patch("/:testPath/metadata",ce(async(t,e)=>{if(!t.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=sg.parse(t.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}let o={message:"ok",newRelativeTestPath:Gd(t.params.testPath,n,ae()).newRelativeTestPath};e.status(200).json(o)}));vr.patch("/:testPath",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=ig.parse(t.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}let o=ae(),a=te(o,S),i;try{i=ol(n,o)}catch(p){e.status(400).json({error:`Existing test file on disk is invalid: ${p}`});return}let{stepsToSave:s,moduleUpdates:l,cachesToSave:c}=await He({stepLists:r.stepLists,cacheCreationParams:{testId:i.id,orgId:rn()}}),d=new Je({apiKey:Hd(),baseUrl:ii(),logger:ut}),u=await Sr(ut,d,o);await ta({orgId:rn(),client:d,gitMetadata:u}).saveStepCacheEntries({logger:ut,testId:i.id,entries:c}),l.forEach(p=>{$t({content:p,schemaVersion:r.schemaVersion,momenticFiles:a,project:o})}),Pt({relativeTestPath:n,steps:s,schemaVersion:r.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));vr.patch("/:testPath/environments",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=pg.parse(t.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Gd(n,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},ae()),e.status(201).json({message:"ok"})}));vr.post("/:testPath/duplicate",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=cg.parse(t.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Yr(r.name)}catch(f){e.status(400).json({error:f.message});return}let o=ae(),a=So.join(o.rootDir,n);if(!zb.existsSync(a)){e.status(404).json({error:"Test not found."});return}let i=te(o,S),s;try{s=await Mt(a,ut,i)}catch(f){e.status(400).send({error:f.message});return}let l=Hb(),c=en.parse({...s,name:r.name,id:l}),{stepsToSave:d}=await He({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:l,orgId:rn()}}),u=Gn({fileType:pe.TEST,...c,beforeSteps:d.beforeSteps??void 0,steps:d.steps,afterSteps:d.afterSteps??void 0}),m=So.dirname(a),p=So.join(m,`${r.name}.${st.TEST}`),g=WL.stringify(u);zb.writeFileSync(p,g,"utf-8");let h={relativeFilePath:So.relative(o.rootDir,p)};vi.track({type:"test_editor:test_create"}),e.status(201).json(h)}));vr.post("/:testPath/chat",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=Fl.getLatestSession();if(!r){e.status(400).json({error:"No active session."});return}let{messages:o}=t.body,a=Hd(),i=rn(),s=ii(),l=ae(),c=ut,d=new Je({apiKey:a,baseUrl:s,logger:c}),u=new ha(d,i),m=new fr(l.config),p=new gr({httpClient:new xt({baseUrl:d.baseUrl,apiKey:d.apiKey,logger:c}),fakerSeed:l.config.advanced?.fakerConstantSeed?gs:void 0}),g={project:l,apiKey:a,orgId:i,baseUrl:s,logger:c,storage:u,flagStore:m,codeEvalTools:p,testPath:n,testContext:r.context,controller:r.controller,socket:r.socket},h=Bb.reduce((b,{name:w,builder:C})=>(b[w]=C(g,new kl(g.controller.browser,g.testContext,g.project,g.logger,g.testPath)),b),{}),f=_b(a);$L({model:f("claude-opus-4-20250514"),stopWhen:HL(30),maxRetries:4,system:jL`
3913
+ `)}],isError:this._isError}}};import{tool as RL}from"ai";import{z as CL}from"zod";var Db=t=>({builder:(n,r)=>RL({description:t.schema.description,inputSchema:CL.object(t.schema.inputSchema),execute:async o=>{try{await t.handle(n,o,r)}catch(a){r.addError(String(a))}return r.serialize()}}),tool:t});var pt=t=>({builder:Db(t).builder,name:t.schema.name});var vL=pt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:{}},handle:async(t,e,n)=>{n.setIncludeSnapshot()}}),Fb=[vL];import{randomUUID as Nl}from"crypto";import{z as Bb}from"zod";import{z as AL}from"zod";var ho={id:!0,cache:!0},fo=AL.discriminatedUnion("type",[Or.omit(ho),Dr.omit(ho),kr.omit(ho),ar.omit(ho),or.omit(ho),Nr.omit(ho),_r.omit(ho),uc.omit({id:!0}),yc.omit({id:!0}),xo.omit({id:!0}),Sc.omit({id:!0}),bc.omit({id:!0}),mc.omit({id:!0})]);import{createAnthropic as xL}from"@ai-sdk/anthropic";import{randomUUID as IL}from"crypto";var Ub=t=>e=>xL({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${t}`},apiKey:t})(e);var Ri=async({step:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s})=>{let{results:c}=await PL({steps:[t],controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s});return c[0]},PL=async({steps:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s})=>{let c={controller:e,storage:n,codeEvalTools:r,logger:o,context:i,billingReporter:new zo};return gn({listParams:{containerName:"copilot-steps",steps:t,tracer:new Er({parentStep:null,parentTracer:null,socket:a})},fixtures:c,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:s,runId:IL(),steps:t,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};var ML=pt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:{description:Bb.string().describe("Description of the element to preview.")}},handle:async({controller:t,logger:e,testContext:n},r,o)=>{o.setIncludeSnapshot();try{let a=await t.locateElement({description:r.description,disableCache:!0,skipWait:!0,logger:e,testContext:n});a.resolution.locator&&await Promise.all([t.browser.scrollIntoViewIfNeeded(a.resolution.locator),t.browser.highlight(a.resolution.locator)]),o.addResult(`Found element matching description: ${a.target.id}`),a.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${a.target.nodeOnlySerializedHtml}`);return}catch(a){o.addError(`Failed to find any element matching description: ${a}`)}}}),LL=pt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:{assertion:Bb.string().describe("Assertion to confirm page state.")}},handle:async(t,e,n)=>{n.setIncludeSnapshot();let{logger:r,storage:o,controller:a,codeEvalTools:i,socket:s,orgId:c,testContext:l}=t,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:Nl()},id:Nl()},u=await Ri({step:d,controller:a,storage:o,codeEvalTools:i,logger:r,socket:s,orgId:c,testContext:l});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),OL=pt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:{command:fo}},handle:async(t,e,n)=>{n.setIncludeSnapshot(),n.setIncludeTestContext();let{logger:r,storage:o,controller:a,codeEvalTools:i,socket:s,orgId:c,testContext:l}=t;n.setIncludeSnapshot();let d={type:"PRESET_ACTION",command:{...e.command,id:Nl()},id:Nl()},u=await Ri({step:d,controller:a,storage:o,codeEvalTools:i,logger:r,socket:s,orgId:c,testContext:l});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),zb=[ML,LL,OL];import NL from"path";import{z as kL}from"zod";var _L=pt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:{}},handle:async(t,e,n)=>{n.setIncludeTestContext()}}),DL=pt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:{}},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot(),await t.controller.browser.reset({})}}),FL=pt({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:{index:kL.number()}},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot();let{project:r,logger:o,testPath:a,storage:i,controller:s,codeEvalTools:c,socket:l,orgId:d,testContext:u}=t,m=ne(r,o),g=(await Mt(NL.join(r.rootDir,a),o,m)).steps[e.index];if(!g){n.addError(`Step at index ${e.index} does not exist.`);return}let h=await Ri({step:g,controller:s,storage:i,codeEvalTools:c,logger:o,socket:l,orgId:d,testContext:u});if(!h){n.addError(`Step at index ${e.index} executed with unknown result.`);return}if(h.status==="SUCCESS"){n.addResult(`Step at index ${e.index} executed successfully: ${h.message}`),h.data&&n.addResult(`Data: ${JSON.stringify(h.data,null,2)}`);return}n.addError(`Step at index ${e.index} failed: ${h.message}`)}}),Hb=[_L,DL,FL];import{randomUUID as Rr}from"crypto";import vi from"path";import{z as Ci}from"zod";var UL=pt({schema:{name:"test_get",description:"Get test contents.",inputSchema:{}},handle:async(t,e,n)=>{n.setIncludeTest()}}),BL=pt({schema:{name:"test_insert_step",description:"Insert a step into the test.",inputSchema:{index:Ci.number(),command:fo}},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=ne(r,o),c=await Mt(vi.join(r.rootDir,a),o,s),l={type:"PRESET_ACTION",command:{...e.command,id:Rr()},id:Rr()};c.steps.splice(e.index,0,l);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:le,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:le,project:r}),i.emit("copilotStepsUpdated",c.steps)}}),zL=pt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:{index:Ci.number(),command:fo}},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=ne(r,o),c=await Mt(vi.join(r.rootDir,a),o,s),l={type:"PRESET_ACTION",command:{...e.command,id:Rr()},id:Rr()};c.steps.splice(e.index,1,l);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:le,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:le,project:r}),i.emit("copilotStepsUpdated",c.steps)}}),HL=pt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:{index:Ci.number()}},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=ne(r,o),c=await Mt(vi.join(r.rootDir,a),o,s);c.steps.splice(e.index,1);let{stepsToSave:l,moduleUpdates:d}=await He({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});d.forEach(u=>{$t({content:u,schemaVersion:le,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:l,schemaVersion:le,project:r}),i.emit("copilotStepsUpdated",c.steps)}}),$L=pt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:{startIndex:Ci.number(),deleteCount:Ci.number(),commands:fo.array()}},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=ne(r,o),c=await Mt(vi.join(r.rootDir,a),o,s),l=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Rr()},id:Rr()}));c.steps.splice(e.startIndex,e.deleteCount,...l);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:le,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:le,project:r}),i.emit("copilotStepsUpdated",c.steps)}}),jL=pt({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:{commands:fo.array()}},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=ne(r,o),c=await Mt(vi.join(r.rootDir,a),o,s),l=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Rr()},id:Rr()}));c.steps=l;let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:c.steps,beforeSteps:c.beforeSteps,afterSteps:c.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:le,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:le,project:r}),i.emit("copilotStepsUpdated",c.steps)}}),$b=[UL,BL,zL,HL,$L,jL];var jb=[...Fb,...Hb,...zb,...$b];var kl=new Pl;var ha=class extends qo{constructor(n,r){super(n,r);this.client=n;this.orgId=r}async fetchTestMetadata(n,r){let o=ie(),i=ne(o,r).tests[n];if(i)return ol(i.relativePath,o)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(n,r){let o=ie();return mi(n,o,Xr)}async fetchIconKnowledgeBase(n){try{return await this.client.fetchIconKnowledgeBase(n)}catch(r){return n.error({err:r},"Failed to fetch icon knowledge base"),null}}};import{randomUUID as GL}from"node:crypto";import{PostHog as WL}from"posthog-node";var _l=class t{bindings;client;options;constructor(e,n={}){this.bindings=e,this.options=n,this.client=new WL("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...n})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new t({...this.bindings,...e},this.options)}track(e,n){if(!Cp(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:GL(),event:r,timestamp:n?.timestamp,properties:{...this.bindings,...o}}),this}};var Ai=new _l({platform:"local_app"},{flushAt:1,flushInterval:0});var Cr=XL();Cr.post("/",de(async(t,e)=>{let n;try{n=sg.parse(t.body)}catch(u){e.status(400).json({error:`Invalid request body: ${u}`});return}try{Yr(n.name)}catch(u){e.status(400).json({error:u.message});return}let o={id:Wb(),name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:le,advanced:{browserType:n.browserType??"Chromium",viewport:n.viewport??Nt},retries:0,steps:[]};n.environment&&(o.envs=[{name:n.environment,default:!0}]);let a=ie(),i=ne(a,S);if(Object.values(i.tests).find(u=>u.name===n.name)){e.status(400).send(`A test with the name "${n.name}" already exists. Please use a different name.`);return}let c=So.join(a.rootDir,...n.pathSegments||[]),l=await _f({test:o,name:n.name,folder:c}),d={...o,relativeFilePath:So.relative(a.rootDir,l)};Ai.track({type:"test_editor:test_create"}),e.status(201).json(d)}));Cr.get("/:testPath",de(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=ie(),o=ne(r,S),a;try{a=await Mt(So.join(r.rootDir,n),mt,o),e.status(200).json(a)}catch(i){e.status(400).send({error:i.message});return}(async()=>{try{let{stepsToSave:i,moduleUpdates:s}=await He({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps}});s.forEach(c=>{$t({content:c,schemaVersion:le,momenticFiles:o,project:r})}),Pt({relativeTestPath:n,steps:i,schemaVersion:le,project:r})}catch(i){mt.error({err:i},"Failed to save migrated test to disk after initial fetch")}})()}));Cr.patch("/:testPath/metadata",de(async(t,e)=>{if(!t.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=ig.parse(t.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}let o={message:"ok",newRelativeTestPath:$d(t.params.testPath,n,ie()).newRelativeTestPath};e.status(200).json(o)}));Cr.patch("/:testPath",de(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=ag.parse(t.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}let o=ie(),a=ne(o,S),i;try{i=ol(n,o)}catch(p){e.status(400).json({error:`Existing test file on disk is invalid: ${p}`});return}let{stepsToSave:s,moduleUpdates:c,cachesToSave:l}=await He({stepLists:r.stepLists,cacheCreationParams:{testId:i.id,orgId:on()}}),d=new Ze({apiKey:Bd(),baseUrl:si(),logger:mt}),u=await fr(mt,d,o);await ta({orgId:on(),client:d,gitMetadata:u}).saveStepCacheEntries({logger:mt,testId:i.id,entries:l}),c.forEach(p=>{$t({content:p,schemaVersion:r.schemaVersion,momenticFiles:a,project:o})}),Pt({relativeTestPath:n,steps:s,schemaVersion:r.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));Cr.patch("/:testPath/environments",de(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=mg.parse(t.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}$d(n,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},ie()),e.status(201).json({message:"ok"})}));Cr.post("/:testPath/duplicate",de(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=lg.parse(t.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Yr(r.name)}catch(f){e.status(400).json({error:f.message});return}let o=ie(),a=So.join(o.rootDir,n);if(!Gb.existsSync(a)){e.status(404).json({error:"Test not found."});return}let i=ne(o,S),s;try{s=await Mt(a,mt,i)}catch(f){e.status(400).send({error:f.message});return}let c=Wb(),l=tn.parse({...s,name:r.name,id:c}),{stepsToSave:d}=await He({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:c,orgId:on()}}),u=jn({fileType:ge.TEST,...l,beforeSteps:d.beforeSteps??void 0,steps:d.steps,afterSteps:d.afterSteps??void 0}),m=So.dirname(a),p=So.join(m,`${r.name}.${lt.TEST}`),g=JL.stringify(u);Gb.writeFileSync(p,g,"utf-8");let h={relativeFilePath:So.relative(o.rootDir,p)};Ai.track({type:"test_editor:test_create"}),e.status(201).json(h)}));Cr.post("/:testPath/chat",de(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=kl.getLatestSession();if(!r){e.status(400).json({error:"No active session."});return}let{messages:o}=t.body,a=Bd(),i=on(),s=si(),c=ie(),l=mt,d=new Ze({apiKey:a,baseUrl:s,logger:l}),u=new ha(d,i),m=new hr(c.config),p=new pr({httpClient:new xt({baseUrl:d.baseUrl,apiKey:d.apiKey,logger:l}),fakerSeed:c.config.advanced?.fakerConstantSeed?gs:void 0}),g={project:c,apiKey:a,orgId:i,baseUrl:s,logger:l,storage:u,flagStore:m,codeEvalTools:p,testPath:n,testContext:r.context,controller:r.controller,socket:r.socket},h=jb.reduce((y,{name:E,builder:v})=>(y[E]=v(g,new Ol(g.controller.browser,g.testContext,g.project,g.logger,g.testPath)),y),{}),f=Ub(a);KL({model:f("claude-opus-4-20250514"),stopWhen:qL(30),maxRetries:4,system:YL`
3916
3914
  <core-identity>
3917
3915
  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.
3918
3916
  </core-identity>
@@ -3958,27 +3956,27 @@ ${t}`;default:return t}}var kM=15;async function Ml({command:t,aiPageFiltering:e
3958
3956
  - Never insert destructive actions (e.g., mass delete) unless explicitly asked.
3959
3957
  - Keep edits scoped to the user's intent; do not optimize unrelated steps.
3960
3958
  </safety>
3961
- `,messages:zL(o),tools:h}).pipeUIMessageStreamToResponse(e,{onError:b=>b instanceof Error?b.message:String(b)})}));var $b=vr;var Ai=class{async prepareGoldenScreenshotForComparison(e,n,r){return await new sa(ae(),!1).prepareGoldenScreenshotForComparison(e,n,r)}};async function Vb(t){let{momenticServerUrl:e,apiKey:n,serverPort:r,staticDir:o,devicePixelRatio:a,alwaysSaveCache:i,noCache:s,initialProject:l}=t;e&&Mf(e),await Lf(n);let c=rn(),d=el();vi.identify({user_id:d,org_id:c});let u=t.logger??ut;u=u.child({orgId:c,userId:d}),u.debug({params:t},"Desktop server init and api key check done");let m=QL(o,r,u),p=`http://localhost:${r}`;S.info(`Desktop server is running at ${p}`),tl(l,C=>ct({configFilePath:C})),await new Promise(C=>{try{m.listen(r,()=>{u.info(`Desktop server is running at ${p}`),C()})}catch(v){v.message.includes("EADDRINUSE")?qb(r):S.error(`An unexpected error occurred while starting the server: ${v.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:ii(),apiKey:n,logger:u},f=async()=>{let C=ae();return new Yo(C.config.ai?.agentConfig,h)},y=async()=>new Xo(h,await f()),b=new Je(h),w=new Ai;Cb({baseServer:m,getOrgId:async()=>rn(),generatorFactory:f,enricherFactory:y,cacheStorageFactory:async C=>{let v=ae(),R=await Sr(u,b,v);return ta({orgId:C,client:b,gitMetadata:R,alwaysSaveCache:i,noCache:s})},branchGetter:async()=>{try{return(await eu(u))?.gitBranchName}catch(C){u.error({err:C},"Failed to get environment git metadata");return}},flagStoreFactory:async C=>{let v=ae();return new fr(v.config)},settingsFactory:async()=>{let C=ae();return{ai:{},browser:{},...C.config}},storageFactory:async C=>new ha(b,C),logger:u,devicePixelRatio:a,authorization:h,visualDiffScreenshotStorage:w,globalE2eStateManager:Fl})}var Wb="25mb";function QL(t,e,n){let r=Gb();r.use(VL()),r.use(jb.json({limit:Wb})),r.use(jb.urlencoded({extended:!1,limit:Wb}));let o=YL();if(o.use("/tests",$b),o.use("/modules",vb),o.use("/environments",Ib),o.use("/projects",Lb),o.use("/folders",jd),o.use("/settings",Nb),o.use("/identify",Mb),o.use("/entities",xb),r.use("/api",o),r.use((i,s,l)=>{i.path!=="/healthcheck"&&!i.path.startsWith("/assets")&&n.debug({url:i.url,path:i.path,query:i.query,method:i.method,body:i.body,headers:i.rawHeaders,client:i.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&n.error({url:i.url,method:i.method,statusCode:s.statusCode},"Request completed in error")}),l()}),r.use((i,s,l,c)=>{if(i instanceof Error&&i.message.includes("BadRequestError: request aborted")){l.status(400).send("Client disconnected");return}n.error({stack:i.stack,msg:i.message,err:i,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),S.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${i.message}
3962
- ${i.stack}`),l.status(500).send(`Internal Server Error: ${i.message}`)}),t){let i=Gb.static(t,{setHeaders:s=>{s.setHeader("Cache-Control","no-cache")},redirect:!1});r.use(i),r.use("*",(s,l)=>{l.sendFile(JL.join(t,"index.html"))})}let a=XL.createServer(r);return a.once("error",i=>{"code"in i&&i.code==="EADDRINUSE"?(qb(e),process.exit(1)):console.error("An unexpected server error occurred:",i.message)}),a}KL.setMaxListeners(50);process.on("warning",t=>{ut.warn({err:t},`Node warning received on desktop-server: ${t.message}`)});process.on("uncaughtException",t=>{ut.error({err:t},"Uncaught exception on desktop-server"),S.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${t.message}`)});process.on("unhandledRejection",(t,e)=>{ut.error({reason:`${t}`,stack:t?.stack},"Uncaught exception on desktop-server (promise rejection)"),S.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${t}`)});function qb(t){S.error(qL`Port ${t} is already in use by another process. Please close the other process and try again.
3959
+ `,messages:VL(o),tools:h}).pipeUIMessageStreamToResponse(e,{onError:y=>y instanceof Error?y.message:String(y)})}));var Vb=Cr;var xi=class{async prepareGoldenScreenshotForComparison(e,n,r){return await new sa(ie(),!1).prepareGoldenScreenshotForComparison(e,n,r)}};async function Xb(t){let{momenticServerUrl:e,apiKey:n,serverPort:r,staticDir:o,devicePixelRatio:a,alwaysSaveCache:i,noCache:s,initialProject:c}=t;e&&Pf(e),await Mf(n);let l=on(),d=el();Ai.identify({user_id:d,org_id:l});let u=t.logger??mt;u=u.child({orgId:l,userId:d}),u.debug({params:t},"Desktop server init and api key check done");let m=oO(o,r,u),p=`http://localhost:${r}`;S.info(`Desktop server is running at ${p}`),tl(c,v=>dt({configFilePath:v})),await new Promise(v=>{try{m.listen(r,()=>{u.info(`Desktop server is running at ${p}`),v()})}catch(R){R.message.includes("EADDRINUSE")?Jb(r):S.error(`An unexpected error occurred while starting the server: ${R.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:si(),apiKey:n,logger:u},f=async()=>{let v=ie();return new Yo(v.config.ai?.agentConfig,h)},b=async()=>new Xo(h,await f()),y=new Ze(h),E=new xi;Ab({baseServer:m,getOrgId:async()=>on(),generatorFactory:f,enricherFactory:b,cacheStorageFactory:async v=>{let R=ie(),C=await fr(u,y,R);return ta({orgId:v,client:y,gitMetadata:C,alwaysSaveCache:i,noCache:s})},branchGetter:async()=>{try{return(await Qd(u))?.gitBranchName}catch(v){u.error({err:v},"Failed to get environment git metadata");return}},flagStoreFactory:async v=>{let R=ie();return new hr(R.config)},settingsFactory:async()=>{let v=ie();return{ai:{},browser:{},...v.config}},storageFactory:async v=>new ha(y,v),logger:u,devicePixelRatio:a,authorization:h,visualDiffScreenshotStorage:E,globalE2eStateManager:kl})}var Yb="25mb";function oO(t,e,n){let r=Kb();r.use(QL()),r.use(qb.json({limit:Yb})),r.use(qb.urlencoded({extended:!1,limit:Yb}));let o=tO();if(o.use("/tests",Vb),o.use("/modules",xb),o.use("/environments",Mb),o.use("/projects",Nb),o.use("/folders",Hd),o.use("/settings",_b),o.use("/identify",Ob),o.use("/entities",Pb),r.use("/api",o),r.use((i,s,c)=>{i.path!=="/healthcheck"&&!i.path.startsWith("/assets")&&n.debug({url:i.url,path:i.path,query:i.query,method:i.method,body:i.body,headers:i.rawHeaders,client:i.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&n.error({url:i.url,method:i.method,statusCode:s.statusCode},"Request completed in error")}),c()}),r.use((i,s,c,l)=>{if(i instanceof Error&&i.message.includes("BadRequestError: request aborted")){c.status(400).send("Client disconnected");return}n.error({stack:i.stack,msg:i.message,err:i,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),S.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${i.message}
3960
+ ${i.stack}`),c.status(500).send(`Internal Server Error: ${i.message}`)}),t){let i=Kb.static(t,{setHeaders:s=>{s.setHeader("Cache-Control","no-cache")},redirect:!1});r.use(i),r.use("*",(s,c)=>{c.sendFile(rO.join(t,"index.html"))})}let a=nO.createServer(r);return a.once("error",i=>{"code"in i&&i.code==="EADDRINUSE"?(Jb(e),process.exit(1)):console.error("An unexpected server error occurred:",i.message)}),a}eO.setMaxListeners(50);process.on("warning",t=>{mt.warn({err:t},`Node warning received on desktop-server: ${t.message}`)});process.on("uncaughtException",t=>{mt.error({err:t},"Uncaught exception on desktop-server"),S.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${t.message}`)});process.on("unhandledRejection",(t,e)=>{mt.error({reason:`${t}`,stack:t?.stack},"Uncaught exception on desktop-server (promise rejection)"),S.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${t}`)});function Jb(t){S.error(ZL`Port ${t} is already in use by another process. Please close the other process and try again.
3963
3961
  Using Bash on MacOS or Linux:
3964
3962
  lsof -t -i :58888 | xargs kill -9
3965
3963
 
3966
3964
  Using Command Prompt on Windows:
3967
3965
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
3968
- `)}import rN from"events";import rc from"fs";import oN from"open";import{cpus as YT}from"os";import nc from"path";import{fileURLToPath as aN}from"url";import ZL from"diff-lines";import{gt as eO}from"semver";async function Kb({test:t,fragment:e,entities:n,client:r,logger:o,yes:a}){eO(e.schemaVersion,se)&&(S.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)),Uh(e.steps).forEach(g=>{n.modules[g]||(S.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!a&&!await bt("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=t.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!a&&!await bt("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=ao(t.fullFilePath,o,n),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${t.fullFilePath} is missing steps array`);let d,u;if(e.schemaVersion!==se){let{steps:g,newVersion:h}=await ri({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:S});d=h,u=Ge.array().parse(g)}else u=Ge.array().parse(e.steps);let{stepsToSave:m}=await He({stepLists:{steps:u}});m.beforeSteps=l.beforeSteps??void 0,m.afterSteps=l.afterSteps??void 0;let p=ZL(JSON.stringify(c,void 0,2),JSON.stringify(m,void 0,2),{n_surrounding:5});S.dimmed("=".repeat(30)),S.dimmed(p),S.dimmed("=".repeat(30)),S.dimmed(""),d&&S.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.`),!a&&!await bt("Do you want to apply this patch?")&&(S.dimmed("Cancelled."),process.exit(1)),Pt({relativeTestPath:t.relativePath,steps:m,schemaVersion:d??e.schemaVersion,project:n.project}),S.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Gt}from"crypto";import{z as Yb}from"zod";function xi(t){return Yb.string().uuid().safeParse(t).success}async function Bl({fix:t,project:e}){let n=te(e,S),r=Object.values(n.tests),o={},a={},i=new Set,s={},l=new Set,c=0;for(let u of r)try{let m=ao(u.fullFilePath,X,n),p=!1,g=!1;xi(u.id)||(S.error(`Test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),c++,g=!0,t&&(u.id=Gt(),p=!0)),n.duplicateEntities[u.id]&&(S.error(`Test '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),c++,g=!0,t&&(u.id=Gt(),p=!0));let h=m.steps;if(!h||h.length===0||!Array.isArray(h)){S.debug(`Test ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f=St.parse(m),y=await eo(f,h,S);y.steps=y.steps.map((b,w)=>{b.id||(S.error(`Step ${w} in test '${u.name}' (${u.relativePath}) does not have an ID`),g=!0,t&&(p=!0,b.id=Gt())),xi(b.id)||(S.error(`Step ${w} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${b.id}'`),c++,g=!0,t&&(p=!0,b.id=Gt()));let C=o[b.id]?.testId,v=o[b.id]?.testRelativePath;if(C?(c++,g=!0,C===u.id?S.error(`Multiple steps in the test '${u.name}' (${u.relativePath}) have the same ID '${b.id}'`):S.error(`Step ${w} in test '${u.name}' (${u.relativePath}) has the ID ${b.id} which is duplicated in ${v}`),t&&(p=!0,b.id=Gt())):o[b.id]={testId:u.id,testRelativePath:u.relativePath},b.type==="PRESET_ACTION"){let R=b.command.id;xi(R)||(S.error(`Command ${w} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${R}'`),c++,g=!0,t&&(p=!0,b.command.id=Gt()));let x=a[R]?.testId,M=a[R]?.testRelativePath;x?(c++,g=!0,x===u.id?S.error(`Multiple commands in the test '${u.name}' (${u.relativePath}) have the same ID '${R}'`):S.error(`Command ${w} in test '${u.name}' (${u.relativePath}) has the ID ${R} which is duplicated in test ${M}`),t&&(p=!0,b.command.id=Gt())):a[R]={testId:u.id,testRelativePath:u.relativePath}}return Me.parse(b)}),g&&S.dimmed("=".repeat(80)),p&&t&&(Pt({relativeTestPath:u.relativePath,steps:{beforeSteps:m.beforeSteps,steps:y.steps,afterSteps:m.afterSteps},schemaVersion:se,project:e}),i.add(u.fullFilePath))}catch(m){S.error({err:m},`Failed to parse test ${u.name} (${u.relativePath})`);continue}let d=Object.values(n.modules);for(let u of d)try{let m=!1,p=!1;xi(u.id)||(S.error(`Module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),c++,p=!0,t&&(u.id=Gt(),m=!0)),n.duplicateEntities[u.id]&&(S.error(`Module '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),c++,p=!0,t&&(u.id=Gt(),m=!0));let g=Wn(u.fullFilePath,S),h=g.steps;if(!h||h.length===0||!Array.isArray(h)){S.debug(`Module ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f,y;try{let w=await eo({id:g.moduleId,schemaVersion:g.schemaVersion},g.steps,S);f=w.steps,y=w.newVersion}catch(w){S.error({err:w},`Failed to migrate module ${u.name} (${u.relativePath})`);continue}let b=f.map((w,C)=>{if(Yb.string().uuid().safeParse(w.id)||(S.error(`Step ${C} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${w.id}'`),c++,p=!0,t&&(m=!0,w.id=Gt())),o[w.id]?.testId){let R=o[w.id]?.testRelativePath;c++,p=!0,S.error(`Step ${C} in module '${u.name}' (${u.relativePath}) has the ID ${w.id} which is duplicated in test ${R}`),t&&(m=!0,w.id=Gt())}if(w.type==="PRESET_ACTION"){let R=w.command.id;xi(R)||(S.error(`Command ${C} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${R}'`),c++,p=!0,t&&(m=!0,w.command.id=Gt()));let x=a[R],M=s[R];x||M?(c++,p=!0,M?.moduleId===u.id?S.error(`Multiple commands in module '${u.name}' (${u.relativePath}) have the same ID '${R}'`):x?S.error(`Command in module '${u.name}' (${u.relativePath}) has the ID ${R} which is duplicated in test ${x.testRelativePath}`):S.error(`Command ${C} in module '${u.name}' (${u.relativePath}) has the ID ${R} which is duplicated in module ${M.moduleRelativePath}`),t&&(m=!0,w.command.id=Gt())):s[R]={moduleId:u.id,moduleRelativePath:u.relativePath}}return Me.parse(w)});p&&S.dimmed("=".repeat(80)),m&&t&&($t({content:{...g,steps:b},schemaVersion:y,momenticFiles:n,project:e,forceSaveOnNoDiffs:!0}),l.add(u.fullFilePath))}catch(m){S.error({err:m},`Failed to parse module ${u.name} (${u.relativePath})`);continue}return{errors:c,modifiedTestFilePaths:i,modifiedModuleFilePaths:l}}async function Xb({fix:t,project:e}){let{errors:n,modifiedTestFilePaths:r,modifiedModuleFilePaths:o}=await Bl({fix:t,project:e});n>0?(S.error(`Found errors in ${n} steps`),t?(S.warn(`Modified the following test files:
3969
- ${[...r].map(a=>`${Ke}- ${a}`).join(`
3966
+ `)}import cN from"events";import ec from"fs";import dN from"open";import{cpus as ZT}from"os";import Zl from"path";import{fileURLToPath as uN}from"url";import aO from"diff-lines";import{gt as iO}from"semver";async function Qb({test:t,fragment:e,entities:n,client:r,logger:o,yes:a}){iO(e.schemaVersion,le)&&(S.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)),Fh(e.steps).forEach(g=>{n.modules[g]||(S.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!a&&!await Tt("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=t.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!a&&!await Tt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let c=ao(t.fullFilePath,o,n),l=c.steps;if(!Array.isArray(l))throw new Error(`Test ${t.fullFilePath} is missing steps array`);let d,u;if(e.schemaVersion!==le){let{steps:g,newVersion:h}=await oi({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:S});d=h,u=We.array().parse(g)}else u=We.array().parse(e.steps);let{stepsToSave:m}=await He({stepLists:{steps:u}});m.beforeSteps=c.beforeSteps??void 0,m.afterSteps=c.afterSteps??void 0;let p=aO(JSON.stringify(l,void 0,2),JSON.stringify(m,void 0,2),{n_surrounding:5});S.dimmed("=".repeat(30)),S.dimmed(p),S.dimmed("=".repeat(30)),S.dimmed(""),d&&S.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.`),!a&&!await Tt("Do you want to apply this patch?")&&(S.dimmed("Cancelled."),process.exit(1)),Pt({relativeTestPath:t.relativePath,steps:m,schemaVersion:d??e.schemaVersion,project:n.project}),S.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Gt}from"crypto";import{z as Zb}from"zod";function Ii(t){return Zb.string().uuid().safeParse(t).success}async function Dl({fix:t,project:e}){let n=ne(e,S),r=Object.values(n.tests),o={},a={},i=new Set,s={},c=new Set,l=0;for(let u of r)try{let m=ao(u.fullFilePath,X,n),p=!1,g=!1;Ii(u.id)||(S.error(`Test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),l++,g=!0,t&&(u.id=Gt(),p=!0)),n.duplicateEntities[u.id]&&(S.error(`Test '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),l++,g=!0,t&&(u.id=Gt(),p=!0));let h=m.steps;if(!h||h.length===0||!Array.isArray(h)){S.debug(`Test ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f=yt.parse(m),b=await eo(f,h,S);b.steps=b.steps.map((y,E)=>{y.id||(S.error(`Step ${E} in test '${u.name}' (${u.relativePath}) does not have an ID`),g=!0,t&&(p=!0,y.id=Gt())),Ii(y.id)||(S.error(`Step ${E} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${y.id}'`),l++,g=!0,t&&(p=!0,y.id=Gt()));let v=o[y.id]?.testId,R=o[y.id]?.testRelativePath;if(v?(l++,g=!0,v===u.id?S.error(`Multiple steps in the test '${u.name}' (${u.relativePath}) have the same ID '${y.id}'`):S.error(`Step ${E} in test '${u.name}' (${u.relativePath}) has the ID ${y.id} which is duplicated in ${R}`),t&&(p=!0,y.id=Gt())):o[y.id]={testId:u.id,testRelativePath:u.relativePath},y.type==="PRESET_ACTION"){let C=y.command.id;Ii(C)||(S.error(`Command ${E} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${C}'`),l++,g=!0,t&&(p=!0,y.command.id=Gt()));let x=a[C]?.testId,I=a[C]?.testRelativePath;x?(l++,g=!0,x===u.id?S.error(`Multiple commands in the test '${u.name}' (${u.relativePath}) have the same ID '${C}'`):S.error(`Command ${E} in test '${u.name}' (${u.relativePath}) has the ID ${C} which is duplicated in test ${I}`),t&&(p=!0,y.command.id=Gt())):a[C]={testId:u.id,testRelativePath:u.relativePath}}return Ie.parse(y)}),g&&S.dimmed("=".repeat(80)),p&&t&&(Pt({relativeTestPath:u.relativePath,steps:{beforeSteps:m.beforeSteps,steps:b.steps,afterSteps:m.afterSteps},schemaVersion:le,project:e}),i.add(u.fullFilePath))}catch(m){S.error({err:m},`Failed to parse test ${u.name} (${u.relativePath})`);continue}let d=Object.values(n.modules);for(let u of d)try{let m=!1,p=!1;Ii(u.id)||(S.error(`Module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),l++,p=!0,t&&(u.id=Gt(),m=!0)),n.duplicateEntities[u.id]&&(S.error(`Module '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),l++,p=!0,t&&(u.id=Gt(),m=!0));let g=Gn(u.fullFilePath,S),h=g.steps;if(!h||h.length===0||!Array.isArray(h)){S.debug(`Module ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f,b;try{let E=await eo({id:g.moduleId,schemaVersion:g.schemaVersion},g.steps,S);f=E.steps,b=E.newVersion}catch(E){S.error({err:E},`Failed to migrate module ${u.name} (${u.relativePath})`);continue}let y=f.map((E,v)=>{if(Zb.string().uuid().safeParse(E.id)||(S.error(`Step ${v} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${E.id}'`),l++,p=!0,t&&(m=!0,E.id=Gt())),o[E.id]?.testId){let C=o[E.id]?.testRelativePath;l++,p=!0,S.error(`Step ${v} in module '${u.name}' (${u.relativePath}) has the ID ${E.id} which is duplicated in test ${C}`),t&&(m=!0,E.id=Gt())}if(E.type==="PRESET_ACTION"){let C=E.command.id;Ii(C)||(S.error(`Command ${v} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${C}'`),l++,p=!0,t&&(m=!0,E.command.id=Gt()));let x=a[C],I=s[C];x||I?(l++,p=!0,I?.moduleId===u.id?S.error(`Multiple commands in module '${u.name}' (${u.relativePath}) have the same ID '${C}'`):x?S.error(`Command in module '${u.name}' (${u.relativePath}) has the ID ${C} which is duplicated in test ${x.testRelativePath}`):S.error(`Command ${v} in module '${u.name}' (${u.relativePath}) has the ID ${C} which is duplicated in module ${I.moduleRelativePath}`),t&&(m=!0,E.command.id=Gt())):s[C]={moduleId:u.id,moduleRelativePath:u.relativePath}}return Ie.parse(E)});p&&S.dimmed("=".repeat(80)),m&&t&&($t({content:{...g,steps:y},schemaVersion:b,momenticFiles:n,project:e,forceSaveOnNoDiffs:!0}),c.add(u.fullFilePath))}catch(m){S.error({err:m},`Failed to parse module ${u.name} (${u.relativePath})`);continue}return{errors:l,modifiedTestFilePaths:i,modifiedModuleFilePaths:c}}async function eT({fix:t,project:e}){let{errors:n,modifiedTestFilePaths:r,modifiedModuleFilePaths:o}=await Dl({fix:t,project:e});n>0?(S.error(`Found errors in ${n} steps`),t?(S.warn(`Modified the following test files:
3967
+ ${[...r].map(a=>`${Ye}- ${a}`).join(`
3970
3968
  `)}`),o.size>0&&S.warn(`Modified the following module files:
3971
- ${[...o].map(a=>`${Ke}- ${a}`).join(`
3972
- `)}`)):S.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(S.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function Jb({project:t}){let e=te(t,S),n=Object.values(e.tests),r=await rl(e,X),o={},a={},i=new Set,s=new Set;for(let c of n)o[c.name]?a[c.name]?a[c.name].push(c.fullFilePath):a[c.name]=[o[c.name],c.fullFilePath]:o[c.name]=c.fullFilePath;for(let c of r)s.has(c.name)&&i.add(c.name),s.add(c.name);if(Object.entries(a).length>0||i.size>0){for(let[c,d]of Object.entries(a))for(let u of d)S.error(`Test Name ${c} is duplicated in ${u}`);for(let c of i)S.error(`Module name ${c} is duplicated in your project`);process.exit(1)}S.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as tO}from"lodash-es";async function Qb({client:t,skipPrompts:e,project:n}){let r=await t.getAllEnvironments(),o=tO(n.config);o.environments||(o.environments=[]);for(let a of r){let i=o.environments?.find(s=>s.name===a.name);if(i)!e&&!await bt(`Environment ${a.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),i.baseUrl=a.variables[at],delete a.variables[at],i.envVariables=a.variables;else{let s=a.variables[at];delete a.variables[at],o.environments.push({name:a.name,baseUrl:s,envVariables:a.variables})}}aa(o,n.configFilePath),S.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Zb}from"crypto";import eT from"fs";async function Wu({testsToFetch:t,client:e,all:n,yes:r}){let{tests:o,modules:a}=await e.getTestYAMLExport({paths:t,all:n}),i=0;for(let[l,c]of Object.entries(o)){let d=tT(l,pe.TEST);!r&&!await Ed(d)||(i+=1,eT.writeFileSync(d,c,"utf-8"),X.info({checksum:Zb("md5").update(c).digest("hex")},`Wrote '${d}'`))}let s=0;for(let[l,c]of Object.entries(a)){let d=tT(l,pe.MODULE);!r&&!await Ed(d)||(s+=1,eT.writeFileSync(d,c,"utf-8"),X.info({checksum:Zb("md5").update(c).digest("hex")},`Wrote '${d}'`))}i===0?S.success("Pulled 0 tests."):S.success(`Pulled ${i} test${i>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function tT(t,e){switch(e){case pe.TEST:return`${ve(t)}.${st.TEST}`;case pe.MODULE:return`${ve(t)}.${st.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function nT(t){let{project:e,client:n,skipPrompts:r}=t;S.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),S.info("Importing environments from Momentic Cloud."),S.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await bt("Are you sure you want to proceed?",!0)||(S.info("Aborting..."),process.exit(1)),await Qb({client:n,project:e,skipPrompts:r}),S.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),S.info("Importing tests and modules from Momentic Cloud."),await Wu({testsToFetch:[],client:n,all:!0,yes:r}),S.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}async function rT(t){let{client:e,skipPrompts:n,paths:r}=t;await Wu({testsToFetch:r,client:e,all:void 0,yes:n}),S.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import{Argument as yo,InvalidArgumentError as Ii,Option as Ie}from"@commander-js/extra-typings";import{validateHeaderValue as nO}from"http";import{z as oT}from"zod";var zl=58888;function Ar(t){let e=parseInt(t,10);if(isNaN(e))throw new Ii("Not a number.");return e}function Hl(t){if(t===void 0)return;let e={};for(let n of t){let r=n.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${n}`);let o=n.slice(0,r),a=n.slice(r+1);nO(o,a),e[o]=a}return e}var hn=new Ie("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(t=>{if(!t)throw new Ii("API key is required.");return t}).makeOptionMandatory(),fn=new Ie("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(t=>{try{return oT.string().url().parse(t),t}catch{throw new Ii("Not a valid URL.")}}),xr=new Ie("-y, --yes","Skip all confirmation prompts.").env("CI"),Vu=new Ie("-w, --wait","Wait for tests to finish running before exiting."),qu=new Ie("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(Ar),$l=new Ie("--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."),aT=new Ie("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(as)),iT=new Ie("--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"),Ku=new Ie("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),sT=new Ie("--upload-results","Upload test results to Momentic Cloud.").default(!1),Yu=new Ie("--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."),Xu=new Ie("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Ju=new Ie("--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(Ar),Qu=new Ie("--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."),jl=new Ie("--env <env>","Name of the environment to use when running tests."),Gl=new Ie("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(t=>{try{return oT.string().url().parse(t),t}catch{throw new Ii("Not a valid URL.")}}),lT=new Ie("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(t=>{let e=Ar(t);if(e<1)throw new Ii("Shard index must be greater than 0.");return e}),cT=new Ie("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Ar),Wt=new Ie("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),fa=new Ie("-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."),dT=new Ie("--fix","Attempt to fix any issues found."),Zu=new Ie("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),em=new Ie("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),uT=new Ie("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),mT=new Ie("--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}),pT=new Ie("--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}),gT=new yo("<tests...>","One or more test paths to queue on Momentic Cloud."),hT=new yo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),tm=new yo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),fT=new yo("<suites...>","One or more suite paths that exist on Momentic Cloud."),ST=new yo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),yT=new yo("<results>","Path to the results archive.").argRequired(),nm=new Ie("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),rm=new yo("<test>","Name of the test to quarantine.").argOptional();async function bT(t){let e=te(t,S),n=Object.values(e.tests);for(let r of n)try{let o=ao(r.fullFilePath,S,e),a=o.steps;if(!a||a.length===0||!Array.isArray(a)){S.debug(`Test ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let i=St.parse(o),s=await eo(i,a,S);S.dimmed(`Updating ${r.relativePath}`),Pt({relativeTestPath:r.relativePath,steps:{beforeSteps:o.beforeSteps,steps:s.steps,afterSteps:o.afterSteps},schemaVersion:se,project:t,forceSaveOnNoDiffs:!0})}catch(o){S.error({err:o},`Failed to read or migrate test ${r.name} (${r.relativePath}), continuing...`)}for(let r of Object.values(e.modules)){S.dimmed(`Updating ${r.relativePath}`);try{let o=Wn(r.fullFilePath,S),a=o.steps;if(!a||a.length===0||!Array.isArray(a)){S.debug(`Module ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let i=await eo({id:o.moduleId,schemaVersion:o.schemaVersion},a,S);$t({content:{...o,steps:i.steps},schemaVersion:se,momenticFiles:e,project:t,forceSaveOnNoDiffs:!0})}catch(o){S.error({err:o},`Failed to read or migrate module ${r.name} (${r.relativePath}), continuing...`)}}}import{spawnSync as aO}from"child_process";import{PostHog as oO}from"posthog-node";async function TT(t,e){let n,r=0,o=3,a,i;for(;r<o;)try{let s=await H(t.getAllFlagsAndPayloads(e),{milliseconds:5e3});a=s.featureFlags||{},i=s.featureFlagPayloads||{};break}catch(s){n=s,r++,await new Promise(l=>setTimeout(l,100*r))}if(a&&i)return{flags:a,payloads:i};throw n}var Wl=class t extends Wa{constructor(n,r,o,a){super(o,a);this.client=n;this.orgId=r}static async init(n){let r=new oO("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:a}=await TT(r,n);return new t(r,n,o,a)}async refresh(){let{flags:n,payloads:r}=await TT(this.client,this.orgId);this.flags=n,this.payloads=r}};function iO(){try{let e=aO("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();S.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(t){let e=t instanceof Error?t.message:String(t);S.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
3973
- ${e}`)}}async function wT({project:t,orgId:e,apiClient:n}){S.info("Pulling browser and AI configuration options from Cloud");let r=await Wl.init(e);t.config.browser={autoExpandIframes:r.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:r.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:r.isBooleanFlagEnabled("global_locator_redirect"),visualActions:r.isBooleanFlagEnabled("visual_actions"),...t.config.browser},t.config.advanced={fakerConstantSeed:r.isBooleanFlagEnabled("faker_constant_seed"),...t.config.advanced},t.config.ai={aiPageFiltering:r.isBooleanFlagEnabled("rag_v2"),agentConfig:await n.getAgentConfig(),...t.config.ai},S.info(`Updated ${t.configFilePath} to include V2 browser and AI configuration options`),S.info("Determining main Git branch"),t.config.gitMainBranch=iO(),aa(t.config,t.configFilePath),S.success("Migration complete!")}import{input as sO,search as lO}from"@inquirer/prompts";import cO from"fuse.js";async function Vl({prompt:t,inputtedTest:e,testOptions:n}){if(e){let i=n.find(s=>s.name===e);if(!i)S.error(`${e} is not a valid test option.`);else return{name:i.name,id:i.value}}let r=new cO(n,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await lO({message:t,source:async i=>!i||i.length===0?n:r.search({name:i}).map(l=>l.item)}),a=n.find(i=>i.value===o);return{name:a.name,id:a.value}}async function ql({prompt:t,inputtedReason:e}){return e||sO({message:t})}async function ET({test:t,reason:e,apiClient:n,project:r,logger:o,identity:a}){let i=te(r,S).tests,s=Object.values(i).map(d=>({value:d.id,name:d.name})),l=await Vl({prompt:"Select a test to quarantine.",inputtedTest:t,testOptions:s}),c=await ql({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await n.quarantineTest(l,c,a),S.success(`Test ${l.name} has been successfully quarantined. Navigate to ${n.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${l.name}'.`)}async function RT({test:t,reason:e,apiClient:n,project:r,logger:o,identity:a}){let i=te(r,S).tests,s=Object.values(i).map(p=>({value:p.id,name:p.name})),l=(await n.getQuarantinedTests()).quarantined,c=new Set(l.map(p=>p.testId)),d=s.filter(p=>c.has(p.value)),u=await Vl({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:d}),m=await ql({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await n.unquarantineTest(u,m,a),S.success(`Test ${u.name} has been successfully removed from quarantine.`)}function CT(t){return t?ve(t):"Unknown suite"}async function vT({client:t,orgId:e,suitePaths:n,wait:r,waitTimeout:o,...a}){let{suiteRunIds:i,runGroupIds:s}=await t.queueSuiteRuns({paths:n,...a});X.info({orgId:e,suiteRunIds:i,runGroupIds:s,suitePaths:n},"Queued suites remotely"),S.dimmed(`Queued ${n.length} suites.`),r||process.exit(0);let l=Date.now();S.dimmed(`Waiting for ${n.length} suites to finish. You can view results upon completion at:`);for(let f of s)S.dimmed(`${Ke}- ${t.getAppUrl()}/run-groups/${f}`);let c=new Set,d=[],u=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(b=>b.status==="FAILED"&&(b.failureReason||b.finishedAt&&Date.now()-b.finishedAt.getTime()>30*1e3)||b.status==="PASSED"||b.status==="CANCELLED"),m=await Ms({name:"suites",getResults:async()=>{let f=s.filter(w=>!d.some(C=>C.id===w)),y=await t.bulkGetRunGroupStatus(f),b=[];for(let w of y)u(w)?d.push(w):b.push(w);return[...d,...b]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(y=>{y.status==="RUNNING"&&(c.has(y.id)||(c.add(y.id),S.log(`${c.size}/${s.length} ${CT(y.suite?.name)}`)))}),f.every(u))}),p=t.getAppUrl(),h=Vo({results:m,startTime:l,onFailed:f=>{let y=CT(f.suite?.name),b=f.runs.filter(C=>C.status==="FAILED").length,w=f.runs.length;S.error(`${y} (${b}/${w} tests failed):`);for(let C of f.runs)if(C.status==="FAILED"){let v=C.testName||C.test?.name;S.error(` ${v?ve(v):"Unknown test"} (${p}/runs/${C.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?ve(f.suite.name):"Unknown suite name"} (${p}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function AT({tests:t,client:e,orgId:n,...r}){!r.yes&&!await bt(`This command will queue ${t.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:a}=await e.queueTests({testPaths:t,...r});if(X.info({queuedTests:o,runIds:a,orgId:n},"Queued tests remotely"),S.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),r.wait||process.exit(0),!a.length)return;S.dimmed(`Waiting for ${o.length} tests to complete.`);let i=new Set,s=[],l=p=>p.status==="FAILED"&&p.failureReason||p.status==="PASSED"||p.status==="CANCELLED",c=e.getAppUrl(),d=Date.now(),u=await Ms({name:"runs",getResults:async()=>{let p=a.filter(f=>!s.some(y=>y.id===f)),g=await e.bulkGetRunStatus(p),h=[];for(let f of g)l(f)?s.push(f):h.push(f);return[...s,...h]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:p=>(p.forEach(g=>{if(g.status==="RUNNING"&&!i.has(g.id)){i.add(g.id);let h=g.testName||g.test?.name;h&&S.log(`${i.size}/${o.length} ${ve(h)}`)}}),p.every(l))}),m=Vo({results:u,startTime:d,onFailed:p=>{let g=p.testName||p.test?.name;Ls(p,g?ve(g):"Unknown test")},getDisplayLine:p=>{let g=p.testName||p.test?.name,h=` ${g?ve(g):"Unknown test"}`;return p.id&&(h+=` (${c}/runs/${p.id})`),h},entity:"test"});process.exit(m.failed>0?1:0)}import{randomUUID as YO}from"crypto";import XO from"fs";import{existsSync as RO,mkdirSync as CO,statSync as vO}from"fs";import{randomUUID as xT}from"crypto";import om from"fs";import{hostname as dO}from"os";import am from"path";async function Kl(t,e,n,r){if(r){let o=await e.getScreenshot(t,r);if(o){let a=`${r}-screenshot.jpeg`,i=am.join(n,a);return om.writeFileSync(i,o),a}}}async function uO(t,e,n,r){let o=r.runId??xT(),a={uuid:o,historyId:o,testCaseId:r.test.id,fullName:r.test.name,name:ve(r.test.name),status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"skipped":"failed",start:r.lastAttemptStartedAt.getTime(),stop:r.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:n.suiteName},{name:"host",value:dO()},{name:"platform",value:"momentic"},{name:"attempts",value:r.attempts.toString()}],steps:[]};r.runId&&a.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${r.runId}`});for(let[s,l]of Object.entries(r.parameters))l!=null&&a.parameters.push({name:s,value:JSON.stringify(l)});r.results&&await mO(t,e,n.folder,a.steps,r.results);let i=`${o}-result.json`;om.writeFileSync(am.join(n.folder,i),JSON.stringify(a,void 0,2))}async function Sa(t,e,n,r){let o={name:hr(r),start:r.startedAt.getTime(),stop:r.finishedAt.getTime(),status:r.status==="SUCCESS"?"passed":r.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};r.beforeUrl&&o.labels?.push({name:"URL before step",value:r.beforeUrl}),r.afterUrl&&o.labels?.push({name:"URL after step",value:r.afterUrl});let a=await Kl(t,e,n,r.beforeSnapshot);a&&o.attachments.push({name:"Screenshot before step",source:a,type:"image/jpeg"});let i=await Kl(t,e,n,r.afterSnapshot);if(i&&o.attachments.push({name:"Screenshot after step",source:i,type:"image/jpeg"}),r.message&&(o.statusDetails={message:r.message}),r.data){let s=`${xT()}-attachment.json`,l=am.join(n,s);om.writeFileSync(l,JSON.stringify(r.data,null,2)),o.attachments.push({name:"Step output data",source:s,type:"text/plain"})}return o}async function mO(t,e,n,r,o){for(let a of o)switch(a.type){case"PRESET_ACTION":{r.push(await Sa(t,e,n,a));break}case"CONDITIONAL":{let i=await Sa(t,e,n,a);i.steps=[],a.assertionResult&&i.steps.push(await Sa(t,e,n,a.assertionResult)),i.steps.push(...await Promise.all(a.results.map(s=>Sa(t,e,n,s)))),r.push(i);break}case"AI_ACTION":case"SECTION":case"MODULE":{let i=await Sa(t,e,n,a);if(i.steps=await Promise.all(a.results.map(s=>Sa(t,e,n,s))),a.type==="MODULE"&&a.inputs){i.parameters=[];for(let[s,l]of Object.entries(a.inputs))i.parameters.push({name:s,value:l})}r.push(i)}}}async function IT(t,e,n,r){for(let o of r.runs)await uO(t,e,{folder:n,suiteName:r.suiteName},o)}import pO from"junit-report-builder";import Yl from"path";function gO(t,e){if(e.name(t.test.name).className(t.test.name).file(Yl.relative(".",t.filePath)).property("id",t.test.id).property("dd_tags[id]",t.test.id),t.test.labels&&(e.property("labels",t.test.labels.join(",")),t.test.labels.forEach(n=>{e.property("dd_tags[label]",n)})),t.baseUrl&&(e.property("base_url",t.baseUrl),e.property("dd_tags[base_url]",t.baseUrl)),t.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${t.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${t.runId}`)),t.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason))),t.beforeResults?.some(n=>n.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),t.results?.some(n=>n.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),t.afterResults?.some(n=>n.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),t.status==="FAILED"){if(t.failureReason){let n=Ki[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||No[t.failureReason];t.runId&&(r+=` Visit https://app.momentic.ai/runs/${t.runId} for more details.`),e.failure(r,n)}t.failureDetails?.errorStack&&e.stacktrace(t.failureDetails.errorStack)}else t.status==="CANCELLED"&&e.skipped();return e.time((t.finishedAt.getTime()-t.lastAttemptStartedAt.getTime())/1e3).property("started_at",t.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",t.lastAttemptStartedAt.toISOString()).property("finished_at",t.finishedAt.toISOString()).property("dd_tags[finished_at]",t.finishedAt.toISOString()),e.property("attempts",t.attempts.toString()).property("dd_tags[attempts]",t.attempts.toString()),t.parameters.envName&&(e.property("environment",t.parameters.envName),e.property("dd_tags[environment]",t.parameters.envName)),t.parameters.urlOverride&&e.property("url_override",t.parameters.urlOverride),e}function hO(t,{suiteId:e,suiteName:n,startedAt:r,finishedAt:o,runs:a,testsToSkip:i,quarantinedTestsToSkip:s,quarantinedTestReasons:l}){let c=t.testSuite().name(n);e&&c.property("id",e),c.timestamp(r).property("startedAt",r.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-r.getTime())/1e3);for(let d of a){let u=c.testCase();gO(d,u)}for(let d of i){let u=c.testCase();u.name(d.name).className(d.name).file(Yl.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(m=>{u.property("dd_tags[label]",m)})),u.skipped()}for(let d of s){let u=c.testCase();u.name(d.name).className(d.name).file(Yl.relative(".",d.relativeFilePath)).property("id",d.id).property("quarantined","true");let m=l[d.id];m&&u.property("quarantinedReason",m),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(p=>{u.property("dd_tags[label]",p)})),u.skipped()}return c}function PT(t,e){let n=pO.newBuilder();hO(n,e),n.writeTo(Yl.join(t,`${e.suiteName}.xml`))}import fO from"fs";import SO from"path";function MT(t){return{title:hr(t),duration:t.finishedAt.getTime()-t.startedAt.getTime(),error:t.status==="FAILED"?{value:t.failureReason}:void 0,steps:t.results&&t.type!=="PRESET_ACTION"?t.results.map(MT):[]}}async function yO(t,e,n,r){if(r.results?.length){let o=await Kl(t,e,n,r.results[r.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function bO(t,e,n,r){return{status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"interrupted":"failed",duration:r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime(),error:r.status==="FAILED"&&r.failureReason?{value:r.failureDetails?.classification?.reason||r.failureReason,message:r.failureDetails?.classification?.summary||No[r.failureReason]}:void 0,retry:r.attempts-1,steps:r.results?.map(MT)||[],startTime:r.lastAttemptStartedAt.toISOString(),attachments:await yO(t,e,n,r)}}async function TO(t,e,n,r){return{expectedStatus:"passed",status:r.status==="PASSED"?"expected":"unexpected",results:[await bO(t,e,n,r)]}}async function wO(t,e,n,r){return{tags:[],title:r.test.name,ok:r.status==="PASSED",tests:[await TO(t,e,n,r)],id:r.runId,file:r.filePath}}function im(t,e){return t.reduce((n,r)=>e(r)?n+1:n,0)}async function EO(t,e,n,r){return{suites:[{title:r.suiteName,file:r.projectConfigPath,specs:await Promise.all(r.runs.map(o=>wO(t,e,n,o)))}],errors:[],stats:{startTime:r.startedAt.toISOString(),duration:r.finishedAt.getTime()-r.startedAt.getTime(),expected:im(r.runs,o=>o.status==="PASSED"),unexpected:im(r.runs,o=>o.status!=="PASSED"),flaky:im(r.runs,o=>!!o.isFlake),skipped:0}}}async function LT(t,e,n,r){let o=await EO(t,e,n,r);fO.writeFileSync(SO.join(n,`${r.suiteName}.json`),JSON.stringify(o,null,2))}async function OT(t,e,n,r,o){switch(RO(o)?vO(o).isDirectory()||(S.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(S.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),CO(o,{recursive:!0})),n){case"junit":PT(o,r);return;case"allure":case"allure-json":await IT(t,e,o,r);return;case"playwright-json":await LT(t,e,o,r);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}import JO from"wait-on";import{execSync as AO}from"child_process";import{platform as xO}from"os";function sm(){return NT()?(S.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),S.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.
3969
+ ${[...o].map(a=>`${Ye}- ${a}`).join(`
3970
+ `)}`)):S.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(S.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function tT({project:t}){let e=ne(t,S),n=Object.values(e.tests),r=await rl(e,X),o={},a={},i=new Set,s=new Set;for(let l of n)o[l.name]?a[l.name]?a[l.name].push(l.fullFilePath):a[l.name]=[o[l.name],l.fullFilePath]:o[l.name]=l.fullFilePath;for(let l of r)s.has(l.name)&&i.add(l.name),s.add(l.name);if(Object.entries(a).length>0||i.size>0){for(let[l,d]of Object.entries(a))for(let u of d)S.error(`Test Name ${l} is duplicated in ${u}`);for(let l of i)S.error(`Module name ${l} is duplicated in your project`);process.exit(1)}S.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as sO}from"lodash-es";async function nT({client:t,skipPrompts:e,project:n}){let r=await t.getAllEnvironments(),o=sO(n.config);o.environments||(o.environments=[]);for(let a of r){let i=o.environments?.find(s=>s.name===a.name);if(i)!e&&!await Tt(`Environment ${a.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),i.baseUrl=a.variables[it],delete a.variables[it],i.envVariables=a.variables;else{let s=a.variables[it];delete a.variables[it],o.environments.push({name:a.name,baseUrl:s,envVariables:a.variables})}}aa(o,n.configFilePath),S.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as rT}from"crypto";import oT from"fs";async function Gu({testsToFetch:t,client:e,all:n,yes:r}){let{tests:o,modules:a}=await e.getTestYAMLExport({paths:t,all:n}),i=0;for(let[c,l]of Object.entries(o)){let d=aT(c,ge.TEST);!r&&!await Td(d)||(i+=1,oT.writeFileSync(d,l,"utf-8"),X.info({checksum:rT("md5").update(l).digest("hex")},`Wrote '${d}'`))}let s=0;for(let[c,l]of Object.entries(a)){let d=aT(c,ge.MODULE);!r&&!await Td(d)||(s+=1,oT.writeFileSync(d,l,"utf-8"),X.info({checksum:rT("md5").update(l).digest("hex")},`Wrote '${d}'`))}i===0?S.success("Pulled 0 tests."):S.success(`Pulled ${i} test${i>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function aT(t,e){switch(e){case ge.TEST:return`${Ce(t)}.${lt.TEST}`;case ge.MODULE:return`${Ce(t)}.${lt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function iT(t){let{project:e,client:n,skipPrompts:r}=t;S.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),S.info("Importing environments from Momentic Cloud."),S.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await Tt("Are you sure you want to proceed?",!0)||(S.info("Aborting..."),process.exit(1)),await nT({client:n,project:e,skipPrompts:r}),S.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),S.info("Importing tests and modules from Momentic Cloud."),await Gu({testsToFetch:[],client:n,all:!0,yes:r}),S.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}async function sT(t){let{client:e,skipPrompts:n,paths:r}=t;await Gu({testsToFetch:r,client:e,all:void 0,yes:n}),S.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import{Argument as yo,InvalidArgumentError as Pi,Option as xe}from"@commander-js/extra-typings";import{validateHeaderValue as lO}from"http";import{z as lT}from"zod";var Fl=58888;function vr(t){let e=parseInt(t,10);if(isNaN(e))throw new Pi("Not a number.");return e}function Ul(t){if(t===void 0)return;let e={};for(let n of t){let r=n.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${n}`);let o=n.slice(0,r),a=n.slice(r+1);lO(o,a),e[o]=a}return e}var fn=new xe("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(t=>{if(!t)throw new Pi("API key is required.");return t}).makeOptionMandatory(),Sn=new xe("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(t=>{try{return lT.string().url().parse(t),t}catch{throw new Pi("Not a valid URL.")}}),Ar=new xe("-y, --yes","Skip all confirmation prompts.").env("CI"),Wu=new xe("-w, --wait","Wait for tests to finish running before exiting."),Vu=new xe("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(vr),Bl=new xe("--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."),cT=new xe("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(as)),dT=new xe("--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"),qu=new xe("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),uT=new xe("--upload-results","Upload test results to Momentic Cloud.").default(!1),Ku=new xe("--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."),Yu=new xe("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Xu=new xe("--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(vr),Ju=new xe("--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."),zl=new xe("--env <env>","Name of the environment to use when running tests."),Hl=new xe("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(t=>{try{return lT.string().url().parse(t),t}catch{throw new Pi("Not a valid URL.")}}),mT=new xe("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(t=>{let e=vr(t);if(e<1)throw new Pi("Shard index must be greater than 0.");return e}),pT=new xe("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(vr),Wt=new xe("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),fa=new xe("-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."),gT=new xe("--fix","Attempt to fix any issues found."),Qu=new xe("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),Zu=new xe("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),hT=new xe("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),fT=new xe("--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}),ST=new xe("--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}),yT=new yo("<tests...>","One or more test paths to queue on Momentic Cloud."),bT=new yo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),em=new yo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),TT=new yo("<suites...>","One or more suite paths that exist on Momentic Cloud."),wT=new yo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),ET=new yo("<results>","Path to the results archive.").argRequired(),tm=new xe("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),nm=new yo("<test>","Name of the test to quarantine.").argOptional();async function RT(t){let e=ne(t,S),n=Object.values(e.tests);for(let r of n)try{let o=ao(r.fullFilePath,S,e),a=o.steps;if(!a||a.length===0||!Array.isArray(a)){S.debug(`Test ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let i=yt.parse(o),s=await eo(i,a,S);S.dimmed(`Updating ${r.relativePath}`),Pt({relativeTestPath:r.relativePath,steps:{beforeSteps:o.beforeSteps,steps:s.steps,afterSteps:o.afterSteps},schemaVersion:le,project:t,forceSaveOnNoDiffs:!0})}catch(o){S.error({err:o},`Failed to read or migrate test ${r.name} (${r.relativePath}), continuing...`)}for(let r of Object.values(e.modules)){S.dimmed(`Updating ${r.relativePath}`);try{let o=Gn(r.fullFilePath,S),a=o.steps;if(!a||a.length===0||!Array.isArray(a)){S.debug(`Module ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let i=await eo({id:o.moduleId,schemaVersion:o.schemaVersion},a,S);$t({content:{...o,steps:i.steps},schemaVersion:le,momenticFiles:e,project:t,forceSaveOnNoDiffs:!0})}catch(o){S.error({err:o},`Failed to read or migrate module ${r.name} (${r.relativePath}), continuing...`)}}}import{spawnSync as uO}from"child_process";import{PostHog as dO}from"posthog-node";async function CT(t,e){let n,r=0,o=3,a,i;for(;r<o;)try{let s=await j(t.getAllFlagsAndPayloads(e),{milliseconds:5e3});a=s.featureFlags||{},i=s.featureFlagPayloads||{};break}catch(s){n=s,r++,await new Promise(c=>setTimeout(c,100*r))}if(a&&i)return{flags:a,payloads:i};throw n}var $l=class t extends Va{constructor(n,r,o,a){super(o,a);this.client=n;this.orgId=r}static async init(n){let r=new dO("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:a}=await CT(r,n);return new t(r,n,o,a)}async refresh(){let{flags:n,payloads:r}=await CT(this.client,this.orgId);this.flags=n,this.payloads=r}};function mO(){try{let e=uO("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();S.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(t){let e=t instanceof Error?t.message:String(t);S.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
3971
+ ${e}`)}}async function vT({project:t,orgId:e,apiClient:n}){S.info("Pulling browser and AI configuration options from Cloud");let r=await $l.init(e);t.config.browser={autoExpandIframes:r.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:r.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:r.isBooleanFlagEnabled("global_locator_redirect"),visualActions:r.isBooleanFlagEnabled("visual_actions"),...t.config.browser},t.config.advanced={fakerConstantSeed:r.isBooleanFlagEnabled("faker_constant_seed"),...t.config.advanced},t.config.ai={aiPageFiltering:r.isBooleanFlagEnabled("rag_v2"),agentConfig:await n.getAgentConfig(),...t.config.ai},S.info(`Updated ${t.configFilePath} to include V2 browser and AI configuration options`),S.info("Determining main Git branch"),t.config.gitMainBranch=mO(),aa(t.config,t.configFilePath),S.success("Migration complete!")}import{input as pO,search as gO}from"@inquirer/prompts";import hO from"fuse.js";async function jl({prompt:t,inputtedTest:e,testOptions:n}){if(e){let i=n.find(s=>s.name===e);if(!i)S.error(`${e} is not a valid test option.`);else return{name:i.name,id:i.value}}let r=new hO(n,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await gO({message:t,source:async i=>!i||i.length===0?n:r.search({name:i}).map(c=>c.item)}),a=n.find(i=>i.value===o);return{name:a.name,id:a.value}}async function Gl({prompt:t,inputtedReason:e}){return e||pO({message:t})}async function AT({test:t,reason:e,apiClient:n,project:r,logger:o,identity:a}){let i=ne(r,S).tests,s=Object.values(i).map(d=>({value:d.id,name:d.name})),c=await jl({prompt:"Select a test to quarantine.",inputtedTest:t,testOptions:s}),l=await Gl({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await n.quarantineTest(c,l,a),S.success(`Test ${c.name} has been successfully quarantined. Navigate to ${n.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${c.name}'.`)}async function xT({test:t,reason:e,apiClient:n,project:r,logger:o,identity:a}){let i=ne(r,S).tests,s=Object.values(i).map(p=>({value:p.id,name:p.name})),c=(await n.getQuarantinedTests()).quarantined,l=new Set(c.map(p=>p.testId)),d=s.filter(p=>l.has(p.value)),u=await jl({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:d}),m=await Gl({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await n.unquarantineTest(u,m,a),S.success(`Test ${u.name} has been successfully removed from quarantine.`)}function IT(t){return t?Ce(t):"Unknown suite"}async function PT({client:t,orgId:e,suitePaths:n,wait:r,waitTimeout:o,...a}){let{suiteRunIds:i,runGroupIds:s}=await t.queueSuiteRuns({paths:n,...a});X.info({orgId:e,suiteRunIds:i,runGroupIds:s,suitePaths:n},"Queued suites remotely"),S.dimmed(`Queued ${n.length} suites.`),r||process.exit(0);let c=Date.now();S.dimmed(`Waiting for ${n.length} suites to finish. You can view results upon completion at:`);for(let f of s)S.dimmed(`${Ye}- ${t.getAppUrl()}/run-groups/${f}`);let l=new Set,d=[],u=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(y=>y.status==="FAILED"&&(y.failureReason||y.finishedAt&&Date.now()-y.finishedAt.getTime()>30*1e3)||y.status==="PASSED"||y.status==="CANCELLED"),m=await Ms({name:"suites",getResults:async()=>{let f=s.filter(E=>!d.some(v=>v.id===E)),b=await t.bulkGetRunGroupStatus(f),y=[];for(let E of b)u(E)?d.push(E):y.push(E);return[...d,...y]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(b=>{b.status==="RUNNING"&&(l.has(b.id)||(l.add(b.id),S.log(`${l.size}/${s.length} ${IT(b.suite?.name)}`)))}),f.every(u))}),p=t.getAppUrl(),h=Vo({results:m,startTime:c,onFailed:f=>{let b=IT(f.suite?.name),y=f.runs.filter(v=>v.status==="FAILED").length,E=f.runs.length;S.error(`${b} (${y}/${E} tests failed):`);for(let v of f.runs)if(v.status==="FAILED"){let R=v.testName||v.test?.name;S.error(` ${R?Ce(R):"Unknown test"} (${p}/runs/${v.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?Ce(f.suite.name):"Unknown suite name"} (${p}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function MT({tests:t,client:e,orgId:n,...r}){!r.yes&&!await Tt(`This command will queue ${t.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:a}=await e.queueTests({testPaths:t,...r});if(X.info({queuedTests:o,runIds:a,orgId:n},"Queued tests remotely"),S.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),r.wait||process.exit(0),!a.length)return;S.dimmed(`Waiting for ${o.length} tests to complete.`);let i=new Set,s=[],c=p=>p.status==="FAILED"&&p.failureReason||p.status==="PASSED"||p.status==="CANCELLED",l=e.getAppUrl(),d=Date.now(),u=await Ms({name:"runs",getResults:async()=>{let p=a.filter(f=>!s.some(b=>b.id===f)),g=await e.bulkGetRunStatus(p),h=[];for(let f of g)c(f)?s.push(f):h.push(f);return[...s,...h]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:p=>(p.forEach(g=>{if(g.status==="RUNNING"&&!i.has(g.id)){i.add(g.id);let h=g.testName||g.test?.name;h&&S.log(`${i.size}/${o.length} ${Ce(h)}`)}}),p.every(c))}),m=Vo({results:u,startTime:d,onFailed:p=>{let g=p.testName||p.test?.name;Ls(p,g?Ce(g):"Unknown test")},getDisplayLine:p=>{let g=p.testName||p.test?.name,h=` ${g?Ce(g):"Unknown test"}`;return p.id&&(h+=` (${l}/runs/${p.id})`),h},entity:"test"});process.exit(m.failed>0?1:0)}import{randomUUID as tN}from"crypto";import nN from"fs";import{existsSync as PO,mkdirSync as MO,statSync as LO}from"fs";import{randomUUID as LT}from"crypto";import rm from"fs";import{hostname as fO}from"os";import om from"path";async function Wl(t,e,n,r){if(r){let o=await e.getScreenshot(t,r);if(o){let a=`${r}-screenshot.jpeg`,i=om.join(n,a);return rm.writeFileSync(i,o),a}}}async function SO(t,e,n,r){let o=r.runId??LT(),a={uuid:o,historyId:o,testCaseId:r.test.id,fullName:r.test.name,name:Ce(r.test.name),status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"skipped":"failed",start:r.lastAttemptStartedAt.getTime(),stop:r.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:n.suiteName},{name:"host",value:fO()},{name:"platform",value:"momentic"},{name:"attempts",value:r.attempts.toString()}],steps:[]};r.runId&&a.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${r.runId}`});for(let[s,c]of Object.entries(r.parameters))c!=null&&a.parameters.push({name:s,value:JSON.stringify(c)});r.results&&await yO(t,e,n.folder,a.steps,r.results);let i=`${o}-result.json`;rm.writeFileSync(om.join(n.folder,i),JSON.stringify(a,void 0,2))}async function Sa(t,e,n,r){let o={name:gr(r),start:r.startedAt.getTime(),stop:r.finishedAt.getTime(),status:r.status==="SUCCESS"?"passed":r.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};r.beforeUrl&&o.labels?.push({name:"URL before step",value:r.beforeUrl}),r.afterUrl&&o.labels?.push({name:"URL after step",value:r.afterUrl});let a=await Wl(t,e,n,r.beforeSnapshot);a&&o.attachments.push({name:"Screenshot before step",source:a,type:"image/jpeg"});let i=await Wl(t,e,n,r.afterSnapshot);if(i&&o.attachments.push({name:"Screenshot after step",source:i,type:"image/jpeg"}),r.message&&(o.statusDetails={message:r.message}),r.data){let s=`${LT()}-attachment.json`,c=om.join(n,s);rm.writeFileSync(c,JSON.stringify(r.data,null,2)),o.attachments.push({name:"Step output data",source:s,type:"text/plain"})}return o}async function yO(t,e,n,r,o){for(let a of o)switch(a.type){case"PRESET_ACTION":{r.push(await Sa(t,e,n,a));break}case"CONDITIONAL":{let i=await Sa(t,e,n,a);i.steps=[],a.assertionResult&&i.steps.push(await Sa(t,e,n,a.assertionResult)),i.steps.push(...await Promise.all(a.results.map(s=>Sa(t,e,n,s)))),r.push(i);break}case"AI_ACTION":case"SECTION":case"MODULE":{let i=await Sa(t,e,n,a);if(i.steps=await Promise.all(a.results.map(s=>Sa(t,e,n,s))),a.type==="MODULE"&&a.inputs){i.parameters=[];for(let[s,c]of Object.entries(a.inputs))i.parameters.push({name:s,value:c})}r.push(i)}}}async function OT(t,e,n,r){for(let o of r.runs)await SO(t,e,{folder:n,suiteName:r.suiteName},o)}import bO from"junit-report-builder";import Vl from"path";function TO(t,e){if(e.name(t.test.name).className(t.test.name).file(Vl.relative(".",t.filePath)).property("id",t.test.id).property("dd_tags[id]",t.test.id),t.test.labels&&(e.property("labels",t.test.labels.join(",")),t.test.labels.forEach(n=>{e.property("dd_tags[label]",n)})),t.baseUrl&&(e.property("base_url",t.baseUrl),e.property("dd_tags[base_url]",t.baseUrl)),t.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${t.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${t.runId}`)),t.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason))),t.beforeResults?.some(n=>n.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),t.results?.some(n=>n.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),t.afterResults?.some(n=>n.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),t.status==="FAILED"){if(t.failureReason){let n=Ki[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||No[t.failureReason];t.runId&&(r+=` Visit https://app.momentic.ai/runs/${t.runId} for more details.`),e.failure(r,n)}t.failureDetails?.errorStack&&e.stacktrace(t.failureDetails.errorStack)}else t.status==="CANCELLED"&&e.skipped();return e.time((t.finishedAt.getTime()-t.lastAttemptStartedAt.getTime())/1e3).property("started_at",t.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",t.lastAttemptStartedAt.toISOString()).property("finished_at",t.finishedAt.toISOString()).property("dd_tags[finished_at]",t.finishedAt.toISOString()),e.property("attempts",t.attempts.toString()).property("dd_tags[attempts]",t.attempts.toString()),t.parameters.envName&&(e.property("environment",t.parameters.envName),e.property("dd_tags[environment]",t.parameters.envName)),t.parameters.urlOverride&&e.property("url_override",t.parameters.urlOverride),e}function wO(t,{suiteId:e,suiteName:n,startedAt:r,finishedAt:o,runs:a,testsToSkip:i,quarantinedTestsToSkip:s,quarantinedTestReasons:c}){let l=t.testSuite().name(n);e&&l.property("id",e),l.timestamp(r).property("startedAt",r.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-r.getTime())/1e3);for(let d of a){let u=l.testCase();TO(d,u)}for(let d of i){let u=l.testCase();u.name(d.name).className(d.name).file(Vl.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(m=>{u.property("dd_tags[label]",m)})),u.skipped()}for(let d of s){let u=l.testCase();u.name(d.name).className(d.name).file(Vl.relative(".",d.relativeFilePath)).property("id",d.id).property("quarantined","true");let m=c[d.id];m&&u.property("quarantinedReason",m),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(p=>{u.property("dd_tags[label]",p)})),u.skipped()}return l}function NT(t,e){let n=bO.newBuilder();wO(n,e),n.writeTo(Vl.join(t,`${e.suiteName}.xml`))}import EO from"fs";import RO from"path";function kT(t){return{title:gr(t),duration:t.finishedAt.getTime()-t.startedAt.getTime(),error:t.status==="FAILED"?{value:t.failureReason}:void 0,steps:t.results&&t.type!=="PRESET_ACTION"?t.results.map(kT):[]}}async function CO(t,e,n,r){if(r.results?.length){let o=await Wl(t,e,n,r.results[r.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function vO(t,e,n,r){return{status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"interrupted":"failed",duration:r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime(),error:r.status==="FAILED"&&r.failureReason?{value:r.failureDetails?.classification?.reason||r.failureReason,message:r.failureDetails?.classification?.summary||No[r.failureReason]}:void 0,retry:r.attempts-1,steps:r.results?.map(kT)||[],startTime:r.lastAttemptStartedAt.toISOString(),attachments:await CO(t,e,n,r)}}async function AO(t,e,n,r){return{expectedStatus:"passed",status:r.status==="PASSED"?"expected":"unexpected",results:[await vO(t,e,n,r)]}}async function xO(t,e,n,r){return{tags:[],title:r.test.name,ok:r.status==="PASSED",tests:[await AO(t,e,n,r)],id:r.runId,file:r.filePath}}function am(t,e){return t.reduce((n,r)=>e(r)?n+1:n,0)}async function IO(t,e,n,r){return{suites:[{title:r.suiteName,file:r.projectConfigPath,specs:await Promise.all(r.runs.map(o=>xO(t,e,n,o)))}],errors:[],stats:{startTime:r.startedAt.toISOString(),duration:r.finishedAt.getTime()-r.startedAt.getTime(),expected:am(r.runs,o=>o.status==="PASSED"),unexpected:am(r.runs,o=>o.status!=="PASSED"),flaky:am(r.runs,o=>!!o.isFlake),skipped:0}}}async function _T(t,e,n,r){let o=await IO(t,e,n,r);EO.writeFileSync(RO.join(n,`${r.suiteName}.json`),JSON.stringify(o,null,2))}async function DT(t,e,n,r,o){switch(PO(o)?LO(o).isDirectory()||(S.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(S.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),MO(o,{recursive:!0})),n){case"junit":NT(o,r);return;case"allure":case"allure-json":await OT(t,e,o,r);return;case"playwright-json":await _T(t,e,o,r);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}import rN from"wait-on";import{execSync as OO}from"child_process";import{platform as NO}from"os";function im(){return FT()?(S.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),S.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.
3974
3972
  `),2):(S.dimmed("Setting device pixel ratio to 1."),S.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.
3975
- l.`),1)}function NT(){return xO()==="darwin"&&AO("system_profiler SPDisplaysDataType").toString().includes("Retina")}function lm(t){NT()&&t===1&&(S.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),S.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import IO from"@actions/exec";import PO from"@actions/io";import MO from"quote";import LO from"string-argv";async function kT(t,e=!0){let n=LO(t),r=await PO.which(n[0],!0),o=n.slice(1),a=IO.exec(MO(r),o,{delay:100});if(e)return a}import OO from"csv-parser";import{createReadStream as NO}from"fs";function cm(t){return new Promise((e,n)=>{let r=[];NO(t).pipe(OO()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>n(o))})}import Xl from"semver";import{z as Jl}from"zod";var Xn="2.16.0",kO="https://registry.npmjs.org/momentic",_O=Jl.object({versions:Jl.record(Jl.string(),Jl.unknown()).optional()});async function _T(t){try{await DO(t)}catch(e){S.warn({err:e},"Failed to check CLI version against NPM servers")}}async function DO(t){if(!Xn){t.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 H(fetch(kO),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let a=await o.json();e=_O.parse(a).versions;break}catch(o){t.warn({err:o},"Failed to fetch npm registry data")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}let n;for(let r of Object.keys(e))Xl.valid(r)&&(!n||Xl.gt(r,n))&&Xl.gt(r,Xn)&&Xl.lt(r,"2.0.0")&&!r.includes("alpha")&&(n=r);n&&(S.warn(`Update available: v${Xn} -> v${n}`),S.warn("This version may be missing critical fixes, features, and security updates."),S.warn(`Run "npx momentic@${n} -V" to update`))}import dm from"fs";import{compact as FO,partition as Ql}from"lodash-es";import um from"path";import{cwd as UO}from"process";import BO from"semver";async function Zl({tests:t,momenticFiles:e,project:n,yes:r,include:o,exclude:a,labels:i,logger:s}){let l=new Set;if(t&&t.length>0){let d=t.some(m=>dm.existsSync(m)),u=UO();d?(u!==n.rootDir&&s.warn(`The current working directory ('${u}') is different from the project root directory ('${n.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),s.info(`Reading tests from the following local file paths:
3976
- ${t.map(m=>`${Ke}- ${m}`).join(`
3973
+ l.`),1)}function FT(){return NO()==="darwin"&&OO("system_profiler SPDisplaysDataType").toString().includes("Retina")}function sm(t){FT()&&t===1&&(S.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),S.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import kO from"@actions/exec";import _O from"@actions/io";import DO from"quote";import FO from"string-argv";async function UT(t,e=!0){let n=FO(t),r=await _O.which(n[0],!0),o=n.slice(1),a=kO.exec(DO(r),o,{delay:100});if(e)return a}import UO from"csv-parser";import{createReadStream as BO}from"fs";function lm(t){return new Promise((e,n)=>{let r=[];BO(t).pipe(UO()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>n(o))})}import ql from"semver";import{z as Kl}from"zod";var Yn="2.17.0",zO="https://registry.npmjs.org/momentic",HO=Kl.object({versions:Kl.record(Kl.string(),Kl.unknown()).optional()});async function BT(t){try{await $O(t)}catch(e){S.warn({err:e},"Failed to check CLI version against NPM servers")}}async function $O(t){if(!Yn){t.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 j(fetch(zO),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let a=await o.json();e=HO.parse(a).versions;break}catch(o){t.warn({err:o},"Failed to fetch npm registry data")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}let n;for(let r of Object.keys(e))ql.valid(r)&&(!n||ql.gt(r,n))&&ql.gt(r,Yn)&&ql.lt(r,"2.0.0")&&!r.includes("alpha")&&(n=r);n&&(S.warn(`Update available: v${Yn} -> v${n}`),S.warn("This version may be missing critical fixes, features, and security updates."),S.warn(`Run "npx momentic@${n} -V" to update`))}import cm from"fs";import{compact as jO,partition as Yl}from"lodash-es";import dm from"path";import{cwd as GO}from"process";import WO from"semver";async function Xl({tests:t,momenticFiles:e,project:n,yes:r,include:o,exclude:a,labels:i,logger:s}){let c=new Set;if(t&&t.length>0){let d=t.some(m=>cm.existsSync(m)),u=GO();d?(u!==n.rootDir&&s.warn(`The current working directory ('${u}') is different from the project root directory ('${n.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),s.info(`Reading tests from the following local file paths:
3974
+ ${t.map(m=>`${Ye}- ${m}`).join(`
3977
3975
  `)}
3978
- `),t.forEach(m=>{if(!dm.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=dm.statSync(m),g=p.isDirectory()}catch(f){s.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=um.resolve(m);Object.values(e.tests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{l.add(f.fullFilePath)})})):(s.info(`Reading all tests from the project and running those matching the following substring filters:
3979
- ${t.map(m=>`${Ke}- ${m}`).join(`
3980
- `)}`),Object.values(e.tests).forEach(m=>{t.some(p=>m.relativePath.includes(p))&&l.add(m.fullFilePath)}))}else{!r&&!await bt("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let d=Object.values(e.tests);s.info(`Reading all ${d.length} tests in the project from local disk.`),d.forEach(u=>{l.add(u.fullFilePath)})}for(let d of l){let u=um.relative(n.rootDir,d);o&&!o.some(m=>new RegExp(m).test(u))&&l.delete(d),a&&a.some(m=>new RegExp(m).test(u))&&l.delete(d)}let c=Array.from(l).map(async d=>{try{let u=await Mt(d,X,e);if(BO.gt(u.schemaVersion,se)&&s.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),i&&i.length>0){let m=u.labels||[];if(!i.some(g=>m.includes(g)))return null}return{...u,fullFilePath:d,relativeFilePath:um.relative(n.rootDir,d)}}catch(u){s.error(`Failed to read and resolve test at '${d}': ${u}`),process.exit(1)}});return Promise.all(c).then(FO)}function DT({testDefinitions:t,quarantinedTestReasons:e,onlyQuarantined:n=!1,skipQuarantined:r=!1}){if(n){let[d,u]=Ql(t,g=>g.id in e),[m,p]=Ql(d,g=>g.disabled||r);return{testsToSkip:m,quarantinedTestsToSkip:[],testsToRun:p,quarantinedTestsToRun:[]}}let[o,a]=Ql(t,d=>d.disabled),[i,s]=Ql(a,d=>d.id in e);return{testsToSkip:o,testsToRun:s,quarantinedTestsToRun:r?[]:i,quarantinedTestsToSkip:r?i:[]}}function FT({testsToRun:t,quarantinedTestsToRun:e,quarantinedTestReasons:n,testInputMatrix:r}){let o=[],a=(i,s,l)=>{r?r.forEach((c,d)=>{o.push({inputs:c,inputIndex:d,testDefinition:i,quarantined:s,quarantinedReason:l})}):o.push({inputs:void 0,testDefinition:i,quarantined:s,quarantinedReason:l})};return t.forEach(i=>a(i,!1)),e.forEach(i=>a(i,!0,n[i.id])),o}import{partition as zO}from"lodash-es";function ec(t){return t.length===1?"test":"tests"}function UT(t){return t===1?"1 worker":`${t} workers`}function BT(t){t.length!==0&&(S.info(`Skipping ${t.length} disabled ${ec(t)}:`),t.forEach(e=>{S.info(`${Ke}- ${[e.relativeFilePath]}`)}),S.log(""))}function zT(t,e){t.length!==0&&(S.info(`Skipping ${t.length} quarantined ${ec(t)}:`),t.forEach(n=>{S.info(`${Ke}- ${[n.relativeFilePath]}: ${e[n.id]}`)}),S.log(""))}function HO(t,e){t.length!==0&&(S.info(`Running ${t.length} quarantined ${ec(t)} with ${UT(e)}:`),t.forEach(n=>{S.info(`${Ke}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),S.log(""))}function $O(t,e,n){e.length===0&&t.length>0||(S.info(`Running ${e.length} ${ec(e)} with ${UT(n)}:`),e.forEach(r=>{S.info(`${Ke}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),S.log(""))}function HT({logger:t,localTestsToRunWithInputs:e,parallel:n,shardCount:r,shardIndex:o}){t.info({tests:e.length,shardCount:r,shardIndex:o,parallel:n},"Running local tests");let[a,i]=zO(e,s=>s.quarantined);HO(a,n),$O(a,i,n)}import{cloneDeep as ya}from"lodash-es";async function $T({orgId:t,codeEvalTools:e,logger:n,outputDefinitions:r,testContext:o,flagStore:a}){let i={};for(let s of r){let{name:l,value:c}=s;i[l]=await jt({orgId:t,s:c,localTools:e,logger:n,context:o})}return i}async function jT({baseUrl:t,envName:e,testName:n,devicePixelRatio:r,apiClient:o,test:a,storageClient:i,codeEvalTools:s,generator:l,orgId:c,variables:d,logger:u,customHeaders:m,testInputs:p,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,flagStore:y}){let b=await hl({settings:g,customHeaders:m,envVariables:d,envName:e,testName:n,baseUrl:t,logger:u,localTools:s,orgId:c}),w={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:X},C=y.isBooleanFlagEnabled("icon_knowledge_base")?await i.fetchIconKnowledgeBase(u):null,v=b.browserType??"Chromium";if(!Ih(v)){let D=`Browser ${v} is required by the test named ${a.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;S.warn(D),X.warn(D)}let R=await kn.init({baseUrl:t,logger:u,userBrowserSettings:b,storage:i,flagStore:y,enricher:new Xo(w,l),contextArgs:{viewport:a.advanced.viewport??Nt,locale:a.advanced.locale??_o,geolocation:a.advanced.geolocation??Fo,timezoneId:a.advanced.timezone??Do,colorScheme:a.advanced.colorScheme,deviceScaleFactor:r},iconKnowledgeBase:C}),x=new pa({browser:R,generator:l,logger:u,orgId:c,options:{scratchPadId:void 0,slowMoMs:b.slowMoMs,autoFollowNewTabs:b.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??y.isBooleanFlagEnabled("rag_v2")},storage:i,flagStore:y,localCodeEvalTools:s,visualDiffScreenshotStorage:f}),M=new Xt({baseUrl:t,currentUrl:x.browser.url(),variablesFromEnvironment:d,envName:e,testName:n});return a.parameters&&await Promise.all(a.parameters.map(async D=>{let{name:_,defaultValue:K,required:P}=D,W=p?.[_];P&&W===void 0&&(S.error(`Required parameter '${_}' is required by test '${a.name}' but not provided`),process.exit(1));let k=await jt({orgId:c,s:W??K,localTools:s,logger:u,context:Xt.dummyContext(M.getEnvName())});M.setMomenticSystemVariable(_,k)})),{controller:x,context:M}}async function GT({testAdvancedSettings:t,orgSettings:e,logger:n}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Ea){let r="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(r),S.warn(r),!1}return!0}async function WT({attemptInputs:t,attemptFixtures:e,attemptMetadata:n}){let{orgId:r,runId:o}=n,{controller:a,context:i,codeEvalTools:s,storageClient:l,logger:c,billingReporter:d,tracer:u}=e,{test:m,orgSettings:p}=t;c.info(`Running test '${m.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let g={controller:a,storage:l,billingReporter:d,context:i,logger:c,codeEvalTools:s},h={orgId:r,runId:o,testMetadata:m,steps:m.steps,beforeSteps:m.beforeSteps,afterSteps:m.afterSteps,orgSettings:p},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await GT({testAdvancedSettings:m.advanced,orgSettings:p.ai,logger:c})};return await gl({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()}}},testParams:{tracer:u}})}async function VT(t){let{testDefinition:e,logger:n}=t,r=new Date;try{return await jO(t)}catch(o){let a="Fatal error running test";return S.error(`${a}: ${o.message}`),n.error({err:o},a),{results:[],parameters:t,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:r,lastAttemptStartedAt:r,finishedAt:new Date,outputs:{}}}}async function jO(t){let{testDefinition:e,project:n,apiClient:r,orgId:o,urlOverride:a,runSigIntHandlers:i,runGroupTracer:s,logger:l,gitMetadata:c,alwaysSaveCache:d,noCache:u,runId:m,testInputs:p,quarantined:g,quarantinedReason:h,billingReporter:f}=t,y=new qo(r,o),b=ta({orgId:o,client:r,gitMetadata:c,alwaysSaveCache:d,noCache:u}),w=ya(e.steps),C=ya(e.beforeSteps)??void 0,v=ya(e.afterSteps)??void 0;try{await b.resolveStepCacheEntries({testId:e.id,stepLists:{steps:w,beforeSteps:C,afterSteps:v},schemaVersion:e.schemaVersion,logger:l})}catch(P){throw l.error({err:P},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${P}`)}let R=t.envName??WO(e),x,M={};if(R){try{x=ui(R,n,l)}catch(P){let W=`Failed to resolve environment ${R} for test ${e.name}: ${P}`;throw new Error(W)}M=x.variables}let D=e.baseUrl;if(a)D=a;else if(!D){let P=M[at];typeof P=="string"&&(D=P)}if(!D){let P=`Cannot run test with no base URL and no ${at} variable defined in its environment`;throw new Error(P)}let _=await s.startRun({logger:l,runId:m,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:D,environmentName:R,schemaVersion:e.schemaVersion,resolvedInputs:p,quarantined:g,quarantinedReason:h}),K=l.child(_.loggerBindings||{});Object.entries(_.envVarBindings||{}).forEach(([P,W])=>{M[P]=W});try{let P=await GO({...t,variables:M,envName:R,resolvedEnv:x,baseUrl:D,storageClient:y,tracer:_,logger:K,cacheStorage:b,stepsWithCaches:w,beforeStepsWithCaches:C,afterStepsWithCaches:v,billingReporter:f});return await _.finish({logger:l,status:P.status,finishedAt:P.finishedAt,failureDetails:P.failureDetails,failureReason:P.failureReason,isFlake:P.isFlake,failureRecoveryDetails:P.failureRecoveryDetails}),{runId:_.runId,...P}}finally{i?.pop()}}async function GO(t){let{testDefinition:e,stepsWithCaches:n,beforeStepsWithCaches:r,afterStepsWithCaches:o,project:a,regenerateGoldenFiles:i,apiClient:s,generator:l,baseUrl:c,storageClient:d,orgId:u,envName:m,urlOverride:p,customHeaders:g,testInputs:h,variables:f,resolvedEnv:y,retriesOverride:b,devicePixelRatio:w,logUpdate:C,tracer:v,logger:R,flagStore:x,cacheStorage:M,gitMetadata:D,quarantined:_,quarantinedReason:K,billingReporter:P}=t,W=a.config.ai?.aiFailureAnalysis??!1,k=new Date,G=new sa(a,i),we={...a.config},Ce={envName:m,urlOverride:p,customHeaders:g,testInputs:h},be,wt=Math.abs(b??a.config.retries??e.retries??0),Sn=[];R.info({...D,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let de=0;de<=wt;de++){let oe=await v.startAttempt(),ot=R.child(oe.loggerBindings||{}),Pe={...e,steps:ya(n),beforeSteps:ya(r),afterSteps:ya(o)};de!==0&&C("RETRY",`attempt ${de+1}/${wt+1}`);let _n=new Date,Pi=we.advanced?.fakerConstantSeed??x.isBooleanFlagEnabled("faker_constant_seed"),Ta=new gr({httpClient:new xt({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:ot}),fakerSeed:Pi?gs:void 0}),oc=oe;try{let{controller:Dn,context:Bt}=await jT({baseUrl:c,envName:m,testName:Pe.name,apiClient:s,devicePixelRatio:w,logger:ot,storageClient:d,codeEvalTools:Ta,test:Pe,generator:l,orgId:u,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...a.config.browser||{},...y?.browser||{},...Pe.advanced},aiSettings:{...a.config.ai||{},...Pe.advanced||{}},visualDiffScreenshotStorage:G,flagStore:x});be=await WT({attemptMetadata:{attemptNumber:de+1,orgId:u,runId:v.runId},attemptFixtures:{logger:ot,storageClient:d,billingReporter:P,codeEvalTools:Ta,flagStore:x,apiClient:s,context:Bt,controller:Dn,tracer:oe},attemptInputs:{test:Pe,orgSettings:we}});let yn=new Date,Pr={logger:R,cacheStorage:M,orgId:u,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:Pe.steps,beforeSteps:Pe.beforeSteps,afterSteps:Pe.afterSteps}};be?.status==="PASSED"?await zs(Pr):be?.status==="FAILED"&&await Hs(Pr),await oe.finish({logger:ot,result:be}),Sn.unshift(be.status);let $=await $T({orgId:u,codeEvalTools:Ta,logger:ot,outputDefinitions:e.outputs??[],testContext:Bt,flagStore:x}),bo=ap(Sn),To=de+1;if(be.status!=="FAILED")return{...be,parameters:Ce,test:Pe,filePath:Pe.relativeFilePath,startedAt:k,lastAttemptStartedAt:_n,finishedAt:yn,attempts:To,baseUrl:c,outputs:$,isFlake:bo,quarantined:_,quarantinedReason:K};let Jn=be.failedStepResult,Fn=Jn?.message||"Unknown failure",Mr=Jn?.failureReason??eg(Fn)??"UnknownError",Qn=ot.child({errResult:Jn,failureReason:Mr,errorMessage:Fn,numAttempts:wt+1,name:Pe.name});if(de<wt){Qn.warn(`Retrying failed execution attempt for run: ${Fn}`);continue}Qn.error(`Test failed after all exhausting attempts: ${Fn}`);let ac=new Error(Fn),Mi={errorMessage:Fn,errorStack:ac.stack},pt;if(W){let Zn;try{if(be.results&&be.results.length>0){let{classification:er,aiFailureReason:Et}=await If({logger:ot,browserStateStorage:oc,generator:l,results:be.results,error:ac,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Zn=er,pt=Et}}catch(er){ot.warn({err:er},"Failed to classify test results")}Zn&&(Mi.classification=Zn,Mr=pt??Mr)}return{...be,parameters:Ce,failureDetails:Mi,failureReason:Mr,test:Pe,filePath:Pe.relativeFilePath,startedAt:k,lastAttemptStartedAt:_n,finishedAt:yn,attempts:de+1,baseUrl:c,outputs:$,quarantined:_,quarantinedReason:K}}catch(Dn){wa(Dn);let Bt=`Encountered fatal platform error while running test '${Pe.name}': ${Dn}`,yn=new Date,Pr=de+1;ot.error({err:Dn},Bt),S.error(Bt);let $={errorMessage:Dn.message,errStack:Dn.stack},bo={status:"FAILED",failureDetails:$,failureReason:"InternalPlatformError",finishedAt:yn};return await oe.finish({logger:ot,result:{status:"FAILED",results:[]}}),{...bo,results:[],parameters:Ce,test:Pe,filePath:Pe.relativeFilePath,startedAt:k,lastAttemptStartedAt:_n,finishedAt:new Date,attempts:Pr,baseUrl:c,outputs:{},quarantined:_,quarantinedReason:K}}}throw new Error("This code should not be reachable")}function WO(t){for(let e of t.envs??[])if(e.default)return e.name}import{randomUUID as VO}from"crypto";var Ir="assets";function qO(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function KO(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var mm=class{constructor(e,n,r,o){this.testId=e;this.testName=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.jpeg`,contents:r})}attachAfterScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.jpeg`,contents:r})}attachBeforeHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.html`,contents:r})}attachAfterHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.html`,contents:r})}heal(e){let{healType:n}=e;this.metadata.healMetadata={healType:n,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finish({status:KO(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},ba=class{constructor(e,n,r){this.testId=e;this.testName=n;this.diskStorage=r}children=[];finished=!1;async getScreenshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.html`)?.toString()}getParentStepIdChain(){return[]}async startStep(e){let{step:n}=e,r={step:n,status:"RUNNING",startedAt:new Date},o=new mm(this.testId,this.testName,r,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finishInternal({status:qO(e.status),finishedAt:e.finishedAt}))))}},pm=class{constructor(e,n,r,o,a){this.testId=e;this.testName=n;this.runAttemptId=r;this.metadata=o;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(n,null,2)})}attachConsoleLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(n,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:n,result:r}=e,o={...this.metadata,status:r.status,finishedAt:new Date,results:Ws(r.results,n),beforeResults:r.beforeResults?Ws(r.beforeResults,n):void 0,afterResults:r.afterResults?Ws(r.afterResults,n):void 0};await Promise.all(this.children.map(a=>a.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.html`)?.toString()}},gm=class{constructor(e,n,r,o,a){this.testId=e;this.testName=n;this.runId=r;this.metadata=o;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[vS]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let n={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(r=>r.finish({logger:e.logger,result:{status:n.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)}),this.diskStorage.close()}async startAttempt(){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=VO(),r={id:n,schemaVersion:se,runAttemptSchemaVersion:ph,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new pm(this.testId,this.testName,n,r,e);return this.children.push(o),o}},tc=class t{constructor(e,n,r,o){this.orgId=e;this.runGroupId=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,n,r,o,a){let i={...o,id:n,trigger:Jt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Xn,labels:a??[]},s=new pi(r);return s.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)}),new t(e,n,i,s)}async finish(e){if(this.finished)return;this.finished=!0;let{status:n}=e,r={...this.metadata,status:n,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:r.status,finishedAt:r.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)})}async startRun(e){let n=this.diskStorage.createRunArchive(e.runId),r={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Xn,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};n.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new gm(e.testId,e.testName,e.runId,r,n);return this.children.push(o),o}};async function qT(t,e,n){if(n)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,a)=>(o[a.testId]=a.quarantinedReason,o),{})}catch(r){return t.warn({err:r},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function KT(t){let{logger:e,tests:n,yes:r,start:o,waitOn:a,client:i,debugDataStorage:s,billingReporter:l,flagStore:c,project:d,retriesOverride:u,urlOverride:m,envName:p,orgId:g,devicePixelRatio:h,customHeaders:f,testInputMatrix:y,reporter:b,include:w,exclude:C,labels:v,reporterDir:R=qf,outputDir:x=Kf,uploadResults:M=!1,waitOnTimeout:D=60,parallel:_,shardIndex:K=1,shardCount:P=1,regenerateGoldenFiles:W,gitMetadata:k,alwaysSaveCache:G,noCache:we,ignoreQuarantine:Ce,skipQuarantined:be,onlyQuarantined:wt,runGroupId:Sn}=t;o&&(e.info({orgId:g},`Executing start command: ${o}`),await kT(o,!1)),a&&(e.info({orgId:g},`Waiting for url: ${a} with timeout: ${D} seconds.`),await JO({resources:[a],interval:2500,timeout:D*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let de=new Yo(d.config.ai?.agentConfig,{baseUrl:i.baseUrl,apiKey:i.apiKey,logger:e}),oe=te(d,S),ot=await Zl({tests:n,momenticFiles:oe,yes:r,project:d,include:w,exclude:C,labels:v,logger:S}),Pe=await qT(e,i,Ce),{testsToSkip:_n,quarantinedTestsToSkip:Pi,testsToRun:Ta,quarantinedTestsToRun:oc}=DT({testDefinitions:ot,quarantinedTestReasons:Pe,onlyQuarantined:wt,skipQuarantined:be});BT(_n),zT(Pi,Pe);let Dn=FT({testsToRun:Ta,quarantinedTestsToRun:oc,quarantinedTestReasons:Pe,testInputMatrix:y}),Bt=ZO({globalTestsToRunWithInputs:Dn,shardIndex:K,shardCount:P});HT({logger:e,localTestsToRunWithInputs:Bt,parallel:_,shardCount:P,shardIndex:K});let yn=[],Pr=new Date,$=new Set,bo=async()=>{let pt=i.getAppUrl(),Zn=Vo({results:yn,startTime:Pr.getTime(),onFailed:Et=>{Ls(Et,Et.filePath)},getDisplayLine:Et=>{let Lr=`${Ke}- ${Et.filePath}${Et.failureRecoveryDetails?" [recovered] ":""}`;return Et.runId&&(Lr+=` ( link when uploaded: ${pt}/runs/${Et.runId} )`),Lr},entity:"test"}),er=yn.filter(Et=>!!Et.failureRecoveryDetails?.attempts);return er.length>0&&S.warn(`Our AI agent automatically prevented ${er.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),S.log(""),M?(S.success(`Test results have been saved to the folder ${x}. Uploading to Momentic Cloud...`),await sl({client:i,consoleLogger:S,resultsPath:x})):S.success(`Test results have been saved to the folder ${x}. Upload them to Momentic Cloud by running 'npx momentic results upload ${x}'.`),Zn};XO.existsSync(x)&&S.warn(`Output directory ${x} already exists, removing before test execution...`);let To=await tc.start(g,Sn,x,k,v),Jn=e.child(To.loggerBindings||{}),Fn=[],Mr=async()=>{S.warn("SIGINT received. Stopping tests and printing latest results..."),await To.finish({logger:Jn,status:"CANCELLED"}),await bo(),await Promise.allSettled(Fn.map(pt=>pt())),process.exit(1)};process.once("SIGINT",Mr);let Qn={};for(let pt=0;pt<Bt.length;pt++){let Zn=Object.values(Qn);Zn.length===_&&await Promise.race(Zn.map(Lr=>Lr.promise));let er=Bt[pt],Et=`test-${pt}`;Qn[Et]={done:!1,promise:(async({inputs:Lr,quarantined:ew,quarantinedReason:tw,testDefinition:wo})=>{$.add({inputs:Lr});let Li=wo.relativeFilePath.includes("..")?wo.fullFilePath:wo.relativeFilePath;Za({status:"START",testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length});let nw=setInterval(()=>Za({status:"RUN",testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length}),5*60*1e3),Sm=YO(),ym=Jn.child({testId:wo.id,runId:Sm});try{let Oi=await VT({testDefinition:wo,project:d,testInputs:Lr,quarantined:ew,quarantinedReason:tw,orgId:g,runId:Sm,devicePixelRatio:h,apiClient:i,runGroupTracer:To,generator:de,retriesOverride:u,urlOverride:m,envName:p,customHeaders:f,regenerateGoldenFiles:W,logUpdate:(Ni,rw)=>Za({status:Ni,testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length,additionalText:rw}),runSigIntHandlers:Fn,logger:ym,flagStore:c,gitMetadata:k,alwaysSaveCache:G,noCache:we,billingReporter:l});Za({status:Oi.status,testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length}),yn.push(Oi)}catch(Oi){let Ni=`Encountered unexpected fatal error when running test '${wo.name}': ${Oi.message}`;S.error(Ni),ym.error(Ni)}finally{clearInterval(nw),Qn[Et].done=!0,delete Qn[Et]}})(er)}}await Promise.allSettled(Object.values(Qn).map(pt=>pt.promise));let Mi=yn.some(pt=>!pt.quarantined&&pt.status==="FAILED")?"FAILED":"PASSED";return await To.finish({logger:Jn,status:Mi}),process.off("SIGINT",Mr),b&&await OT(Jn,s,b,{projectConfigPath:d.configFilePath,suiteName:d.config.name,startedAt:Pr,finishedAt:new Date,runs:yn,testsToSkip:_n,quarantinedTestsToSkip:Pi,quarantinedTestReasons:Pe},R),bo()}function QO(t,e,n){if(n>t.length&&(S.warn(`Shard count ${n} is greater than the number of tests ${t.length}! Some workers won't have any tests to run.`),n=Math.max(n,t.length),e>n))return[];let r=Math.floor((e-1)*(t.length/n)),o=Math.floor(e*(t.length/n));return t.sort().filter((i,s)=>s>=r&&s<o)}function ZO({globalTestsToRunWithInputs:t,shardIndex:e,shardCount:n}){return n&&n>1?QO(t,e,n):t}ic||X.warn("Sentry is not enabled in this environment due to unsupported node version");var iN=process.argv.some(t=>t.includes("--log-level"))&&process.argv.some(t=>t.includes("debug")),hm=t=>{iN&&S.dimmed(t)},Tt=new eN;Tt.name("momentic").description("Momentic CLI").version(Xn);Tt.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${Rd.join(", ")}.`).action(async(t,e)=>{!e.all&&t.length===0&&(S.error("No browsers specified"),process.exit(1)),await Ph({rawBrowsers:t,force:e.force,all:e.all})});Tt.addOption(new Ut("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",t=>{t==="debug"&&S.info("Enabling debug logging"),S.setMinLevel(t.toLowerCase())});Tt.addOption(new Ut("--verbose","enable verbose logging")).on("option:verbose",()=>{X.enableConsoleLogs(),S.setMinLevel(20)});var fm=Tt.command("checks").alias("check").description("Perform various project checks");fm.command("config").addOption(Wt).action(async t=>{ct({configFilePath:t.config})});fm.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(Wt).addOption(dT).action(async t=>{let e=ct({configFilePath:t.config});await Xb({project:e,fix:t.fix})});fm.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Wt).action(async t=>{let e=ct({configFilePath:t.config});await Jb({project:e})});var XT=Tt.command("migrate").description("Migrate and upgrade tooling");XT.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(Wt).action(async t=>{let e=ct({configFilePath:t.config});await bT(e)});XT.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(fn).addOption(Wt).addOption(hn).addOption(xr).action(async t=>{!t.yes&&!await bt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=ct({configFilePath:t.config}),n=new Je({baseUrl:t.server,apiKey:t.apiKey,logger:X}),{orgId:r}=await n.getAuthInfo();await wT({project:e,orgId:r,apiClient:n}),process.exit(0)});Tt.command("import").addOption(hn).addOption(fn).addOption(Wt).addOption(xr).addArgument(hT).action(async(t,e)=>{let{apiKey:n,server:r,config:o,yes:a}=e,i=ct({configFilePath:o}),s=new Je({baseUrl:r,apiKey:n,logger:X});!t||t.length===0?await nT({client:s,project:i,skipPrompts:a}):await rT({client:s,project:i,paths:t,skipPrompts:a}),process.exit(0)});Tt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Ut("--name <name>","Name of the project")).action(async t=>{S.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3981
- `),S.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."),rc.existsSync(oa)&&(S.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 n={name:t.name??await Ch("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Vd};aa(n,oa),S.success(`Initialized Momentic project file at ${nc.resolve(oa)}`)});Tt.command("app").addOption(hn).addOption(fn).addOption(xr).addOption(Ju).addOption(Wt).addOption(Zu).addOption(em).action(async t=>{let{apiKey:e,yes:n,server:r,pixelRatio:o,disableCache:a,saveCache:i}=t,s=ct({configFilePath:t.config,nameFilter:void 0}),{errors:l}=await Bl({project:s,fix:!1});l>0&&(S.error(`Found ${l} errors`),S.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 c=new Je({baseUrl:r,apiKey:e,logger:X});await xd({client:c,skipPrompts:n});let d=aN(import.meta.url),u=nc.dirname(d),m=nc.resolve(u,"..","static"),p=nc.resolve(u,"..","assets"),g=o??sm();lm(g),await Vb({momenticServerUrl:r,apiKey:e,serverPort:zl,appPort:zl,staticDir:m,assetsDir:p,devicePixelRatio:g,noCache:a,alwaysSaveCache:i,initialProject:s});let h=`http://localhost:${zl}`;await oN(h)});var JT=Tt.command("queue").description("Queue tests or suites to run on Momentic Cloud");JT.command("suites").description("Run one or more suites on Momentic Cloud").addOption(hn).addOption(fn).addOption(Vu).addOption(qu).addOption(xr).addArgument(fT).addOption(Gl).addOption(jl).addOption($l).action(async(t,e)=>{let{apiKey:n,server:r,wait:o,waitTimeout:a,env:i,urlOverride:s}=e,l=Hl(e.customHeaders),c=new Je({baseUrl:r,apiKey:n,logger:X});(!t||!Array.isArray(t)||!t.length)&&(S.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await vT({client:c,orgId:d,wait:o,suitePaths:t,waitTimeout:a,env:i,urlOverride:s,customHeaders:l})});JT.command("tests").description("Run one or more tests on Momentic Cloud").addOption(hn).addOption(fn).addOption(xr).addOption($l).addOption(Qu).addOption(Gl).addOption(jl).addOption(new Ut("--all","Run all tests.").default(!1)).addOption(Vu).addOption(qu).addArgument(gT).action(async(t,e)=>{let{all:n,apiKey:r,env:o,server:a,inputCsv:i,urlOverride:s,wait:l,waitTimeout:c,yes:d}=e,u=Hl(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||rc.existsSync(h))&&S.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 Je({baseUrl:a,apiKey:r,logger:X}),{orgId:p}=await m.getAuthInfo(),g;i&&(g=await cm(i)),await AT({client:m,orgId:p,tests:t,all:n,customHeaders:u,env:o,urlOverride:s,wait:l,waitTimeout:c,testInputMatrix:g,yes:d}),process.exit(0)});var sN=Tt.command("list").description("List test paths");sN.addOption(Wt).addOption(fa).addOption(Yu).addOption(Xu).addOption(new Ut("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(tm).action(async(t,e)=>{let n=ct({configFilePath:e.config,nameFilter:e.filter}),r=te(n,S),o=await Zl({tests:t,momenticFiles:r,yes:!0,project:n,include:e.include,exclude:e.exclude,labels:e.labels,logger:new Ka(40,{})});S.info(o.map(a=>a.relativeFilePath).join(`
3982
- `)),process.exit(0)});var lN=Tt.command("run").alias("test").description("Run tests on the local machine");lN.addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(xr).addOption($l).addOption(Qu).addOption(Zu).addOption(em).addOption(uT).addOption(mT).addOption(pT).addOption(jl).addOption(Gl).addOption(Ju).addOption(new Ut("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Ut("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Ut("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(Ar)).addOption(new Ut("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(Ar)).addOption(new Ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Ar)).addOption(new Ut("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Ut("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(aT).addOption(iT).addOption(Ku).addOption(sT).addOption(cT).addOption(lT).addOption(Yu).addOption(Xu).addArgument(tm).action(async(t,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let n=Hl(e.customHeaders),r=ct({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??r.config.parallel??1;YT().length<o*2&&S.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${YT().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),S.debug({projectName:r.config.name},"Identified project config");let{errors:a}=await Bl({project:r,fix:!1});a>0&&(S.error(`Found ${a} errors`),S.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 i=new Je({baseUrl:e.server,apiKey:e.apiKey,logger:X});S.debug("Checking API key and dependencies");let{orgId:s,userId:l}=await xd({client:i,skipPrompts:e.yes});S.debug("API key check and browser installation complete");let c=new Ns(i),d=new $a,u=e.outputDir??r.config.outputDir,m=e.reporterDir??r.config.reporterDir,p=nN(),g=X.child({runGroupId:p,orgId:s,userId:l,cliVersion:Xn,trigger:"CLI"}),h=await Sr(X,i,r);g.info(h,"Got local git metadata");let f=new fr(r.config),y;e.inputCsv&&(y=await cm(e.inputCsv));let b=e.pixelRatio??sm();lm(b);try{(await KT({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:b,tests:t,project:r,client:i,debugDataStorage:d,billingReporter:c,flagStore:f,outputDir:u,uploadResults:e.uploadResults,reporterDir:m,customHeaders:n,envName:e.env,orgId:s,testInputMatrix:y,logger:g,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:h,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:p})).failed>0?process.exit(1):process.exit(0)}catch(w){S.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),S.error(w),process.exit(1)}});var cN=Tt.command("apply").description("Apply an operation to local resources");cN.command("patch").addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(xr).addOption(new Ut("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Ut("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async t=>{let{apiKey:e,server:n,config:r,yes:o}=t,a=ct({configFilePath:r}),i=X,s=new Je({baseUrl:n,apiKey:e,logger:i}),l=te(a,S),c=l.tests[t.to]??Object.values(l.tests).find(u=>ve(u.name)===t.to.trim());c||(S.error(`No test matching '${t.to}' could be found in the current project.`),process.exit(1));let d=await s.fetchTestFragment(t.from);await Kb({client:s,test:c,fragment:d,yes:o,entities:l,logger:X}),process.exit(0)});var QT=Tt.command("results").description("Merge and upload test results.");QT.command("merge").description("Merge test results files.").addOption(Ku).addArgument(ST).action(async(t,e)=>{let{outputDir:n}=e;n||(S.error("Output directory is required."),process.exit(1)),rc.existsSync(t)||(S.warn("Results path does not exist, skipping merge."),process.exit(0)),rc.existsSync(n)&&S.warn(`Output directory ${n} already exists, removing before merging...`),Qf(X,n,t)});QT.command("upload").description("Upload test results to Momentic cloud.").addOption(hn).addOption(fn).addArgument(yT).action(async(t,e)=>{let{apiKey:n,server:r}=e,o=X,a=new Je({baseUrl:r,apiKey:n,logger:o});await sl({consoleLogger:S,resultsPath:t,client:a}),process.exit(0)});var ZT=Tt.command("quarantine").description("Manage test quarantines");ZT.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(nm).addArgument(rm).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:a}=e,i=X,s=ct({configFilePath:o}),l=new Je({baseUrl:r,apiKey:n,logger:i}),c=await Sr(X,l,s);await ET({test:t,reason:a,apiClient:l,project:s,logger:i,identity:c})});ZT.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(nm).addArgument(rm).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:a}=e,i=X,s=ct({configFilePath:o}),l=new Je({baseUrl:r,apiKey:n,logger:i}),c=await Sr(X,l,s);await RT({test:t,reason:a,apiClient:l,project:s,logger:i,identity:c})});async function dN(){hm("Main program started"),await _T(X),hm("CLI version check complete");try{await Tt.parseAsync(process.argv)}catch(t){let e={};try{e.playwrightVersion=tN("npx playwright --version").toString()}catch(n){X.error({err:n},"Error fetching debug information")}X.error({err:t,debugInfo:e},"Uncaught error in CLI"),X.flush(),wa(t,e),S.error(t),process.exit(1)}}rN.setMaxListeners(50);process.on("warning",t=>{X.warn({err:t},`Node warning received on CLI: ${t.message}`)});hm("CLI parsing setup complete");dN();
3976
+ `),t.forEach(m=>{if(!cm.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=cm.statSync(m),g=p.isDirectory()}catch(f){s.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=dm.resolve(m);Object.values(e.tests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{c.add(f.fullFilePath)})})):(s.info(`Reading all tests from the project and running those matching the following substring filters:
3977
+ ${t.map(m=>`${Ye}- ${m}`).join(`
3978
+ `)}`),Object.values(e.tests).forEach(m=>{t.some(p=>m.relativePath.includes(p))&&c.add(m.fullFilePath)}))}else{!r&&!await Tt("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let d=Object.values(e.tests);s.info(`Reading all ${d.length} tests in the project from local disk.`),d.forEach(u=>{c.add(u.fullFilePath)})}for(let d of c){let u=dm.relative(n.rootDir,d);o&&!o.some(m=>new RegExp(m).test(u))&&c.delete(d),a&&a.some(m=>new RegExp(m).test(u))&&c.delete(d)}let l=Array.from(c).map(async d=>{try{let u=await Mt(d,X,e);if(WO.gt(u.schemaVersion,le)&&s.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),i&&i.length>0){let m=u.labels||[];if(!i.some(g=>m.includes(g)))return null}return{...u,fullFilePath:d,relativeFilePath:dm.relative(n.rootDir,d)}}catch(u){s.error(`Failed to read and resolve test at '${d}': ${u}`),process.exit(1)}});return Promise.all(l).then(jO)}function zT({testDefinitions:t,quarantinedTestReasons:e,onlyQuarantined:n=!1,skipQuarantined:r=!1}){if(n){let[d,u]=Yl(t,g=>g.id in e),[m,p]=Yl(d,g=>g.disabled||r);return{testsToSkip:m,quarantinedTestsToSkip:[],testsToRun:p,quarantinedTestsToRun:[]}}let[o,a]=Yl(t,d=>d.disabled),[i,s]=Yl(a,d=>d.id in e);return{testsToSkip:o,testsToRun:s,quarantinedTestsToRun:r?[]:i,quarantinedTestsToSkip:r?i:[]}}function HT({testsToRun:t,quarantinedTestsToRun:e,quarantinedTestReasons:n,testInputMatrix:r}){let o=[],a=(i,s,c)=>{r?r.forEach((l,d)=>{o.push({inputs:l,inputIndex:d,testDefinition:i,quarantined:s,quarantinedReason:c})}):o.push({inputs:void 0,testDefinition:i,quarantined:s,quarantinedReason:c})};return t.forEach(i=>a(i,!1)),e.forEach(i=>a(i,!0,n[i.id])),o}import{partition as VO}from"lodash-es";function Jl(t){return t.length===1?"test":"tests"}function $T(t){return t===1?"1 worker":`${t} workers`}function jT(t){t.length!==0&&(S.info(`Skipping ${t.length} disabled ${Jl(t)}:`),t.forEach(e=>{S.info(`${Ye}- ${[e.relativeFilePath]}`)}),S.log(""))}function GT(t,e){t.length!==0&&(S.info(`Skipping ${t.length} quarantined ${Jl(t)}:`),t.forEach(n=>{S.info(`${Ye}- ${[n.relativeFilePath]}: ${e[n.id]}`)}),S.log(""))}function qO(t,e){t.length!==0&&(S.info(`Running ${t.length} quarantined ${Jl(t)} with ${$T(e)}:`),t.forEach(n=>{S.info(`${Ye}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),S.log(""))}function KO(t,e,n){e.length===0&&t.length>0||(S.info(`Running ${e.length} ${Jl(e)} with ${$T(n)}:`),e.forEach(r=>{S.info(`${Ye}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),S.log(""))}function WT({logger:t,localTestsToRunWithInputs:e,parallel:n,shardCount:r,shardIndex:o}){t.info({tests:e.length,shardCount:r,shardIndex:o,parallel:n},"Running local tests");let[a,i]=VO(e,s=>s.quarantined);qO(a,n),KO(a,i,n)}import{cloneDeep as ya}from"lodash-es";async function VT({orgId:t,codeEvalTools:e,logger:n,outputDefinitions:r,testContext:o,flagStore:a}){let i={};for(let s of r){let{name:c,value:l}=s;i[c]=await jt({orgId:t,s:l,localTools:e,logger:n,context:o})}return i}async function qT({baseUrl:t,envName:e,testName:n,devicePixelRatio:r,apiClient:o,test:a,storageClient:i,codeEvalTools:s,generator:c,orgId:l,variables:d,logger:u,customHeaders:m,testInputs:p,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,flagStore:b}){let y=await hl({settings:g,customHeaders:m,envVariables:d,envName:e,testName:n,baseUrl:t,logger:u,localTools:s,orgId:l}),E={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:X},v=b.isBooleanFlagEnabled("icon_knowledge_base")?await i.fetchIconKnowledgeBase(u):null,R=y.browserType??"Chromium";if(!xh(R)){let D=`Browser ${R} is required by the test named ${a.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;S.warn(D),X.warn(D)}let C=await kn.init({baseUrl:t,logger:u,userBrowserSettings:y,storage:i,flagStore:b,enricher:new Xo(E,c),contextArgs:{viewport:a.advanced.viewport??Nt,locale:a.advanced.locale??_o,geolocation:a.advanced.geolocation??Fo,timezoneId:a.advanced.timezone??Do,colorScheme:a.advanced.colorScheme,deviceScaleFactor:r},iconKnowledgeBase:v}),x=new pa({browser:C,generator:c,logger:u,orgId:l,options:{scratchPadId:void 0,slowMoMs:y.slowMoMs,autoFollowNewTabs:y.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??b.isBooleanFlagEnabled("rag_v2")},storage:i,flagStore:b,localCodeEvalTools:s,visualDiffScreenshotStorage:f}),I=new Jt({baseUrl:t,currentUrl:x.browser.url(),variablesFromEnvironment:d,envName:e,testName:n});return a.parameters&&await Promise.all(a.parameters.map(async D=>{let{name:k,defaultValue:q,required:$}=D,_=p?.[k];$&&_===void 0&&(S.error(`Required parameter '${k}' is required by test '${a.name}' but not provided`),process.exit(1));let M=await jt({orgId:l,s:_??q,localTools:s,logger:u,context:Jt.dummyContext(I.getEnvName())});I.setMomenticSystemVariable(k,M)})),{controller:x,context:I}}async function KT({testAdvancedSettings:t,orgSettings:e,logger:n}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Ea){let r="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(r),S.warn(r),!1}return!0}async function YT({attemptInputs:t,attemptFixtures:e,attemptMetadata:n}){let{orgId:r,runId:o}=n,{controller:a,context:i,codeEvalTools:s,storageClient:c,logger:l,billingReporter:d,tracer:u}=e,{test:m,orgSettings:p}=t;l.info(`Running test '${m.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let g={controller:a,storage:c,billingReporter:d,context:i,logger:l,codeEvalTools:s},h={orgId:r,runId:o,testMetadata:m,steps:m.steps,beforeSteps:m.beforeSteps,afterSteps:m.afterSteps,orgSettings:p},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await KT({testAdvancedSettings:m.advanced,orgSettings:p.ai,logger:l})};return await gl({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()}}},testParams:{tracer:u}})}async function XT(t){let{testDefinition:e,logger:n}=t,r=new Date;try{return await YO(t)}catch(o){let a="Fatal error running test";return S.error(`${a}: ${o.message}`),n.error({err:o},a),{results:[],parameters:t,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:r,lastAttemptStartedAt:r,finishedAt:new Date,outputs:{}}}}async function YO(t){let{testDefinition:e,project:n,apiClient:r,orgId:o,urlOverride:a,runSigIntHandlers:i,runGroupTracer:s,logger:c,gitMetadata:l,alwaysSaveCache:d,noCache:u,runId:m,testInputs:p,quarantined:g,quarantinedReason:h,billingReporter:f}=t,b=new qo(r,o),y=ta({orgId:o,client:r,gitMetadata:l,alwaysSaveCache:d,noCache:u}),E=ya(e.steps),v=ya(e.beforeSteps)??void 0,R=ya(e.afterSteps)??void 0;try{await y.resolveStepCacheEntries({testId:e.id,stepLists:{steps:E,beforeSteps:v,afterSteps:R},schemaVersion:e.schemaVersion,logger:c})}catch($){throw c.error({err:$},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is a Momentic issue, please contact Support with the following error: ${$}`)}let C=t.envName??JO(e),x,I={};if(C){try{x=mi(C,n,c)}catch($){let _=`Failed to resolve environment ${C} for test ${e.name}: ${$}`;throw new Error(_)}I=x.variables}let D=e.baseUrl;if(a)D=a;else if(!D){let $=I[it];typeof $=="string"&&(D=$)}if(!D){let $=`Cannot run test with no base URL and no ${it} variable defined in its environment`;throw new Error($)}let k=await s.startRun({logger:c,runId:m,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:D,environmentName:C,schemaVersion:e.schemaVersion,resolvedInputs:p,quarantined:g,quarantinedReason:h}),q=c.child(k.loggerBindings||{});Object.entries(k.envVarBindings||{}).forEach(([$,_])=>{I[$]=_});try{let $=await XO({...t,variables:I,envName:C,resolvedEnv:x,baseUrl:D,storageClient:b,tracer:k,logger:q,cacheStorage:y,stepsWithCaches:E,beforeStepsWithCaches:v,afterStepsWithCaches:R,billingReporter:f});return await k.finish({logger:c,status:$.status,finishedAt:$.finishedAt,failureDetails:$.failureDetails,failureReason:$.failureReason,isFlake:$.isFlake,failureRecoveryDetails:$.failureRecoveryDetails}),{runId:k.runId,...$}}finally{i?.pop()}}async function XO(t){let{testDefinition:e,stepsWithCaches:n,beforeStepsWithCaches:r,afterStepsWithCaches:o,project:a,regenerateGoldenFiles:i,apiClient:s,generator:c,baseUrl:l,storageClient:d,orgId:u,envName:m,urlOverride:p,customHeaders:g,testInputs:h,variables:f,resolvedEnv:b,retriesOverride:y,devicePixelRatio:E,logUpdate:v,tracer:R,logger:C,flagStore:x,cacheStorage:I,gitMetadata:D,quarantined:k,quarantinedReason:q,billingReporter:$}=t,_=a.config.ai?.aiFailureAnalysis??!1,M=new Date,z=new sa(a,i),ue={...a.config},oe={envName:m,urlOverride:p,customHeaders:g,testInputs:h},ke,je=Math.abs(y??a.config.retries??e.retries??0),Vt=[];C.info({...D,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let tt=0;tt<=je;tt++){let Z=await R.startAttempt(),_e=C.child(Z.loggerBindings||{}),Re={...e,steps:ya(n),beforeSteps:ya(r),afterSteps:ya(o)};tt!==0&&v("RETRY",`attempt ${tt+1}/${je+1}`);let ln=new Date,Ir=ue.advanced?.fakerConstantSeed??x.isBooleanFlagEnabled("faker_constant_seed"),Ta=new pr({httpClient:new xt({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:_e}),fakerSeed:Ir?gs:void 0}),tc=Z;try{let{controller:_n,context:Bt}=await qT({baseUrl:l,envName:m,testName:Re.name,apiClient:s,devicePixelRatio:E,logger:_e,storageClient:d,codeEvalTools:Ta,test:Re,generator:c,orgId:u,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...a.config.browser||{},...b?.browser||{},...Re.advanced},aiSettings:{...a.config.ai||{},...Re.advanced||{}},visualDiffScreenshotStorage:z,flagStore:x});ke=await YT({attemptMetadata:{attemptNumber:tt+1,orgId:u,runId:R.runId},attemptFixtures:{logger:_e,storageClient:d,billingReporter:$,codeEvalTools:Ta,flagStore:x,apiClient:s,context:Bt,controller:_n,tracer:Z},attemptInputs:{test:Re,orgSettings:ue}});let yn=new Date,Pr={logger:C,cacheStorage:I,orgId:u,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:Re.steps,beforeSteps:Re.beforeSteps,afterSteps:Re.afterSteps}};ke?.status==="PASSED"?await zs(Pr):ke?.status==="FAILED"&&await Hs(Pr),await Z.finish({logger:_e,result:ke}),Vt.unshift(ke.status);let G=await VT({orgId:u,codeEvalTools:Ta,logger:_e,outputDefinitions:e.outputs??[],testContext:Bt,flagStore:x}),bo=op(Vt),To=tt+1;if(ke.status!=="FAILED")return{...ke,parameters:oe,test:Re,filePath:Re.relativeFilePath,startedAt:M,lastAttemptStartedAt:ln,finishedAt:yn,attempts:To,baseUrl:l,outputs:G,isFlake:bo,quarantined:k,quarantinedReason:q};let Xn=ke.failedStepResult,Dn=Xn?.message||"Unknown failure",Mr=Xn?.failureReason??Zp(Dn)??"UnknownError",Jn=_e.child({errResult:Xn,failureReason:Mr,errorMessage:Dn,numAttempts:je+1,name:Re.name});if(tt<je){Jn.warn(`Retrying failed execution attempt for run: ${Dn}`);continue}Jn.error(`Test failed after all exhausting attempts: ${Dn}`);let nc=new Error(Dn),Mi={errorMessage:Dn,errorStack:nc.stack},gt;if(_){let Qn;try{if(ke.results&&ke.results.length>0){let{classification:Zn,aiFailureReason:Et}=await xf({logger:_e,browserStateStorage:tc,generator:c,results:ke.results,error:nc,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Qn=Zn,gt=Et}}catch(Zn){_e.warn({err:Zn},"Failed to classify test results")}Qn&&(Mi.classification=Qn,Mr=gt??Mr)}return{...ke,parameters:oe,failureDetails:Mi,failureReason:Mr,test:Re,filePath:Re.relativeFilePath,startedAt:M,lastAttemptStartedAt:ln,finishedAt:yn,attempts:tt+1,baseUrl:l,outputs:G,quarantined:k,quarantinedReason:q}}catch(_n){wa(_n);let Bt=`Encountered fatal platform error while running test '${Re.name}': ${_n}`,yn=new Date,Pr=tt+1;_e.error({err:_n},Bt),S.error(Bt);let G={errorMessage:_n.message,errStack:_n.stack},bo={status:"FAILED",failureDetails:G,failureReason:"InternalPlatformError",finishedAt:yn};return await Z.finish({logger:_e,result:{status:"FAILED",results:[]}}),{...bo,results:[],parameters:oe,test:Re,filePath:Re.relativeFilePath,startedAt:M,lastAttemptStartedAt:ln,finishedAt:new Date,attempts:Pr,baseUrl:l,outputs:{},quarantined:k,quarantinedReason:q}}}throw new Error("This code should not be reachable")}function JO(t){for(let e of t.envs??[])if(e.default)return e.name}import{randomUUID as QO}from"crypto";var xr="assets";function ZO(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function eN(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var um=class{constructor(e,n,r,o){this.testId=e;this.testName=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${xr}/${n}.jpeg`,contents:r})}attachAfterScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${xr}/${n}.jpeg`,contents:r})}attachBeforeHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${xr}/${n}.html`,contents:r})}attachAfterHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${xr}/${n}.html`,contents:r})}heal(e){let{healType:n}=e;this.metadata.healMetadata={healType:n,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finish({status:eN(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},ba=class{constructor(e,n,r){this.testId=e;this.testName=n;this.diskStorage=r}children=[];finished=!1;async getScreenshot(e,n){return this.diskStorage.readFile(`${xr}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${xr}/${n}.html`)?.toString()}getParentStepIdChain(){return[]}async startStep(e){let{step:n}=e,r={step:n,status:"RUNNING",startedAt:new Date},o=new um(this.testId,this.testName,r,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finishInternal({status:ZO(e.status),finishedAt:e.finishedAt}))))}},mm=class{constructor(e,n,r,o,a){this.testId=e;this.testName=n;this.runAttemptId=r;this.metadata=o;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(n,null,2)})}attachConsoleLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(n,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:n,result:r}=e,o={...this.metadata,status:r.status,finishedAt:new Date,results:Ws(r.results,n),beforeResults:r.beforeResults?Ws(r.beforeResults,n):void 0,afterResults:r.afterResults?Ws(r.afterResults,n):void 0};await Promise.all(this.children.map(a=>a.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,n){return this.diskStorage.readFile(`${xr}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${xr}/${n}.html`)?.toString()}},pm=class{constructor(e,n,r,o,a){this.testId=e;this.testName=n;this.runId=r;this.metadata=o;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[CS]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let n={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(r=>r.finish({logger:e.logger,result:{status:n.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)}),this.diskStorage.close()}async startAttempt(){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=QO(),r={id:n,schemaVersion:le,runAttemptSchemaVersion:mh,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new mm(this.testId,this.testName,n,r,e);return this.children.push(o),o}},Ql=class t{constructor(e,n,r,o){this.orgId=e;this.runGroupId=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,n,r,o,a){let i={...o,id:n,trigger:Qt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Yn,labels:a??[]},s=new gi(r);return s.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)}),new t(e,n,i,s)}async finish(e){if(this.finished)return;this.finished=!0;let{status:n}=e,r={...this.metadata,status:n,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:r.status,finishedAt:r.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)})}async startRun(e){let n=this.diskStorage.createRunArchive(e.runId),r={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Yn,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};n.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new pm(e.testId,e.testName,e.runId,r,n);return this.children.push(o),o}};async function JT(t,e,n){if(n)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,a)=>(o[a.testId]=a.quarantinedReason,o),{})}catch(r){return t.warn({err:r},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function QT(t){let{logger:e,tests:n,yes:r,start:o,waitOn:a,client:i,debugDataStorage:s,billingReporter:c,flagStore:l,project:d,retriesOverride:u,urlOverride:m,envName:p,orgId:g,devicePixelRatio:h,customHeaders:f,testInputMatrix:b,reporter:y,include:E,exclude:v,labels:R,reporterDir:C=Vf,outputDir:x=qf,uploadResults:I=!1,waitOnTimeout:D=60,parallel:k,shardIndex:q=1,shardCount:$=1,regenerateGoldenFiles:_,gitMetadata:M,alwaysSaveCache:z,noCache:ue,ignoreQuarantine:oe,skipQuarantined:ke,onlyQuarantined:je,runGroupId:Vt}=t;o&&(e.info({orgId:g},`Executing start command: ${o}`),await UT(o,!1)),a&&(e.info({orgId:g},`Waiting for url: ${a} with timeout: ${D} seconds.`),await rN({resources:[a],interval:2500,timeout:D*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let tt=new Yo(d.config.ai?.agentConfig,{baseUrl:i.baseUrl,apiKey:i.apiKey,logger:e}),Z=ne(d,S),_e=await Xl({tests:n,momenticFiles:Z,yes:r,project:d,include:E,exclude:v,labels:R,logger:S}),Re=await JT(e,i,oe),{testsToSkip:ln,quarantinedTestsToSkip:Ir,testsToRun:Ta,quarantinedTestsToRun:tc}=zT({testDefinitions:_e,quarantinedTestReasons:Re,onlyQuarantined:je,skipQuarantined:ke});jT(ln),GT(Ir,Re);let _n=HT({testsToRun:Ta,quarantinedTestsToRun:tc,quarantinedTestReasons:Re,testInputMatrix:b}),Bt=aN({globalTestsToRunWithInputs:_n,shardIndex:q,shardCount:$});WT({logger:e,localTestsToRunWithInputs:Bt,parallel:k,shardCount:$,shardIndex:q});let yn=[],Pr=new Date,G=new Set,bo=async()=>{let gt=i.getAppUrl(),Qn=Vo({results:yn,startTime:Pr.getTime(),onFailed:Et=>{Ls(Et,Et.filePath)},getDisplayLine:Et=>{let Lr=`${Ye}- ${Et.filePath}${Et.failureRecoveryDetails?" [recovered] ":""}`;return Et.runId&&(Lr+=` ( link when uploaded: ${gt}/runs/${Et.runId} )`),Lr},entity:"test"}),Zn=yn.filter(Et=>!!Et.failureRecoveryDetails?.attempts);return Zn.length>0&&S.warn(`Our AI agent automatically prevented ${Zn.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),S.log(""),I?(S.success(`Test results have been saved to the folder ${x}. Uploading to Momentic Cloud...`),await sl({client:i,consoleLogger:S,resultsPath:x})):S.success(`Test results have been saved to the folder ${x}. Upload them to Momentic Cloud by running 'npx momentic results upload ${x}'.`),Qn};nN.existsSync(x)&&S.warn(`Output directory ${x} already exists, removing before test execution...`);let To=await Ql.start(g,Vt,x,M,R),Xn=e.child(To.loggerBindings||{}),Dn=[],Mr=async()=>{S.warn("SIGINT received. Stopping tests and printing latest results..."),await To.finish({logger:Xn,status:"CANCELLED"}),await bo(),await Promise.allSettled(Dn.map(gt=>gt())),process.exit(1)};process.once("SIGINT",Mr);let Jn={};for(let gt=0;gt<Bt.length;gt++){let Qn=Object.values(Jn);Qn.length===k&&await Promise.race(Qn.map(Lr=>Lr.promise));let Zn=Bt[gt],Et=`test-${gt}`;Jn[Et]={done:!1,promise:(async({inputs:Lr,quarantined:ow,quarantinedReason:aw,testDefinition:wo})=>{G.add({inputs:Lr});let Li=wo.relativeFilePath.includes("..")?wo.fullFilePath:wo.relativeFilePath;ei({status:"START",testLogRef:Li,getRunningTestsCount:()=>G.size,getTotalTestsCount:()=>Bt.length});let iw=setInterval(()=>ei({status:"RUN",testLogRef:Li,getRunningTestsCount:()=>G.size,getTotalTestsCount:()=>Bt.length}),5*60*1e3),fm=tN(),Sm=Xn.child({testId:wo.id,runId:fm});try{let Oi=await XT({testDefinition:wo,project:d,testInputs:Lr,quarantined:ow,quarantinedReason:aw,orgId:g,runId:fm,devicePixelRatio:h,apiClient:i,runGroupTracer:To,generator:tt,retriesOverride:u,urlOverride:m,envName:p,customHeaders:f,regenerateGoldenFiles:_,logUpdate:(Ni,sw)=>ei({status:Ni,testLogRef:Li,getRunningTestsCount:()=>G.size,getTotalTestsCount:()=>Bt.length,additionalText:sw}),runSigIntHandlers:Dn,logger:Sm,flagStore:l,gitMetadata:M,alwaysSaveCache:z,noCache:ue,billingReporter:c});ei({status:Oi.status,testLogRef:Li,getRunningTestsCount:()=>G.size,getTotalTestsCount:()=>Bt.length}),yn.push(Oi)}catch(Oi){let Ni=`Encountered unexpected fatal error when running test '${wo.name}': ${Oi.message}`;S.error(Ni),Sm.error(Ni)}finally{clearInterval(iw),Jn[Et].done=!0,delete Jn[Et]}})(Zn)}}await Promise.allSettled(Object.values(Jn).map(gt=>gt.promise));let Mi=yn.some(gt=>!gt.quarantined&&gt.status==="FAILED")?"FAILED":"PASSED";return await To.finish({logger:Xn,status:Mi}),process.off("SIGINT",Mr),y&&await DT(Xn,s,y,{projectConfigPath:d.configFilePath,suiteName:d.config.name,startedAt:Pr,finishedAt:new Date,runs:yn,testsToSkip:ln,quarantinedTestsToSkip:Ir,quarantinedTestReasons:Re},C),bo()}function oN(t,e,n){if(n>t.length&&(S.warn(`Shard count ${n} is greater than the number of tests ${t.length}! Some workers won't have any tests to run.`),n=Math.max(n,t.length),e>n))return[];let r=Math.floor((e-1)*(t.length/n)),o=Math.floor(e*(t.length/n));return t.sort().filter((i,s)=>s>=r&&s<o)}function aN({globalTestsToRunWithInputs:t,shardIndex:e,shardCount:n}){return n&&n>1?oN(t,e,n):t}rc||X.warn("Sentry is not enabled in this environment due to unsupported node version");var mN=process.argv.some(t=>t.includes("--log-level"))&&process.argv.some(t=>t.includes("debug")),gm=t=>{mN&&S.dimmed(t)},wt=new iN;wt.name("momentic").description("Momentic CLI").version(Yn);wt.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${wd.join(", ")}.`).action(async(t,e)=>{!e.all&&t.length===0&&(S.error("No browsers specified"),process.exit(1)),await Ih({rawBrowsers:t,force:e.force,all:e.all})});wt.addOption(new Ut("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",t=>{t==="debug"&&S.info("Enabling debug logging"),S.setMinLevel(t.toLowerCase())});wt.addOption(new Ut("--verbose","enable verbose logging")).on("option:verbose",()=>{X.enableConsoleLogs(),S.setMinLevel(20)});var hm=wt.command("checks").alias("check").description("Perform various project checks");hm.command("config").addOption(Wt).action(async t=>{dt({configFilePath:t.config})});hm.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(Wt).addOption(gT).action(async t=>{let e=dt({configFilePath:t.config});await eT({project:e,fix:t.fix})});hm.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Wt).action(async t=>{let e=dt({configFilePath:t.config});await tT({project:e})});var ew=wt.command("migrate").description("Migrate and upgrade tooling");ew.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(Wt).action(async t=>{let e=dt({configFilePath:t.config});await RT(e)});ew.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(Sn).addOption(Wt).addOption(fn).addOption(Ar).action(async t=>{!t.yes&&!await Tt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=dt({configFilePath:t.config}),n=new Ze({baseUrl:t.server,apiKey:t.apiKey,logger:X}),{orgId:r}=await n.getAuthInfo();await vT({project:e,orgId:r,apiClient:n}),process.exit(0)});wt.command("import").addOption(fn).addOption(Sn).addOption(Wt).addOption(Ar).addArgument(bT).action(async(t,e)=>{let{apiKey:n,server:r,config:o,yes:a}=e,i=dt({configFilePath:o}),s=new Ze({baseUrl:r,apiKey:n,logger:X});!t||t.length===0?await iT({client:s,project:i,skipPrompts:a}):await sT({client:s,project:i,paths:t,skipPrompts:a}),process.exit(0)});wt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Ut("--name <name>","Name of the project")).action(async t=>{S.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3979
+ `),S.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."),ec.existsSync(oa)&&(S.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 n={name:t.name??await Rh("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Gd};aa(n,oa),S.success(`Initialized Momentic project file at ${Zl.resolve(oa)}`)});wt.command("app").addOption(fn).addOption(Sn).addOption(Ar).addOption(Xu).addOption(Wt).addOption(Qu).addOption(Zu).action(async t=>{let{apiKey:e,yes:n,server:r,pixelRatio:o,disableCache:a,saveCache:i}=t,s=dt({configFilePath:t.config,nameFilter:void 0}),{errors:c}=await Dl({project:s,fix:!1});c>0&&(S.error(`Found ${c} errors`),S.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 l=new Ze({baseUrl:r,apiKey:e,logger:X});await vd({client:l,skipPrompts:n});let d=uN(import.meta.url),u=Zl.dirname(d),m=Zl.resolve(u,"..","static"),p=Zl.resolve(u,"..","assets"),g=o??im();sm(g),await Xb({momenticServerUrl:r,apiKey:e,serverPort:Fl,appPort:Fl,staticDir:m,assetsDir:p,devicePixelRatio:g,noCache:a,alwaysSaveCache:i,initialProject:s});let h=`http://localhost:${Fl}`;await dN(h)});var tw=wt.command("queue").description("Queue tests or suites to run on Momentic Cloud");tw.command("suites").description("Run one or more suites on Momentic Cloud").addOption(fn).addOption(Sn).addOption(Wu).addOption(Vu).addOption(Ar).addArgument(TT).addOption(Hl).addOption(zl).addOption(Bl).action(async(t,e)=>{let{apiKey:n,server:r,wait:o,waitTimeout:a,env:i,urlOverride:s}=e,c=Ul(e.customHeaders),l=new Ze({baseUrl:r,apiKey:n,logger:X});(!t||!Array.isArray(t)||!t.length)&&(S.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await l.getAuthInfo();await PT({client:l,orgId:d,wait:o,suitePaths:t,waitTimeout:a,env:i,urlOverride:s,customHeaders:c})});tw.command("tests").description("Run one or more tests on Momentic Cloud").addOption(fn).addOption(Sn).addOption(Ar).addOption(Bl).addOption(Ju).addOption(Hl).addOption(zl).addOption(new Ut("--all","Run all tests.").default(!1)).addOption(Wu).addOption(Vu).addArgument(yT).action(async(t,e)=>{let{all:n,apiKey:r,env:o,server:a,inputCsv:i,urlOverride:s,wait:c,waitTimeout:l,yes:d}=e,u=Ul(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||ec.existsSync(h))&&S.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 Ze({baseUrl:a,apiKey:r,logger:X}),{orgId:p}=await m.getAuthInfo(),g;i&&(g=await lm(i)),await MT({client:m,orgId:p,tests:t,all:n,customHeaders:u,env:o,urlOverride:s,wait:c,waitTimeout:l,testInputMatrix:g,yes:d}),process.exit(0)});var pN=wt.command("list").description("List test paths");pN.addOption(Wt).addOption(fa).addOption(Ku).addOption(Yu).addOption(new Ut("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(em).action(async(t,e)=>{let n=dt({configFilePath:e.config,nameFilter:e.filter}),r=ne(n,S),o=await Xl({tests:t,momenticFiles:r,yes:!0,project:n,include:e.include,exclude:e.exclude,labels:e.labels,logger:new Ya(40,{})});S.info(o.map(a=>a.relativeFilePath).join(`
3980
+ `)),process.exit(0)});var gN=wt.command("run").alias("test").description("Run tests on the local machine");gN.addOption(fn).addOption(Sn).addOption(Wt).addOption(fa).addOption(Ar).addOption(Bl).addOption(Ju).addOption(Qu).addOption(Zu).addOption(hT).addOption(fT).addOption(ST).addOption(zl).addOption(Hl).addOption(Xu).addOption(new Ut("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Ut("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Ut("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(vr)).addOption(new Ut("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(vr)).addOption(new Ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(vr)).addOption(new Ut("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Ut("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(cT).addOption(dT).addOption(qu).addOption(uT).addOption(pT).addOption(mT).addOption(Ku).addOption(Yu).addArgument(em).action(async(t,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let n=Ul(e.customHeaders),r=dt({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??r.config.parallel??1;ZT().length<o*2&&S.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${ZT().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),S.debug({projectName:r.config.name},"Identified project config");let{errors:a}=await Dl({project:r,fix:!1});a>0&&(S.error(`Found ${a} errors`),S.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 i=new Ze({baseUrl:e.server,apiKey:e.apiKey,logger:X});S.debug("Checking API key and dependencies");let{orgId:s,userId:c}=await vd({client:i,skipPrompts:e.yes});S.debug("API key check and browser installation complete");let l=new Ns(i),d=new ja,u=e.outputDir??r.config.outputDir,m=e.reporterDir??r.config.reporterDir,p=lN(),g=X.child({runGroupId:p,orgId:s,userId:c,cliVersion:Yn,trigger:"CLI"}),h=await fr(X,i,r);g.info(h,"Got local git metadata");let f=new hr(r.config),b;e.inputCsv&&(b=await lm(e.inputCsv));let y=e.pixelRatio??im();sm(y);try{(await QT({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:y,tests:t,project:r,client:i,debugDataStorage:d,billingReporter:l,flagStore:f,outputDir:u,uploadResults:e.uploadResults,reporterDir:m,customHeaders:n,envName:e.env,orgId:s,testInputMatrix:b,logger:g,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:h,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:p})).failed>0?process.exit(1):process.exit(0)}catch(E){S.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),S.error(E),process.exit(1)}});var hN=wt.command("apply").description("Apply an operation to local resources");hN.command("patch").addOption(fn).addOption(Sn).addOption(Wt).addOption(fa).addOption(Ar).addOption(new Ut("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Ut("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async t=>{let{apiKey:e,server:n,config:r,yes:o}=t,a=dt({configFilePath:r}),i=X,s=new Ze({baseUrl:n,apiKey:e,logger:i}),c=ne(a,S),l=c.tests[t.to]??Object.values(c.tests).find(u=>Ce(u.name)===t.to.trim());l||(S.error(`No test matching '${t.to}' could be found in the current project.`),process.exit(1));let d=await s.fetchTestFragment(t.from);await Qb({client:s,test:l,fragment:d,yes:o,entities:c,logger:X}),process.exit(0)});var nw=wt.command("results").description("Merge and upload test results.");nw.command("merge").description("Merge test results files.").addOption(qu).addArgument(wT).action(async(t,e)=>{let{outputDir:n}=e;n||(S.error("Output directory is required."),process.exit(1)),ec.existsSync(t)||(S.warn("Results path does not exist, skipping merge."),process.exit(0)),ec.existsSync(n)&&S.warn(`Output directory ${n} already exists, removing before merging...`),Jf(X,n,t)});nw.command("upload").description("Upload test results to Momentic cloud.").addOption(fn).addOption(Sn).addArgument(ET).action(async(t,e)=>{let{apiKey:n,server:r}=e,o=X,a=new Ze({baseUrl:r,apiKey:n,logger:o});await sl({consoleLogger:S,resultsPath:t,client:a}),process.exit(0)});var rw=wt.command("quarantine").description("Manage test quarantines");rw.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(fn).addOption(Sn).addOption(Wt).addOption(fa).addOption(tm).addArgument(nm).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:a}=e,i=X,s=dt({configFilePath:o}),c=new Ze({baseUrl:r,apiKey:n,logger:i}),l=await fr(X,c,s);await AT({test:t,reason:a,apiClient:c,project:s,logger:i,identity:l})});rw.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(fn).addOption(Sn).addOption(Wt).addOption(fa).addOption(tm).addArgument(nm).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:a}=e,i=X,s=dt({configFilePath:o}),c=new Ze({baseUrl:r,apiKey:n,logger:i}),l=await fr(X,c,s);await xT({test:t,reason:a,apiClient:c,project:s,logger:i,identity:l})});async function fN(){gm("Main program started"),await BT(X),gm("CLI version check complete");try{await wt.parseAsync(process.argv)}catch(t){let e={};try{e.playwrightVersion=sN("npx playwright --version").toString()}catch(n){X.error({err:n},"Error fetching debug information")}X.error({err:t,debugInfo:e},"Uncaught error in CLI"),X.flush(),wa(t,e),S.error(t),process.exit(1)}}cN.setMaxListeners(50);process.on("warning",t=>{X.warn({err:t},`Node warning received on CLI: ${t.message}`)});gm("CLI parsing setup complete");fN();
3983
3981
  //# sourceMappingURL=cli.js.map
3984
- //# debugId=5ae4a21c-85ec-580b-8627-11d5337ee5e5
3982
+ //# debugId=c9cae857-4881-55a6-b917-3c68fc9296b3